hexsha
stringlengths
40
40
size
int64
7
1.05M
ext
stringclasses
13 values
lang
stringclasses
1 value
max_stars_repo_path
stringlengths
4
269
max_stars_repo_name
stringlengths
5
108
max_stars_repo_head_hexsha
stringlengths
40
40
max_stars_repo_licenses
listlengths
1
9
max_stars_count
int64
1
191k
max_stars_repo_stars_event_min_datetime
stringlengths
24
24
max_stars_repo_stars_event_max_datetime
stringlengths
24
24
max_issues_repo_path
stringlengths
4
269
max_issues_repo_name
stringlengths
5
116
max_issues_repo_head_hexsha
stringlengths
40
40
max_issues_repo_licenses
listlengths
1
9
max_issues_count
int64
1
67k
max_issues_repo_issues_event_min_datetime
stringlengths
24
24
max_issues_repo_issues_event_max_datetime
stringlengths
24
24
max_forks_repo_path
stringlengths
4
269
max_forks_repo_name
stringlengths
5
116
max_forks_repo_head_hexsha
stringlengths
40
40
max_forks_repo_licenses
listlengths
1
9
max_forks_count
int64
1
105k
max_forks_repo_forks_event_min_datetime
stringlengths
24
24
max_forks_repo_forks_event_max_datetime
stringlengths
24
24
content
stringlengths
7
1.05M
avg_line_length
float64
1.21
330k
max_line_length
int64
6
990k
alphanum_fraction
float64
0.01
0.99
author_id
stringlengths
2
40
00083cc9417349cb253d289b375ad145301a2fc8
4,812
cc
C++
src/KeyTest.cc
nliao6622/QuantaDB-1
e5db80c7b9e9f5b3c2c6715ce77c56d56e4c4c94
[ "Apache-2.0" ]
12
2021-01-20T23:20:27.000Z
2021-12-10T12:14:26.000Z
src/KeyTest.cc
rodgarrison/RAMCloud
9aed8ace822c4aafef5501f418ab2b79450b7413
[ "0BSD" ]
null
null
null
src/KeyTest.cc
rodgarrison/RAMCloud
9aed8ace822c4aafef5501f418ab2b79450b7413
[ "0BSD" ]
2
2021-01-13T02:03:32.000Z
2022-01-20T17:26:55.000Z
/* Copyright (c) 2012-2016 Stanford University * * Permission to use, copy, modify, and distribute this software for any * purpose with or without fee is hereby granted, provided that the above * copyright notice and this permission notice appear in all copies. * * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR(S) DISCLAIM ALL WARRANTIES * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL AUTHORS BE LIABLE FOR * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */ #include "TestUtil.h" #include "Key.h" #include "Object.h" namespace RAMCloud { /** * Unit tests for Key. */ class KeyTest : public ::testing::Test { public: KeyTest() { } private: DISALLOW_COPY_AND_ASSIGN(KeyTest); }; TEST_F(KeyTest, constructor_fromLog) { Buffer buffer; Key key(12, "blah", 5); Buffer dataBuffer; Object object(key, NULL, 0, 0, 0, dataBuffer); object.assembleForLog(buffer); Key key2(LOG_ENTRY_TYPE_OBJ, buffer); EXPECT_EQ(12U, key2.getTableId()); EXPECT_STREQ("blah", reinterpret_cast<const char*>(key2.getStringKey())); EXPECT_EQ(5U, key2.getStringKeyLength()); ObjectTombstone tombstone(object, 5, 0); buffer.reset(); tombstone.assembleForLog(buffer); Key key3(LOG_ENTRY_TYPE_OBJTOMB, buffer); EXPECT_EQ(12U, key3.getTableId()); EXPECT_STREQ("blah", reinterpret_cast<const char*>(key3.getStringKey())); EXPECT_EQ(5U, key3.getStringKeyLength()); EXPECT_FALSE(key.hash); EXPECT_FALSE(key2.hash); EXPECT_FALSE(key3.hash); EXPECT_THROW(Key(LOG_ENTRY_TYPE_SEGHEADER, buffer), FatalError); } TEST_F(KeyTest, constructor_fromBuffer) { Buffer buffer; buffer.appendExternal("woops", 6); Key key(48, buffer, 0, 6); EXPECT_EQ(48U, key.getTableId()); EXPECT_EQ("woops", string(reinterpret_cast<const char*>( key.getStringKey()))); EXPECT_EQ(6U, key.getStringKeyLength()); Key key2(59, buffer, 1, 3); EXPECT_EQ(59U, key2.getTableId()); EXPECT_EQ("oop", string(reinterpret_cast<const char*>( key2.getStringKey()), 3)); EXPECT_EQ(3U, key2.getStringKeyLength()); EXPECT_FALSE(key.hash); EXPECT_FALSE(key2.hash); } TEST_F(KeyTest, constructor_fromVoidPointer) { Key key(74, "na-na-na-na", 12); EXPECT_EQ(74U, key.getTableId()); EXPECT_EQ("na-na-na-na", string(reinterpret_cast<const char*>( key.getStringKey()))); EXPECT_EQ(12U, key.getStringKeyLength()); EXPECT_FALSE(key.hash); } TEST_F(KeyTest, getHash) { Key key(82, "hey-hey-hey", 12); EXPECT_FALSE(key.hash); EXPECT_EQ(0x889d47d556739eebUL, key.getHash()); EXPECT_TRUE(key.hash); EXPECT_EQ(0x889d47d556739eebUL, key.getHash()); } TEST_F(KeyTest, getHash_static) { Key key(82, "goodbye", 8); Key key1(83, "goodbye", 8); Key key2(83, "goodbye", 7); EXPECT_NE(key, key1); EXPECT_NE(key, key2); EXPECT_NE(key1, key2); } /* * Ensure that #RAMCloud::HashTable::hash() generates hashes using the full * range of bits. */ TEST_F(KeyTest, getHash_UsesAllBits) { uint64_t observedBits = 0UL; srand(1); for (uint32_t i = 0; i < 50; i++) { uint64_t input1 = generateRandom(); uint64_t input2 = generateRandom(); observedBits |= Key::getHash(input1, &input2, sizeof(input2)); } EXPECT_EQ(~0UL, observedBits); } TEST_F(KeyTest, getStringKey) { const char *keyString = reinterpret_cast<const char*>( Key(8274, "hi", 3).getStringKey()); EXPECT_EQ("hi", string(keyString)); } TEST_F(KeyTest, getStringKeyLength) { EXPECT_EQ(3, Key(8274, "hi", 3).getStringKeyLength()); } TEST_F(KeyTest, getTableId) { EXPECT_EQ(8274U, Key(8274, "hi", 3).getTableId()); } TEST_F(KeyTest, operatorEquals_and_operatorNotEquals) { Key key(82, "fun", 4); Key key2(82, "fun", 4); EXPECT_EQ(key, key); EXPECT_EQ(key, key2); Key key3(83, "fun", 4); EXPECT_NE(key, key3); Key key4(83, "fun", 3); EXPECT_NE(key, key4); EXPECT_NE(key2, key4); EXPECT_NE(key3, key4); } TEST_F(KeyTest, toString) { EXPECT_EQ("<tableId: 27, key: \"ascii key\", " "keyLength: 9, hash: 0xe415add6e960d438>", Key(27, "ascii key", 9).toString()); EXPECT_EQ("<tableId: 814, key: \"binary key\\xaa\\x0a\", " "keyLength: 12, hash: 0xe972fd5603c67b0e>", Key(814, "binary key\xaa\x0a", 12).toString()); } } // namespace RAMCloud
28.814371
77
0.656899
nliao6622
0008e813424aec01d42bb2f95fd4ddb1289151dc
30,963
cpp
C++
Source/System/Math/Algebra/Quaternion.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
2
2020-01-09T07:48:24.000Z
2020-01-09T07:48:26.000Z
Source/System/Math/Algebra/Quaternion.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
Source/System/Math/Algebra/Quaternion.cpp
arian153/Engine-5
34f85433bc0a74a7ebe7da350d3f3698de77226e
[ "MIT" ]
null
null
null
#include "Quaternion.hpp" #include "Matrix33.hpp" #include "Vector3.hpp" #include "..//Utility/Utility.hpp" #include <ostream> #include "../Utility/VectorDef.hpp" #include <sstream> namespace Engine5 { Quaternion::Quaternion(Real r, Real i, Real j, Real k) : r(r), i(i), j(j), k(k) { } Quaternion::Quaternion(const Vector3& from, const Vector3& to) { Set(from, to); } Quaternion::Quaternion(const Vector3& vector) { Set(vector); } Quaternion::Quaternion(const Matrix33& rotation_matrix) { Set(rotation_matrix); } Quaternion::Quaternion(const AxisRadian& axis_radian) { Set(axis_radian); } Quaternion::Quaternion(const EulerAngle& euler_angle) { Set(euler_angle); } Quaternion::Quaternion(const Vector3& axis, Real radian) { Set(axis, radian); } Quaternion::Quaternion(const Quaternion& rhs) : r(rhs.r), i(rhs.i), j(rhs.j), k(rhs.k) { } Quaternion::~Quaternion() { } void Quaternion::Set(Real _r, Real _i, Real _j, Real _k) { r = _r; i = _i; j = _j; k = _k; } void Quaternion::Set(const Vector3& from, const Vector3& to) { // get axis of rotation Vector3 axis = from.CrossProduct(to); // get scaled cos of angle between vectors and set initial quaternion Set(from.DotProduct(to), axis.x, axis.y, axis.z); // quaternion at this point is ||from||*||to||*( cos(theta), r*sin(theta) ) // normalize to remove ||from||*||to|| factor SetNormalize(); // quaternion at this point is ( cos(theta), r*sin(theta) ) // what we want is ( cos(theta/2), r*sin(theta/2) ) // set up for half angle calculation r += 1.0f; // now when we normalize, we'll be dividing by sqrt(2*(1+cos(theta))), which is // what we want for r*sin(theta) to give us r*sin(theta/2) // w will become // 1+cos(theta) // ---------------------- // sqrt(2*(1+cos(theta))) // which simplifies to cos(theta/2) // before we normalize, check if vectors are opposing if (r <= Math::EPSILON) { //rotate pi radians around orthogonal vector take cross product with x axis if (from.z * from.z > from.x * from.x) Set(0.0f, 0.0f, from.z, -from.y); //or take cross product with z axis else Set(0.0f, from.y, -from.x, 0.0f); } //s = sqrtf(2*(1+cos(theta))) //Real s = sqrtf(2.0f * r); Real norm = sqrtf(r * r + i * i + j * j + k * k); //r = s * 0.5f; i = axis.x / s; j = axis.y / s; k = axis.z / s; //s is equal to norm. so just normalize again to get rotation quaternion. SetNormalize(); } void Quaternion::Set(const Vector3& axis, Real radian) { // if axis of rotation is zero vector, just set to identity quat Real length = axis.LengthSquared(); if (Math::IsZero(length) == true) { SetIdentity(); return; } // take half-angle Real half_rad = radian * 0.5f; Real sin_theta = sinf(half_rad); Real cos_theta = cosf(half_rad); Real scale = sin_theta / sqrtf(length); r = cos_theta; i = scale * axis.x; j = scale * axis.y; k = scale * axis.z; } void Quaternion::Set(const Vector3& vector) { r = 0.0f; i = vector.x; j = vector.y; k = vector.z; } void Quaternion::Set(const Matrix33& rotation_matrix) { Real trace = rotation_matrix.Trace(); if (trace > 0.0f) { Real s = sqrtf(trace + 1.0f); r = s * 0.5f; Real multiplier = 0.5f / s; i = (rotation_matrix(2, 1) - rotation_matrix(1, 2)) * multiplier; j = (rotation_matrix(0, 2) - rotation_matrix(2, 0)) * multiplier; k = (rotation_matrix(1, 0) - rotation_matrix(0, 1)) * multiplier; } else { size_t _i = 0; if (rotation_matrix(1, 1) > rotation_matrix(0, 0)) { _i = 1; } if (rotation_matrix(2, 2) > rotation_matrix(_i, _i)) { _i = 2; } size_t _j = (_i + 1) % 3; size_t _k = (_j + 1) % 3; Real s = sqrtf(rotation_matrix(_i, _i) - rotation_matrix(_j, _j) - rotation_matrix(_k, _k) + 1.0f); (*this)[_i] = 0.5f * s; Real multiplier = 0.5f / s; r = (rotation_matrix(_k, _j) - rotation_matrix(_j, _k)) * multiplier; (*this)[_j] = (rotation_matrix(_j, _i) + rotation_matrix(_i, _j)) * multiplier; (*this)[_k] = (rotation_matrix(_k, _i) + rotation_matrix(_i, _k)) * multiplier; } } void Quaternion::Set(const AxisRadian& axis_radian) { // if axis of rotation is zero vector, just set to identity quat Real length = axis_radian.axis.LengthSquared(); if (Math::IsZero(length) == true) { SetIdentity(); return; } // take half-angle Real half_rad = axis_radian.radian * 0.5f; Real sin_theta = sinf(half_rad); Real cos_theta = cosf(half_rad); Real scale = sin_theta / sqrtf(length); r = cos_theta; i = scale * axis_radian.axis.x; j = scale * axis_radian.axis.y; k = scale * axis_radian.axis.z; } void Quaternion::Set(const EulerAngle& euler_angle) { Real roll = euler_angle.x_rotation * .5f; Real pitch = euler_angle.y_rotation * .5f; Real yaw = euler_angle.z_rotation * .5f; Real cos_roll = cosf(roll); Real sin_roll = sinf(roll); Real cos_pitch = cosf(pitch); Real sin_pitch = sinf(pitch); Real cos_yaw = cosf(yaw); Real sin_yaw = sinf(yaw); r = cos_roll * cos_pitch * cos_yaw + sin_roll * sin_pitch * sin_yaw; i = sin_roll * cos_pitch * cos_yaw - cos_roll * sin_pitch * sin_yaw; j = cos_roll * sin_pitch * cos_yaw + sin_roll * cos_pitch * sin_yaw; k = cos_roll * cos_pitch * sin_yaw - sin_roll * sin_pitch * cos_yaw; } void Quaternion::Set(const Quaternion& rhs) { r = rhs.r; i = rhs.i; j = rhs.j; k = rhs.k; } void Quaternion::SetNormalize() { Real d = r * r + i * i + j * j + k * k; // Check for zero length quaternion, //and use the no-rotation quaternion in that case. if (Math::IsZero(d) == true) { r = 1.0f; return; } Real multiplier = Math::InvSqrt(d);//1.f / sqrtf(d); r *= multiplier; i *= multiplier; j *= multiplier; k *= multiplier; } void Quaternion::SetClean() { if (Math::IsZero(r)) r = 0.0f; if (Math::IsZero(i)) i = 0.0f; if (Math::IsZero(j)) j = 0.0f; if (Math::IsZero(k)) k = 0.0f; } void Quaternion::SetZero() { r = i = j = k = 0.0f; } void Quaternion::SetIdentity() { r = 1.0f; i = j = k = 0.0f; } void Quaternion::SetConjugate() { i = -i; j = -j; k = -k; } void Quaternion::SetInverse() { Real norm = r * r + i * i + j * j + k * k; if (Math::IsZero(norm)) { //E5_ASSERT(false, "inverse the zero quaternion"); return; } Real inverse_norm = 1.0f / norm; r = inverse_norm * r; i = -inverse_norm * i; j = -inverse_norm * j; k = -inverse_norm * k; } Real Quaternion::Norm() const { return sqrtf(r * r + i * i + j * j + k * k); } Real Quaternion::NormSquared() const { return (r * r + i * i + j * j + k * k); } bool Quaternion::IsZero() const { return Math::IsZero(r * r + i * i + j * j + k * k); } bool Quaternion::IsUnit() const { return Math::IsZero(1.0f - (r * r + i * i + j * j + k * k)); } bool Quaternion::IsIdentity() const { return Math::IsZero(1.0f - r) && Math::IsZero(i) && Math::IsZero(j) && Math::IsZero(k); } bool Quaternion::IsEqual(const Quaternion& rhs) const { if (Math::IsEqual(r, rhs.r) == false) return false; if (Math::IsEqual(i, rhs.i) == false) return false; if (Math::IsEqual(j, rhs.j) == false) return false; if (Math::IsEqual(k, rhs.k) == false) return false; return true; } bool Quaternion::IsNotEqual(const Quaternion& rhs) const { if (Math::IsEqual(r, rhs.r) == false) return true; if (Math::IsEqual(i, rhs.i) == false) return true; if (Math::IsEqual(j, rhs.j) == false) return true; if (Math::IsEqual(k, rhs.k) == false) return true; return false; } bool Quaternion::IsLostAxis() const { return Math::IsZero(1.0f - r); } Vector3 Quaternion::ToVector() const { return Vector3(i, j, k); } Matrix33 Quaternion::ToMatrix() const { Matrix33 result; if (IsUnit()) { Real xs = i + i; Real ys = j + j; Real zs = k + k; Real wx = r * xs; Real wy = r * ys; Real wz = r * zs; Real xx = i * xs; Real xy = i * ys; Real xz = i * zs; Real yy = j * ys; Real yz = j * zs; Real zz = k * zs; result.data[0] = 1.0f - (yy + zz); result.data[1] = xy - wz; result.data[2] = xz + wy; result.data[3] = xy + wz; result.data[4] = 1.0f - (xx + zz); result.data[5] = yz - wx; result.data[6] = xz - wy; result.data[7] = yz + wx; result.data[8] = 1.0f - (xx + yy); } return result; } AxisRadian Quaternion::ToAxisRadian() const { Real radian = 2.0f * acosf(r); Real length = sqrtf(1.0f - (r * r)); Vector3 axis = Math::Vector3::Y_AXIS; if (Math::IsZero(length) == false) { length = 1.0f / length; axis.Set(i * length, j * length, k * length); } return AxisRadian(axis, radian); } EulerAngle Quaternion::ToEulerAngle() const { Real roll = atan2f(2.f * (r * i + j * k), 1.f - (2.f * (i * i + j * j))); Real pitch; Real sin_pitch = 2.f * (r * j - k * i); if (fabsf(sin_pitch) >= 1) pitch = copysignf(Math::HALF_PI, sin_pitch); // use 90 degrees if out of range else pitch = asinf(sin_pitch); Real yaw = atan2f(2.f * (r * k + i * j), 1.f - (2.f * (j * j + k * k))); return EulerAngle(roll, pitch, yaw); } Quaternion Quaternion::Conjugate() const { return Quaternion(r, -i, -j, -k); } Quaternion Quaternion::Inverse() const { Real norm = r * r + i * i + j * j + k * k; // if we're the zero quaternion, just return if (Math::IsZero(norm)) return Quaternion(r, i, j, k); Real inverse_norm = 1.0f / norm; return Quaternion(inverse_norm * r, -inverse_norm * i, -inverse_norm * j, -inverse_norm * k); } Real Quaternion::DotProduct(const Quaternion& quaternion) const { return (r * quaternion.r + i * quaternion.i + j * quaternion.j + k * quaternion.k); } Vector3 Quaternion::Rotate(const Vector3& vector) const { if (IsUnit() == true) { Real v_multiplier = 2.0f * (i * vector.x + j * vector.y + k * vector.z); Real c_multiplier = 2.0f * r; Real p_multiplier = c_multiplier * r - 1.0f; return Vector3( p_multiplier * vector.x + v_multiplier * i + c_multiplier * (j * vector.z - k * vector.y), p_multiplier * vector.y + v_multiplier * j + c_multiplier * (k * vector.x - i * vector.z), p_multiplier * vector.z + v_multiplier * k + c_multiplier * (i * vector.y - j * vector.x)); } //"Rotate non-unit quaternion" return Vector3(); } Vector3 Quaternion::RotateVector(const Vector3& vector) const { Quaternion inverse = Inverse(); Quaternion given_vector(0.0f, vector.x, vector.y, vector.z); //calculate qpq^-1 Quaternion result = ((*this) * given_vector) * inverse; return Vector3(result.i, result.j, result.k); } Quaternion Quaternion::Multiply(const Quaternion& rhs) const { return Quaternion( r * rhs.r - i * rhs.i - j * rhs.j - k * rhs.k, r * rhs.i + i * rhs.r + j * rhs.k - k * rhs.j, r * rhs.j + j * rhs.r + k * rhs.i - i * rhs.k, r * rhs.k + k * rhs.r + i * rhs.j - j * rhs.i); } void Quaternion::AddRotation(const Vector3& axis, Real radian) { Quaternion quaternion(AxisRadian(axis, radian)); *this = quaternion * (*this); SetNormalize(); } void Quaternion::AddRotation(const Quaternion& quaternion) { (*this) = quaternion * (*this); SetNormalize(); } void Quaternion::AddRadian(Real radian) { Real curr_rad = 2.0f * acosf(r); Real length = sqrtf(1.0f - (r * r)); Vector3 axis = Math::Vector3::Y_AXIS; Real half_rad = (curr_rad + radian) * 0.5f; Real sin_theta = sinf(half_rad); Real cos_theta = cosf(half_rad); if (Math::IsZero(length) == false) { length = 1.0f / length; axis.Set(i * length, j * length, k * length); r = cos_theta; i = sin_theta * axis.x; j = sin_theta * axis.y; k = sin_theta * axis.z; } } void Quaternion::ChangeAxis(const Vector3& axis) { Real radian = 2.0f * acosf(r); Real length = sqrtf(1.0f - (r * r)); Real axis_length = axis.LengthSquared(); if (Math::IsZero(length) == false && Math::IsZero(axis_length) == false) { Real half_rad = (radian) * 0.5f; Real sin_theta = sinf(half_rad); Real cos_theta = cosf(half_rad); axis_length = 1.0f / axis_length; Real scale = sin_theta / sqrtf(axis_length); r = cos_theta; i = scale * axis.x; j = scale * axis.y; k = scale * axis.z; } } Quaternion Quaternion::operator-() const { return Quaternion(-r, -i, -j, -k); } Quaternion& Quaternion::operator=(const Quaternion& rhs) { if (this != &rhs) { r = rhs.r; i = rhs.i; j = rhs.j; k = rhs.k; } return *this; } bool Quaternion::operator==(const Quaternion& rhs) const { if (Math::IsEqual(r, rhs.r) == false) return false; if (Math::IsEqual(i, rhs.i) == false) return false; if (Math::IsEqual(j, rhs.j) == false) return false; if (Math::IsEqual(k, rhs.k) == false) return false; return true; } bool Quaternion::operator!=(const Quaternion& rhs) const { if (Math::IsEqual(r, rhs.r) == false) return true; if (Math::IsEqual(i, rhs.i) == false) return true; if (Math::IsEqual(j, rhs.j) == false) return true; if (Math::IsEqual(k, rhs.k) == false) return true; return false; } Real Quaternion::operator[](size_t _i) const { return (&i)[_i]; } Real& Quaternion::operator[](size_t _i) { return (&i)[_i]; } Quaternion Quaternion::operator*(const Quaternion& rhs) const { return Quaternion( r * rhs.r - i * rhs.i - j * rhs.j - k * rhs.k, r * rhs.i + i * rhs.r + j * rhs.k - k * rhs.j, r * rhs.j + j * rhs.r + k * rhs.i - i * rhs.k, r * rhs.k + k * rhs.r + i * rhs.j - j * rhs.i); } Quaternion& Quaternion::operator*=(const Quaternion& rhs) { auto q = *this; r = q.r * rhs.r - q.i * rhs.i - q.j * rhs.j - q.k * rhs.k; i = q.r * rhs.i + q.i * rhs.r + q.j * rhs.k - q.k * rhs.j; j = q.r * rhs.j + q.j * rhs.r + q.k * rhs.i - q.i * rhs.k; k = q.r * rhs.k + q.k * rhs.r + q.i * rhs.j - q.j * rhs.i; return *this; } Quaternion Quaternion::operator*(const Vector3& vector) const { return Quaternion( - i * vector.x - j * vector.y - k * vector.z, r * vector.x + j * vector.z - k * vector.y, r * vector.y + k * vector.x - i * vector.z, r * vector.z + i * vector.y - j * vector.x); } Matrix33 Quaternion::operator*(const Matrix33& matrix) const { Matrix33 result; if (IsUnit()) { result.data[0] = (1.0f - 2.0f * (j * j + k * k)) * matrix.data[0] + 2.0f * (i * j - r * k) * matrix.data[3] + 2.0f * (i * k + r * j) * matrix.data[6]; result.data[1] = (1.0f - 2.0f * (j * j + k * k)) * matrix.data[1] + 2.0f * (i * j - r * k) * matrix.data[4] + 2.0f * (i * k + r * j) * matrix.data[7]; result.data[2] = (1.0f - 2.0f * (j * j + k * k)) * matrix.data[2] + 2.0f * (i * j - r * k) * matrix.data[5] + 2.0f * (i * k + r * j) * matrix.data[8]; result.data[3] = 2.0f * (i * j + r * k) * matrix.data[0] + (1.0f - 2.0f * (i * i + k * k)) * matrix.data[3] + 2.0f * (j * k - r * i) * matrix.data[6]; result.data[4] = 2.0f * (i * j + r * k) * matrix.data[1] + (1.0f - 2.0f * (i * i + k * k)) * matrix.data[4] + 2.0f * (j * k - r * i) * matrix.data[7]; result.data[5] = 2.0f * (i * j + r * k) * matrix.data[2] + (1.0f - 2.0f * (i * i + k * k)) * matrix.data[5] + 2.0f * (j * k - r * i) * matrix.data[8]; result.data[6] = 2.0f * (i * k - r * j) * matrix.data[0] + 2.0f * (j * k + r * i) * matrix.data[3] + (1.0f - 2.0f * (i * i + j * j)) * matrix.data[6]; result.data[7] = 2.0f * (i * k - r * j) * matrix.data[1] + 2.0f * (j * k + r * i) * matrix.data[4] + (1.0f - 2.0f * (i * i + j * j)) * matrix.data[7]; result.data[8] = 2.0f * (i * k - r * j) * matrix.data[2] + 2.0f * (j * k + r * i) * matrix.data[5] + (1.0f - 2.0f * (i * i + j * j)) * matrix.data[8]; } return result; } Quaternion Quaternion::operator+(const Quaternion& rhs) const { return Quaternion(r + rhs.r, i + rhs.i, j + rhs.j, k + rhs.k); } Quaternion& Quaternion::operator+=(const Quaternion& rhs) { r += rhs.r; i += rhs.i; j += rhs.j; k += rhs.k; return *this; } Quaternion Quaternion::operator-(const Quaternion& rhs) const { return Quaternion(r - rhs.r, i - rhs.i, j - rhs.j, k - rhs.k); } Quaternion& Quaternion::operator-=(const Quaternion& rhs) { r -= rhs.r; i -= rhs.i; j -= rhs.j; k -= rhs.k; return *this; } Quaternion Quaternion::operator*(Real scalar) const { return Quaternion(r * scalar, i * scalar, j * scalar, k * scalar); } Quaternion& Quaternion::operator*=(Real scalar) { r *= scalar; i *= scalar; j *= scalar; k *= scalar; return *this; } Quaternion operator*(const Vector3& vector, const Quaternion& quaternion) { return Quaternion( -vector.x * quaternion.i - vector.y * quaternion.j - vector.z * quaternion.k, +vector.x * quaternion.r + vector.y * quaternion.k - vector.z * quaternion.j, +vector.y * quaternion.r + vector.z * quaternion.i - vector.x * quaternion.k, +vector.z * quaternion.r + vector.x * quaternion.j - vector.y * quaternion.i); } Matrix33 operator*(const Matrix33& matrix, const Quaternion& quaternion) { Matrix33 result; if (quaternion.IsUnit()) { result.data[0] = matrix.data[0] * (1.0f - 2.0f * (quaternion.j * quaternion.j + quaternion.k * quaternion.k)) + 2.0f * matrix.data[1] * (quaternion.i * quaternion.j + quaternion.r * quaternion.k) + 2.0f * matrix.data[2] * (quaternion.i * quaternion.k - quaternion.r * quaternion.j); result.data[1] = matrix.data[1] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.k * quaternion.k)) + 2.0f * matrix.data[0] * (quaternion.i * quaternion.j - quaternion.r * quaternion.k) + 2.0f * matrix.data[2] * (quaternion.j * quaternion.k + quaternion.r * quaternion.i); result.data[2] = matrix.data[2] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.j * quaternion.j)) + 2.0f * matrix.data[0] * (quaternion.i * quaternion.k + quaternion.r * quaternion.j) + 2.0f * matrix.data[1] * (quaternion.j * quaternion.k - quaternion.r * quaternion.i); result.data[3] = matrix.data[3] * (1.0f - 2.0f * (quaternion.j * quaternion.j + quaternion.k * quaternion.k)) + 2.0f * matrix.data[4] * (quaternion.i * quaternion.j + quaternion.r * quaternion.k) + 2.0f * matrix.data[5] * (quaternion.i * quaternion.k - quaternion.r * quaternion.j); result.data[4] = matrix.data[4] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.k * quaternion.k)) + 2.0f * matrix.data[3] * (quaternion.i * quaternion.j - quaternion.r * quaternion.k) + 2.0f * matrix.data[5] * (quaternion.j * quaternion.k + quaternion.r * quaternion.i); result.data[5] = matrix.data[5] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.j * quaternion.j)) + 2.0f * matrix.data[3] * (quaternion.i * quaternion.k + quaternion.r * quaternion.j) + 2.0f * matrix.data[4] * (quaternion.j * quaternion.k - quaternion.r * quaternion.i);; result.data[6] = matrix.data[6] * (1.0f - 2.0f * (quaternion.j * quaternion.j + quaternion.k * quaternion.k)) + 2.0f * matrix.data[7] * (quaternion.i * quaternion.j + quaternion.r * quaternion.k) + 2.0f * matrix.data[8] * (quaternion.i * quaternion.k - quaternion.r * quaternion.j); result.data[7] = matrix.data[7] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.k * quaternion.k)) + 2.0f * matrix.data[6] * (quaternion.i * quaternion.j - quaternion.r * quaternion.k) + 2.0f * matrix.data[8] * (quaternion.j * quaternion.k + quaternion.r * quaternion.i); result.data[8] = matrix.data[8] * (1.0f - 2.0f * (quaternion.i * quaternion.i + quaternion.j * quaternion.j)) + 2.0f * matrix.data[6] * (quaternion.i * quaternion.k + quaternion.r * quaternion.j) + 2.0f * matrix.data[7] * (quaternion.j * quaternion.k - quaternion.r * quaternion.i); } return result; } Quaternion Quaternion::Identity() { return Quaternion(); } Quaternion Conjugate(const Quaternion& quaternion) { return quaternion.Conjugate(); } Quaternion Inverse(const Quaternion& quaternion) { return quaternion.Inverse(); } Real DotProduct(const Quaternion& quat1, const Quaternion& quat2) { return quat1.DotProduct(quat2); } Quaternion LinearInterpolation(const Quaternion& start, const Quaternion& end, Real t) { Real cos_theta = start.DotProduct(end); // initialize result Quaternion result = t * end; // if "angle" between quaternions is less than 90 degrees if (cos_theta >= Math::EPSILON) { // use standard interpolation result += (1.0f - t) * start; } else { // otherwise, take the shorter path result += (t - 1.0f) * start; } return result; } Quaternion SphericalLinearInterpolation(const Quaternion& start, const Quaternion& end, Real t) { // get cosine of "angle" between quaternions Real cos_theta = start.DotProduct(end); Real start_interp, end_interp; // if "angle" between quaternions is less than 90 degrees if (cos_theta >= Math::EPSILON) { // if angle is greater than zero if ((1.0f - cos_theta) > Math::EPSILON) { // use standard slerp Real theta = acosf(cos_theta); Real inv_sin_theta = 1.0f / sinf(theta); start_interp = sinf((1.0f - t) * theta) * inv_sin_theta; end_interp = sinf(t * theta) * inv_sin_theta; } // angle is close to zero else { // use linear interpolation start_interp = 1.0f - t; end_interp = t; } } // otherwise, take the shorter route else { // if angle is less than 180 degrees if ((1.0f + cos_theta) > Math::EPSILON) { // use slerp w/negation of start quaternion Real theta = acosf(-cos_theta); Real inv_sin_theta = 1.0f / sinf(theta); start_interp = sinf((t - 1.0f) * theta) * inv_sin_theta; end_interp = sinf(t * theta) * inv_sin_theta; } // angle is close to 180 degrees else { // use lerp w/negation of start quaternion start_interp = t - 1.0f; end_interp = t; } } Quaternion result = start_interp * start + end_interp * end; return result; } Quaternion SwingTwistInterpolation(const Quaternion& start, const Quaternion& end, const Vector3& twist_axis, Real t) { Quaternion delta_rotation = end * start.Inverse(); Quaternion swing_full; Quaternion twist_full; Vector3 r = Vector3(delta_rotation.i, delta_rotation.j, delta_rotation.k); // singularity: rotation by 180 degree if (r.LengthSquared() < Math::EPSILON) { Vector3 rotated_twist_axis = delta_rotation.Rotate(twist_axis); Vector3 swing_axis = twist_axis.CrossProduct(rotated_twist_axis); if (swing_axis.LengthSquared() > Math::EPSILON) { Real swing_radian = Radian(twist_axis, rotated_twist_axis); swing_full = Quaternion(swing_axis, swing_radian); } else { // more singularity: // rotation axis parallel to twist axis swing_full = Quaternion::Identity(); // no swing } // always twist 180 degree on singularity twist_full = Quaternion(twist_axis, Math::PI); } else { // meat of swing-twist decomposition Vector3 p = r.ProjectionTo(twist_axis); twist_full = Quaternion(delta_rotation.r, p.x, p.y, p.z); twist_full.SetNormalize(); swing_full = delta_rotation * twist_full.Inverse(); } Quaternion swing = SphericalLinearInterpolation(Quaternion::Identity(), swing_full, t); Quaternion twist = SphericalLinearInterpolation(Quaternion::Identity(), twist_full, t); return twist * swing; } Quaternion operator*(Real scalar, const Quaternion& quaternion) { return Quaternion(scalar * quaternion.r, scalar * quaternion.i, scalar * quaternion.j, scalar * quaternion.k); } std::ostream& operator<<(std::ostream& os, const Quaternion& rhs) { if (rhs.IsUnit() == true) { Real radian = 2.0f * acosf(rhs.r); Real length = sqrtf(1.0f - (rhs.r * rhs.r)); Vector3 axis = Math::Vector3::Y_AXIS; if (Math::IsZero(length) == false) { length = 1.0f / length; axis.Set(rhs.i * length, rhs.j * length, rhs.k * length); } Real degree = Math::RadiansToDegrees(radian); //os << std::setprecision(3); os << "[cos(" << degree << ") + sin(" << degree << ") * (" << axis.x << "i + " << axis.y << "j + " << axis.z << "k)]"; //os << std::setprecision(std::ios_base::precision); } else { os << "[" << rhs.r << ", " << rhs.i << ", " << rhs.j << ", " << rhs.k << "]"; } return os; } std::wstringstream& operator<<(std::wstringstream& os, const Quaternion& rhs) { if (rhs.IsUnit() == true) { Real radian = 2.0f * acosf(rhs.r); Real length = sqrtf(1.0f - (rhs.r * rhs.r)); Vector3 axis = Math::Vector3::Y_AXIS; if (Math::IsZero(length) == false) { length = 1.0f / length; axis.Set(rhs.i * length, rhs.j * length, rhs.k * length); } Real degree = Math::RadiansToDegrees(radian); //os << std::setprecision(3); os << "[cos(" << degree << ") + sin(" << degree << ") * (" << axis.x << "i + " << axis.y << "j + " << axis.z << "k)]"; //os << std::setprecision(std::ios_base::precision); } else { os << "[" << rhs.r << ", " << rhs.i << ", " << rhs.j << ", " << rhs.k << "]"; } return os; } }
36.003488
162
0.489907
arian153
000b585f9671e7db56d035f0878a003200f77418
5,157
hpp
C++
Nostra Utils/src/header/nostrautils/core/Version.hpp
Lehks/NostraUtils
ef1b2d492a1358775752a2a7621c714d86bf96b2
[ "MIT" ]
10
2018-01-07T01:00:11.000Z
2021-09-16T14:08:45.000Z
NostraUtils/Nostra Utils/src/header/nostrautils/core/Version.hpp
Lehks/NostraEngine
0d610dcd97ba482fd8f183795140c38728c3a6b3
[ "MIT" ]
107
2018-04-06T10:15:47.000Z
2018-09-28T07:13:46.000Z
NostraUtils/Nostra Utils/src/header/nostrautils/core/Version.hpp
Lehks/NostraEngine
0d610dcd97ba482fd8f183795140c38728c3a6b3
[ "MIT" ]
null
null
null
#ifndef NOU_CORE_VERSION_HPP #define NOU_CORE_VERSION_HPP #include "nostrautils/core/StdIncludes.hpp" #include "nostrautils/core/Utils.hpp" /** \file core/Version.hpp \author Lukas Reichmann \version 1.0.0 \since 1.0.0 \brief A file that contains the nostra::utils::core::Version struct. \see nostra::utils::core::Version */ namespace NOU::NOU_CORE { /** \brief A class that wraps around the macros from the StdIncludes.hpp that generate versions (like NOU_MAKE_VERSION). However, this struct does not have problems with overflowing the single parts. */ struct Version final { public: /** \brief The type of a version (which also serves as the type for the parts). */ using VersionType = decltype(NOU_MAKE_VERSION(0, 0, 0)); private: /** \brief The version itself. */ VersionType m_version; public: /** \param version The version to import. \brief Imports a version that was previously created using NOU_MAKE_VERSION. */ constexpr Version(VersionType version); /** \param major The major part of the version. \param minor The minor part of the version. \param patch The patch part of the version. \brief Constructs a new version. \details Constructs a new version. This constructor will clamp the values of the parts to avoid overflows. The maximum values of the parts are determined by the NOU_VERSION_*_MAX macros. */ constexpr Version(VersionType major, VersionType minor, VersionType patch); /** \return The full version. \brief Returns the full version as generated by NOU_MAKE_VERSION. */ constexpr VersionType getRaw() const; /** \return The major part of the version. \brief Returns the major part of the version. */ constexpr VersionType getMajor() const; /** \return The minor part of the version. \brief Returns the major part of the version. */ constexpr VersionType getMinor() const; /** \return The patch part of the version. \brief Returns the major part of the version. */ constexpr VersionType getPatch() const; /** \param other The version to compare this one to. \return True, if this version is bigger than \p other, false if not. \brief Checks if this version is bigger than \p other. */ constexpr boolean operator > (const Version &other) const; /** \param other The version to compare this one to. \return True, if this version is bigger than or equal to \p other, false if not. \brief Checks if this version is bigger than or equal to \p other. */ constexpr boolean operator >= (const Version &other) const; /** \param other The version to compare this one to. \return True, if this version is smaller than \p other, false if not. \brief Checks if this version is smaller than \p other. */ constexpr boolean operator < (const Version &other) const; /** \param other The version to compare this one to. \return True, if this version is smaller than or equal to \p other, false if not. \brief Checks if this version is smaller than or equal to \p other. */ constexpr boolean operator <= (const Version &other) const; /** \param other The version to compare this one to. \return True, if this version is equal to \p other, false if not. \brief Checks if this version is equal to \p other. */ constexpr boolean operator == (const Version &other) const; /** \param other The version to compare this one to. \return True, if this version is unequal to \p other, false if not. \brief Checks if this version is unequal to \p other. */ constexpr boolean operator != (const Version &other) const; }; constexpr Version::Version(VersionType version) : m_version(version) {} constexpr Version::Version(VersionType major, VersionType minor, VersionType patch) : m_version(NOU_MAKE_VERSION(clamp(major, static_cast<VersionType>(0), NOU_VERSION_MAJOR_MAX), clamp(minor, static_cast<VersionType>(0), NOU_VERSION_MINOR_MAX), clamp(patch, static_cast<VersionType>(0), NOU_VERSION_PATCH_MAX))) {} constexpr typename Version::VersionType Version::getRaw() const { return m_version; } constexpr typename Version::VersionType Version::getMajor() const { return NOU_VERSION_MAJOR(m_version); } constexpr typename Version::VersionType Version::getMinor() const { return NOU_VERSION_MINOR(m_version); } constexpr typename Version::VersionType Version::getPatch() const { return NOU_VERSION_PATCH(m_version); } constexpr boolean Version::operator > (const Version &other) const { return getRaw() > other.getRaw(); } constexpr boolean Version::operator >= (const Version &other) const { return getRaw() >= other.getRaw(); } constexpr boolean Version::operator < (const Version &other) const { return getRaw() < other.getRaw(); } constexpr boolean Version::operator <= (const Version &other) const { return getRaw() <= other.getRaw(); } constexpr boolean Version::operator == (const Version &other) const { return getRaw() == other.getRaw(); } constexpr boolean Version::operator != (const Version &other) const { return getRaw() != other.getRaw(); } } #endif
25.156098
105
0.714951
Lehks
00117fd642dc8a5d1aa39f6f6dbc0b2e1b1e4695
12,157
cpp
C++
src/display_module.cpp
oskrs111/diy-co2-monitior
ca72bf613421732216da5af8359749af52bb49c3
[ "MIT" ]
8
2020-11-03T09:51:59.000Z
2021-09-20T05:01:42.000Z
src/display_module.cpp
oskrs111/diy-co2-monitior
ca72bf613421732216da5af8359749af52bb49c3
[ "MIT" ]
2
2020-11-29T08:11:41.000Z
2021-01-24T19:21:00.000Z
src/display_module.cpp
oskrs111/diy-co2-monitior
ca72bf613421732216da5af8359749af52bb49c3
[ "MIT" ]
3
2020-11-19T12:06:42.000Z
2021-02-05T10:31:57.000Z
/* Copyright 2020 Oscar Sanz Llopis 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 <stdint.h> #include "module_common.h" #include "config_module.h" #include "sensor_module.h" #include "display_module.h" #include "display_module_fonts.h" #include "display_module_icons.h" #include "SSD1306Wire.h" #if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE char debug_string[256]; #endif static struct display_preferences* preferences = 0x00; static SSD1306Wire display(0x3c, DISPLAY_SDA_PIN, DISPLAY_SCL_PIN); static struct st_display_data display_data; static char display_string[64]; static uint16_t *span_average = 0x00; void display_module_init() { preferences = &config_module_get_preferences()->display; memset(&display_data, 0x00, sizeof(display_data)); display_module_historical_init(); display.init(); display.setI2cAutoInit(true); display.flipScreenVertically(); display_module_draw_splash(); display_module_set_battery(100); display_module_set_ipaddress((char*)"000.000"); display_module_set_ppm(0); display_module_set_warming(0); display_module_set_reading(0); display_module_set_calibrating(0); display_module_set_ble(0); Serial.write("> display_module_init() => Done!\r\n"); } void display_module_historical_init() { uint16_t t = 0; span_average = new uint16_t[preferences->average_interval]; for(t = 1; t < (DISPLAY_MODULE_HISTORICAL_SPAN - 1); t++) { display_data.historical.historical_values[t].p_next = &display_data.historical.historical_values[t+1]; display_data.historical.historical_values[t].p_prev = &display_data.historical.historical_values[t-1]; display_data.historical.historical_values[t]._pos = t; display_data.historical.historical_values[t].value = 0x00; } display_data.historical.historical_values[0].p_next = &display_data.historical.historical_values[1]; display_data.historical.historical_values[0].p_prev = &display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)]; display_data.historical.historical_values[0]._pos = 0; display_data.historical.historical_values[0].value = 0x00; display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)].p_next = &display_data.historical.historical_values[0]; display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)].p_prev = &display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 2)]; display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)]._pos = (DISPLAY_MODULE_HISTORICAL_SPAN - 1); display_data.historical.historical_values[(DISPLAY_MODULE_HISTORICAL_SPAN - 1)].value = 0x00; display_data.historical.p_ppm_in = &display_data.historical.historical_values[0]; display_data.historical.ppm_length = 0; display_data.historical.ppm_max = SENSOR_MIN_PPM; display_data.historical.ppm_min = SENSOR_MAX_PPM; display_data.historical.ppm_maxd = SENSOR_MAX_PPM; display_data.historical.ppm_mind = SENSOR_MIN_PPM; } void display_module_clear() { display.clear(); } void display_module_update() { display.display(); } void display_module_set_ppm(uint16_t ppm) { display_data.ppm = ppm; display_module_push_historical(ppm); } void display_module_set_temperature(float temp) { display_data.temperature = temp; } void display_module_push_historical(uint16_t ppm) { static uint16_t span_average_count = 0; struct st_ppm_value *p = 0x00; uint16_t t = 0x00; if((ppm == SENSOR_MIN_PPM) || (ppm == SENSOR_MAX_PPM)) { #if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE sprintf(&debug_string[0],"> Skip value= %d\r\n",ppm); Serial.write(&debug_string[0]); return; #endif } if(span_average_count < preferences->average_interval) { span_average[span_average_count] = ppm; span_average_count++; #if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE sprintf(&debug_string[0],"> Push value= %d, cnt= %d\r\n",ppm, span_average_count); Serial.write(&debug_string[0]); #endif } else { display_data.historical.p_ppm_in->value = display_module_get_average(&span_average[0], preferences->average_interval); #if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE sprintf(&debug_string[0],"> Store value [%04d]= %d, len=%d\r\n",display_data.historical.p_ppm_in->_pos, display_data.historical.p_ppm_in->value, display_data.historical.ppm_length); Serial.write(&debug_string[0]); #endif display_data.historical.p_ppm_in = display_data.historical.p_ppm_in->p_next; if(display_data.historical.ppm_length < DISPLAY_MODULE_HISTORICAL_SPAN) { display_data.historical.ppm_length++; } span_average_count = 0; display_data.historical.ppm_max = SENSOR_MIN_PPM; display_data.historical.ppm_min = SENSOR_MAX_PPM; p = display_data.historical.p_ppm_in->p_prev; for(t = 0; t < DISPLAY_MODULE_HISTORICAL_SPAN; t++) { if(p->value != 0) { display_module_max_min_update(p->value); } p = p->p_prev; } } } uint16_t display_module_get_average(uint16_t *data, uint16_t length) { uint32_t sum = 0; uint16_t t = 0; for(t = 0; t < length; t++) { sum += data[t]; } return (uint16_t)(sum/(uint32_t)length); } void display_module_set_battery(uint16_t battery) { display_data.battery = battery; } void display_module_set_ipaddress(char* ipaddress) { if(strlen(&ipaddress[0]) < sizeof(display_data.ipaddress)) { memcpy(&display_data.ipaddress, &ipaddress[0], strlen(&ipaddress[0])); display_data.ipaddress[strlen(&ipaddress[0])] = 0; } display_module_draw_ipaddress(); } void display_module_draw_splash() { display.clear(); display.drawXbm(23,0,logo_image_width,logo_image_height,&logo_image[0]); display.setFont(ArialMT_Plain_10); display.drawString(23,54,"diy-co2-monitor"); display.display(); } void display_module_draw_ppm() { char *format = (char*)"%04d"; if(display_data.ppm < 1000) { format = (char*)" %03d"; } sprintf(&display_string[0],&format[0],display_data.ppm); display.setFont(Roboto_Black_24); display.drawString(0,0, &display_string[0]); display.setFont(ArialMT_Plain_10); display.drawString(60,0,"ppm"); } void display_module_draw_ppm_graph() { #define VERTICAL_START 38 #define VERTICAL_HEIGHT 30 struct st_ppm_value *p = 0x00; uint16_t t = 0x00; uint16_t max = display_data.historical.ppm_max; uint16_t min = display_data.historical.ppm_min; uint8_t x_pos = 0x00; uint8_t y_pos = 0x00; uint8_t step_size = 0x00; uint8_t length = 0x00; if(display_data.historical.ppm_length == 0x00) { return; } if((max - min) < VERTICAL_HEIGHT) { max = (((max + min)/2)+VERTICAL_HEIGHT); min = (((max + min)/2)-VERTICAL_HEIGHT); } else { max += (VERTICAL_HEIGHT/4); min -= (VERTICAL_HEIGHT/4); } /**< Update the main maxd/mind values in order to show same values in web dashboard*/ display_data.historical.ppm_maxd = max; display_data.historical.ppm_mind = min; step_size = ((max - min) / VERTICAL_HEIGHT); step_size = (step_size == 0x00)?1:step_size; x_pos = display_data.historical.ppm_length; p = display_data.historical.p_ppm_in->p_prev; for(t = display_data.historical.ppm_length; t > 0; t--) { length = ((p->value - min)/ step_size); y_pos = (VERTICAL_START + (VERTICAL_HEIGHT - length)); display.drawVerticalLine(x_pos, y_pos, length); #if 0 sprintf(&debug_string[0],"> Draw pos=%d, value= %d, x= %d, y= %d, ln= %d, st= %d, max= %d, min= %d\r\n", p->_pos, p->value, x_pos, y_pos, length, step_size, max, min ); Serial.write(&debug_string[0]); #endif p = p->p_prev; x_pos--; } display.drawHorizontalLine(0, 63, 64); display.drawVerticalLine(0, VERTICAL_START, 32); display.setFont(ArialMT_Plain_10); sprintf(&display_string[0],"%d", max); display.drawString(65,24,&display_string[0]); sprintf(&display_string[0],"%d", min); display.drawString(65,54,&display_string[0]); } void display_module_max_min_update(uint16_t ppm) { if(ppm > display_data.historical.ppm_max) { display_data.historical.ppm_max = ppm; } if(ppm < display_data.historical.ppm_min) { display_data.historical.ppm_min = ppm; } #if DEBUG_TRACES_ENABLE && DISPLAY_TRACES_ENABLE sprintf(&debug_string[0],"> Update M/m ppm= %d, max= %d, min= %d\r\n", ppm, display_data.historical.ppm_max, display_data.historical.ppm_min); Serial.write(&debug_string[0]); #endif } void display_module_draw_battery() { sprintf(&display_string[0],"%d", display_data.ppm); display.setFont(ArialMT_Plain_10); display.drawString(104,0,&display_string[0]); display.drawRect(102, 0, 22, 12); display.drawRect(124, 2, 4, 8); } void display_module_draw_ipaddress() { display.setFont(ArialMT_Plain_10); display.drawString(95,0,&display_data.ipaddress[0]); display.drawString(89,0,"<"); } void display_module_set_warming(uint8_t state) { if(state > 0 ) { display.drawCircle(120, 40, 6); } else { display.fillCircle(120, 40, 6); } } void display_module_set_ble(uint8_t state) { display.drawRect(112, 48, 16, 16); } void display_module_set_reading(uint8_t state) { if(state > 0 ) { display.drawCircle(120, 57, 6); } else { display.fillCircle(120, 57, 6); } } void display_module_set_calibrating(uint8_t state) { display.drawRect(112, 32, 16, 16); } void display_module_defaults(struct display_preferences* preferences) { preferences->average_interval = DISPLAY_MODULE_AVERAGE_INTERVAL_DEFAULT; } char* display_module_historical_2_json() { static char buffer[((DISPLAY_MODULE_HISTORICAL_SPAN * 5) + 64)]; struct st_ppm_value *p = 0x00; char* j = &buffer[0]; memset(j, 0x00, sizeof(buffer)); j += sprintf(j,"\"historical\":{\"span\":%d, \"interval\":%d, \"max\":%d, \"min\":%d, \"data\":[", DISPLAY_MODULE_HISTORICAL_SPAN, DISPLAY_MODULE_AVERAGE_INTERVAL_DEFAULT, display_data.historical.ppm_maxd, display_data.historical.ppm_mind); p = display_data.historical.p_ppm_in->p_prev; for(uint16_t t = display_data.historical.ppm_length; t > 0; t--) { j += sprintf(j,"%d,", p->value); p = p->p_prev; } if(display_data.historical.ppm_length > 0x00) j--; /**< To remove the last ',' */ j += sprintf(j,"]}"); return &buffer[0]; /**< [0] position is the most recent measure */ }
34.24507
189
0.681254
oskrs111
00144f6fe0033d2f64866ceca60fcb1b78d5fad7
5,672
hpp
C++
backend/compiler.hpp
mark-sed/ebe
6280704e377e55b89aa5125942cc710b5e73209e
[ "MIT" ]
1
2022-02-22T21:42:28.000Z
2022-02-22T21:42:28.000Z
backend/compiler.hpp
mark-sed/ebe
6280704e377e55b89aa5125942cc710b5e73209e
[ "MIT" ]
null
null
null
backend/compiler.hpp
mark-sed/ebe
6280704e377e55b89aa5125942cc710b5e73209e
[ "MIT" ]
null
null
null
/** * @file compiler.hpp * @author Marek Sedlacek * @date July 2021 * @copyright Copyright 2021 Marek Sedlacek. All rights reserved. * * @brief Abstract data for all processing units * * Every input processing unit should extend processor class * so that all needed information and methods are present in it. */ #ifndef _COMPILER_HPP_ #define _COMPILER_HPP_ #include <iostream> #include <unistd.h> #include "exceptions.hpp" /** * Namespace holding resources for error and warning handling */ namespace Error { /** * Namespace for terminal colorization */ namespace Colors { extern const char * NO_COLOR; extern const char * BLACK; extern const char * GRAY; extern const char * RED; extern const char * LIGHT_RED; extern const char * GREEN; extern const char * LIGHT_GREEN; extern const char * BROWN; extern const char * YELLOW; extern const char * BLUE; extern const char * LIGHT_BLUE; extern const char * PURPLE; extern const char * LIGHT_PURPLE; extern const char * CYAN; extern const char * LIGHT_CYAN; extern const char * LIGHT_GRAY; extern const char * WHITE; extern const char * RESET; /** * Checks if stderr is redirected to a file * @return true if stderr is redirected */ inline bool is_cerr_redirected() { static bool initialized(false); static bool is_redir; if (!initialized) { initialized = true; is_redir = ttyname(fileno(stderr)) == nullptr; } return is_redir; } /** * Returns passes in color in case the output is not redirected. * If output is redirected then this returns empty string ("") * @param color Colors to sanitize * @return color if output if not redirected otherwise empty string */ inline const char *colorize(const char * color) { // Check if stderr is redirected if(is_cerr_redirected()) { return ""; } return color; } /** * Resets set color to default terminal settings * @return Colors::RESET if output is not redirected otherwise empty string */ inline const char *reset() { // Check if stderr is redirected if(is_cerr_redirected()) { return ""; } return Colors::RESET; } } /** * Possible enum codes * @note When new code is added its string name should be added also to the get_code_name function */ enum ErrorCode { NO_ERROR = 0, ///< When no error occurred but program had to exit (otherwise return code would be for some error 0) UNKNOWN, ///< Unknown error (shouldn't be really used) INTERNAL, ///< Internal compiler error (such as unable to allocate memory) FILE_ACCESS, ///< Problem opening/writing/working with users files (not internal config files) ARGUMENTS, ///< Problem with user arguments SYNTACTIC, ///< Syntactical error SEMANTIC, ///< Semantical error UNIMPLEMENTED, ///< Problems with instruction RUNTIME, ///< Runtime errors VERSION ///< For when the version is not sufficient }; /** * Returns name of ErrorCode * @param code Error code * @return Error code's name */ const char *get_code_name(ErrorCode code); /** * Function for when fatal error occurres * Prints error information passed in and exits with passed in code * @param code Code of an error that occurred * @param msg Info message to be printed for the user * @param exc Exception that might hava accompanied this error or nullptr * @param exit If true (default), then after the message is printed program exits with code */ void error(Error::ErrorCode code, const char *msg, Exception::EbeException *exc=nullptr, bool exit=true); void error(Error::ErrorCode code, const char *file, long line, long column, const char *msg, Exception::EbeException *exc=nullptr, bool exit=true); /** * Prints warning to std::cerr * @param msg Message to print */ void warning(const char *msg); /** * Exits program with passed in code * @param code Error code to exit with */ [[noreturn]] void exit(Error::ErrorCode code); } /** * Base class for all compiler components * @note Every compilation pass should extend this class */ class Compiler { public: const char *unit_name; ///< Name of the compilation unit (needed for error printing) protected: /** * Constructor * @param unit_name Name of unit which extends this class */ Compiler(const char *unit_name); /** * Prints error to the user and exits * @param code Error code to exit with * @param file Name of the file in which this error occurred * @param line Line at which the error occurred * @param column Column at which the error occurred * @param msg Message to be printed to the user * @param exc Exception that might hava accompanied this error or nullptr * @param exit If true (default), then after the message is printed program exits with code */ void error(Error::ErrorCode code, const char *file, long line, long column, const char *msg, Exception::EbeException *exc=nullptr, bool exit=true); }; #endif//_COMPILER_HPP_
33.56213
124
0.618124
mark-sed
00149f7fb5fe229d3262a881e551925b3849842b
1,209
cpp
C++
pr1/zadaci/Zadatak16/Source.cpp
jasarsoft/fit-src
d9b963be3afbd4494de9d0289c947b0a41ad91d7
[ "MIT" ]
null
null
null
pr1/zadaci/Zadatak16/Source.cpp
jasarsoft/fit-src
d9b963be3afbd4494de9d0289c947b0a41ad91d7
[ "MIT" ]
null
null
null
pr1/zadaci/Zadatak16/Source.cpp
jasarsoft/fit-src
d9b963be3afbd4494de9d0289c947b0a41ad91d7
[ "MIT" ]
null
null
null
#include <iostream> using namespace std; /* Prepravite prethodni program tako da program racuna i ispisuje zapreminu V i povrsinu cilindra (varijabla Pcil). - Koristite dodatnu varijablu M za povrsinu omotaca i varijablu O za obim kruga. - Koristite konstantu Pi. Matematicke formule koje vam mogu pomoci su date u nastavku: P(cilindar) = 2P(krug) + M M = O(krug) * H O(krug) = 2*r*PI P(krug) = r^2 * PI */ int main() { const float PI = 3.14F; int poluprecnik, visina; //cilindar float krug, povrsina, zapremina, omotac, obim; //cilindra cout << "Unesite poluprecnik cilindra: "; cin >> poluprecnik; cout << "Unesite visinu cilindra: "; cin >> visina; obim = 2 * poluprecnik * PI; //O(krug) = 2*r*PI omotac = obim * visina; //M = O(krug) * H krug = poluprecnik * poluprecnik * PI; //P(krug) = r^2 * PI povrsina = 2 * krug + omotac; //P(cilindar) = 2P(krug) + M zapremina = povrsina * visina; cout << "Obim cilindra: " << obim << endl; cout << "Omotac cilindra: " << omotac << endl; cout << "Povrsina kruga cilindra: " << krug << endl; cout << "Povrsina cilindra: " << povrsina << endl; cout << "Zapremina cilindra: " << zapremina << endl; system("pause"); return 0; }
28.116279
82
0.652605
jasarsoft
0016f0ba712c1efb9c9a9a6d094b8d5ac0268237
36,801
cpp
C++
ugene/src/corelibs/U2Core/src/gobjects/AnnotationTableObject.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Core/src/gobjects/AnnotationTableObject.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
ugene/src/corelibs/U2Core/src/gobjects/AnnotationTableObject.cpp
iganna/lspec
c75cba3e4fa9a46abeecbf31b5d467827cf4fec0
[ "MIT" ]
null
null
null
/** * UGENE - Integrated Bioinformatics Tools. * Copyright (C) 2008-2012 UniPro <ugene@unipro.ru> * http://ugene.unipro.ru * * 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 "AnnotationTableObject.h" #include "GObjectTypes.h" #include <U2Core/Timer.h> #include <U2Core/DNATranslation.h> #include <U2Core/TextUtils.h> #include <U2Core/U2SafePoints.h> #include <U2Core/DNASequenceObject.h> #include <U2Core/AppContext.h> #include <U2Core/U2FeatureUtils.h> #include <U2Core/U2OpStatusUtils.h> #include <U2Core/U2DbiRegistry.h> #include <U2Core/U2FeatureDbi.h> #include <QtCore/QBitArray> // for Qt::escape #include <QtGui/QTextDocument> namespace U2 { Annotation::Annotation(SharedAnnotationData _d): obj(NULL), d(_d), caseAnnotation(false) { } Annotation::~Annotation() { //todo: add state checks? } bool Annotation::isValidQualifierName(const QString& s) { return !s.isEmpty() && s.length() < 20 && TextUtils::fits(TextUtils::QUALIFIER_NAME_CHARS, s.toAscii().data(), s.length()); } bool Annotation::isValidQualifierValue(const QString& s) { Q_UNUSED(s); //todo: check whitespaces! return true; } bool Annotation::isValidAnnotationName(const QString& n) { //todo: optimize if (n.isEmpty() || n.length() > 100) { return false; } QBitArray validChars = TextUtils::ALPHA_NUMS; validChars['_'] = true; validChars['-'] = true; validChars[' '] = true; validChars['\''] = true; validChars['*'] = true; QByteArray name = n.toLocal8Bit(); if (!TextUtils::fits(validChars, name.constData(), name.size())) { return false; } if (name[0] == ' ' || name[name.size() - 1] == ' ') { return false; } return true; } static QList<U2CigarToken> parceCigar(const QString& cigar) { QList<U2CigarToken> cigarTokens; QRegExp rx("(\\d+)(\\w)"); int pos = 0; while ((pos = rx.indexIn(cigar, pos)) != -1) { if (rx.numCaptures() != 2) { break; } int count = rx.cap(1).toInt(); QString cigarChar = rx.cap(2); if (cigarChar == "M") { cigarTokens.append( U2CigarToken( U2CigarOp_M, count) ); } else if (cigarChar == "I") { cigarTokens.append( U2CigarToken( U2CigarOp_I, count)); } else if (cigarChar == "D") { cigarTokens.append( U2CigarToken( U2CigarOp_D, count)); } else if (cigarChar == "X") { cigarTokens.append( U2CigarToken( U2CigarOp_X, count)); } else { break; } pos += rx.matchedLength(); } return cigarTokens; } static QString getAlignmentTip(const QString& ref, const QList<U2CigarToken>& tokens, int maxVisibleSymbols) { QString alignmentTip; if (tokens.size() == 0) { return ref; } int pos = 0; QList<int> mismatchPositions; foreach (const U2CigarToken& t, tokens) { if (t.op == U2CigarOp_M) { alignmentTip += ref.mid(pos, t.count); pos += t.count; } else if (t.op == U2CigarOp_X) { alignmentTip += ref.mid(pos, t.count); mismatchPositions.append(pos); pos += t.count; } else if (t.op == U2CigarOp_I) { // gap already present in sequence? pos += t.count; } } if (alignmentTip.length() > maxVisibleSymbols) { alignmentTip = alignmentTip.left(maxVisibleSymbols); alignmentTip += " ... "; } // make mismatches bold int offset = 0; static const int OFFSET_LEN = QString("<b></b>").length(); foreach(int pos, mismatchPositions) { int newPos = pos + offset; if (newPos + 1 >= alignmentTip.length() ) { break; } alignmentTip.replace(newPos, 1, QString("<b>%1</b>").arg( alignmentTip.at(newPos) ) ); offset += OFFSET_LEN; } return alignmentTip; } QString Annotation::getQualifiersTip(int maxRows, U2SequenceObject* seq, DNATranslation* comlTT, DNATranslation* aminoTT) const { QString tip; int rows = 0; const int QUALIFIER_VALUE_CUT = 40; QString cigar, ref; if (d->qualifiers.size() != 0) { tip += "<nobr>"; bool first = true; foreach (const U2Qualifier& q, d->qualifiers) { if (++rows > maxRows) { break; } if (q.name == QUALIFIER_NAME_CIGAR) { cigar = q.value; } else if (q.name == QUALIFIER_NAME_SUBJECT) { ref = q.value; continue; } QString val = q.value; if(val.length() > QUALIFIER_VALUE_CUT) { val = val.left(QUALIFIER_VALUE_CUT) + " ..."; } if (first) { first = false; } else { tip += "<br>"; } tip += "<b>" + Qt::escape(q.name) + "</b> = " + Qt::escape(val); } tip += "</nobr>"; } if (cigar.size() > 0 && ref.size() > 0) { QList<U2CigarToken> tokens = parceCigar(cigar); QString alignmentTip = getAlignmentTip(ref, tokens, QUALIFIER_VALUE_CUT); tip += "<br><b>Reference</b> = " + alignmentTip; rows++; } bool canShowSeq = true; int seqLen = seq ? seq->getSequenceLength() : 0; foreach(const U2Region& r, d->getRegions()) { if (r.endPos() > seqLen) { canShowSeq = false; } } if (seq && rows <= maxRows && (getStrand().isCompementary() || comlTT != NULL) && canShowSeq) { QVector<U2Region> loc = getRegions(); if (getStrand().isCompementary()) { qStableSort(loc.begin(), loc.end(), qGreater<U2Region>()); } QString seqVal; QString aminoVal; bool complete = true; for (int i = 0; i < loc.size(); i++) { if (!seqVal.isEmpty()) { seqVal += "^"; } if (!aminoVal.isEmpty()) { aminoVal += "^"; } const U2Region& r = loc.at(i); int len = qMin(int(r.length), QUALIFIER_VALUE_CUT - seqVal.length()); if (len != r.length) { complete = false; } if (getStrand().isCompementary() && comlTT != NULL) { QByteArray ba = seq->getSequenceData(U2Region(r.endPos() - len, len)); comlTT->translate(ba.data(), len); TextUtils::reverse(ba.data(), len); seqVal += QString::fromLocal8Bit(ba.data(), len); if (aminoTT!=NULL) { int aminoLen = aminoTT->translate(ba.data(), len); aminoVal += QString::fromLocal8Bit(ba.data(), aminoLen); } } else { QByteArray ba = seq->getSequenceData(U2Region(r.startPos, len)); seqVal += QString::fromLocal8Bit(ba.constData(), len); if (aminoTT!=NULL) { int aminoLen = aminoTT->translate(ba.data(), len); aminoVal += QString::fromLocal8Bit(ba.data(), aminoLen); } } if (seqVal.length() >= QUALIFIER_VALUE_CUT) { complete &= (i == loc.size() - 1); break; } } if(!complete || seqVal.length() > QUALIFIER_VALUE_CUT) { seqVal = seqVal.left(QUALIFIER_VALUE_CUT) + " ..."; } if(!complete || aminoVal.length() > QUALIFIER_VALUE_CUT) { aminoVal = aminoVal.left(QUALIFIER_VALUE_CUT) + " ..."; } if (!tip.isEmpty()) { tip+="<br>"; } assert(seqVal.length() > 0); tip += "<nobr><b>" + U2::AnnotationTableObject::tr("Sequence") + "</b> = " + Qt::escape(seqVal) + "</nobr>"; rows++; if (rows <= maxRows && aminoTT!=NULL) { tip+="<br>"; tip += "<nobr><b>" + U2::AnnotationTableObject::tr("Translation") + "</b> = " + Qt::escape(aminoVal) + "</nobr>"; } } return tip; } QStringList Annotation::getFullGroupsNames() const { QStringList res; foreach(AnnotationGroup* g, getGroups()) { res << g->getGroupPath(); } return res; } bool Annotation::annotationLessThan(Annotation *first, Annotation *second) { QListIterator<AnnotationGroup *> firstIterator(first->getGroups()); QListIterator<AnnotationGroup *> secondIterator(second->getGroups()); while(firstIterator.hasNext() && secondIterator.hasNext()) { if (firstIterator.peekNext()->getGroupName() < secondIterator.peekNext()->getGroupName()) { return true; } if (firstIterator.peekNext()->getGroupName() > secondIterator.peekNext()->getGroupName()) { return false; } firstIterator.next(); secondIterator.next(); } if (secondIterator.hasNext()) { if(first->getAnnotationName() < secondIterator.peekNext()->getGroupName()) { return true; } if(first->getAnnotationName() > secondIterator.peekNext()->getGroupName()) { return false; } secondIterator.next(); } if (firstIterator.hasNext()) { if(firstIterator.peekNext()->getGroupName() < second->getAnnotationName()) { return true; } if(firstIterator.peekNext()->getGroupName() > second->getAnnotationName()) { return false; } firstIterator.next(); } if (secondIterator.hasNext()) { return true; } if (firstIterator.hasNext()) { return false; } return (first->getAnnotationName() < second->getAnnotationName()); } const QVector<U2Qualifier>& Annotation::getQualifiers() const { return d->qualifiers; } void Annotation::setAnnotationName(const QString& newName) { if (newName == d->name) { return; } SAFE_POINT(!newName.isEmpty(), "Annotation name is empty!",); QString oldName = d->name; d->name = newName; if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_NameChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::setLocationOperator(U2LocationOperator op) { if (op == getLocationOperator()) { return; } d->setLocationOperator(op); if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::setStrand(U2Strand s) { if (s == getStrand()) { return; } d->setStrand(s); if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::addLocationRegion(const U2Region& reg) { d->location->regions.append(reg); if (obj!=NULL) { obj->setModified(true); AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::addQualifier(const U2Qualifier& q) { d->qualifiers.append(q); if (obj!=NULL) { obj->setModified(true); QualifierModification md(AnnotationModification_QualifierAdded, this, q); obj->emit_onAnnotationModified(md); } } void Annotation::removeQualifier(const U2Qualifier& q) { assert(d->qualifiers.contains(q)); int idx = d->qualifiers.indexOf(q); d->qualifiers.remove(idx); if (obj!=NULL) { obj->setModified(true); QualifierModification md(AnnotationModification_QualifierRemoved, this, q); obj->emit_onAnnotationModified(md); } } void Annotation::setLocation(const U2Location& location ) { d->location = location; if (obj!=NULL) { AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } void Annotation::replaceRegions(const QVector<U2Region>& regions) { if (d->location->regions == regions) { return; } d->location->regions = regions; if (obj!=NULL) { AnnotationModification md(AnnotationModification_LocationChanged, this); obj->emit_onAnnotationModified(md); } } bool Annotation::isCaseAnnotation() const { return caseAnnotation; } void Annotation::setCaseAnnotation(bool caseAnnotation) { this->caseAnnotation = caseAnnotation; } ////////////////////////////////////////////////////////////////////////// // Group AnnotationGroup::AnnotationGroup(AnnotationTableObject* p, const QString& _name, AnnotationGroup* parentGrp) : name(_name), obj(p), parentGroup(parentGrp) { assert(!name.isEmpty() && (!name.contains('/') || name == AnnotationGroup::ROOT_GROUP_NAME)); } AnnotationGroup::~AnnotationGroup() { //annotations are not removed here -> contract with ~AnnotationTableObject foreach(AnnotationGroup* g, subgroups) { delete g; } } void AnnotationGroup::findAllAnnotationsInGroupSubTree(QSet<Annotation*>& set) const { set+=QSet<Annotation*>::fromList(annotations); foreach(AnnotationGroup* g, subgroups) { g->findAllAnnotationsInGroupSubTree(set); } } void AnnotationGroup::addAnnotation(Annotation* a) { if (a->getGObject() == NULL) { //adding annotation to the object by adding it to the group. //usually this method is called for annotation with groupName!=annotationName obj->addAnnotation(a, getGroupPath()); return; } SAFE_POINT(a->getGObject() == obj, "Illegal object!",); assert(/*!annotations.contains(a) && */! a->groups.contains(this)); obj->setModified(true); annotations.append(a); a->groups.append(this); if (obj!=NULL && a->groups.size() > 1) { obj->setModified(true); AnnotationGroupModification md(AnnotationModification_AddedToGroup, a, this); obj->emit_onAnnotationModified(md); } } void AnnotationGroup::removeAnnotations(const QList<Annotation*>& ans) { QList<Annotation*> toRemoveFromObj; foreach(Annotation* a, ans) { assert(annotations.contains(a) && a->groups.contains(this)); if (a->groups.size() == 1) { toRemoveFromObj.append(a); } else { annotations.removeOne(a); a->groups.removeOne(this); if (obj!=NULL) { obj->setModified(true); AnnotationGroupModification md(AnnotationModification_RemovedFromGroup, a, this); obj->emit_onAnnotationModified(md); } } } if (!toRemoveFromObj.isEmpty()) { obj->removeAnnotations(toRemoveFromObj); } } void AnnotationGroup::removeAnnotation(Annotation* a) { assert(annotations.contains(a) && a->groups.contains(this)); if (a->groups.size() == 1) { SAFE_POINT(a->groups.first() == this, "Illegal group!",); obj->removeAnnotation(a); } else { annotations.removeOne(a); a->groups.removeOne(this); if (obj!=NULL) { obj->setModified(true); AnnotationGroupModification md(AnnotationModification_RemovedFromGroup, a, this); obj->emit_onAnnotationModified(md); } } } bool AnnotationGroup::isValidGroupName(const QString& n, bool pathMode) { if (n.isEmpty()) { return false; } //todo: optimize QBitArray validChars = TextUtils::ALPHA_NUMS; validChars['_'] = true; validChars['-'] = true; validChars[' '] = true; validChars['\''] = true; if (pathMode) { validChars['/'] = true; } QByteArray groupName = n.toLocal8Bit(); if (!TextUtils::fits(validChars, groupName.constData(), groupName.size())) { return false; } if (groupName[0] == ' ' || groupName[groupName.size()-1] == ' ') { return false; } return true; } AnnotationGroup* AnnotationGroup::getSubgroup(const QString& path, bool create) { if (path.isEmpty()) { return this; } int idx = path.indexOf('/'); QString name = idx < 0 ? path : (idx == 0 ? path.mid(idx+1) : path.left(idx)); AnnotationGroup* group = NULL; foreach (AnnotationGroup *g, subgroups) { if (g->getGroupName() == name) { group = g; break; } } if (group == NULL && create) { group = new AnnotationGroup(obj, name, this); subgroups.push_back(group); obj->emit_onGroupCreated(group); } if (idx <= 0 || group == NULL) { return group; } AnnotationGroup* result = group->getSubgroup(path.mid(idx+1), create); return result; } void AnnotationGroup::removeSubgroup(AnnotationGroup* g) { SAFE_POINT(g->getParentGroup() == this, "Illegal parent group!",); obj->setModified(true); g->clear(); subgroups.removeOne(g); obj->emit_onGroupRemoved(this, g); delete g; } void AnnotationGroup::clear() { while (!subgroups.isEmpty()) { removeSubgroup(subgroups.first()); } if (!annotations.isEmpty()) { removeAnnotations(annotations); } } bool AnnotationGroup::isParentOf(AnnotationGroup* g) const { if (g->getGObject() != obj || g == this) { return false; } for (AnnotationGroup* pg = g->getParentGroup(); pg!=NULL; pg = pg->getParentGroup()) { if ( pg == this) { return true; } } return false; } void AnnotationGroup::setGroupName(const QString& newName) { if (name == newName) { return; } QString oldName = name; name = newName; obj->setModified(true); obj->emit_onGroupRenamed(this, oldName); } QString AnnotationGroup::getGroupPath() const { if (parentGroup == NULL) { return QString(""); } if (parentGroup->parentGroup == NULL) { return name; } return parentGroup->getGroupPath() + "/" + name; } void AnnotationGroup::getSubgroupPaths(QStringList& res) const { if (!isRootGroup()) { res.append(getGroupPath()); } foreach(const AnnotationGroup* g, subgroups) { g->getSubgroupPaths(res); } } QDataStream& operator>>(QDataStream& dataStream, AnnotationGroup* parentGroup) { QString name; dataStream >> name; AnnotationGroup *group = parentGroup->getSubgroup(name, true); int s; dataStream >> s; for (int i = 0; i < s; ++i) { AnnotationData *adata = new AnnotationData; dataStream >> *adata; Annotation *a = new Annotation(QSharedDataPointer<AnnotationData>(adata)); group->addAnnotation(a); } dataStream >> s; for (int i = 0; i < s; ++i) dataStream >> group; return dataStream; } QDataStream& operator<<(QDataStream& dataStream, const AnnotationGroup& group) { dataStream << group.name; int s = group.annotations.size(); dataStream << s; for (int i = 0; i < s; ++i) dataStream << *group.annotations[i]->data(); s = group.subgroups.size(); dataStream << s; for (int i = 0; i < s; ++i) dataStream << *group.subgroups[i]; return dataStream; } ////////////////////////////////////////////////////////////////////////// /// Annotation table object const QString AnnotationGroup::ROOT_GROUP_NAME("/"); AnnotationTableObject::AnnotationTableObject(const QString& objectName, const QVariantMap& hintsMap) : GObject(GObjectTypes::ANNOTATION_TABLE, objectName, hintsMap) { rootGroup = new AnnotationGroup(this, AnnotationGroup::ROOT_GROUP_NAME, NULL); } AnnotationTableObject::~AnnotationTableObject() { foreach(Annotation* a, annotations) { delete a; } delete rootGroup; } GObject* AnnotationTableObject::clone(const U2DbiRef&, U2OpStatus&) const { GTIMER(c2,t2,"AnnotationTableObject::clone"); AnnotationTableObject* cln = new AnnotationTableObject(getGObjectName(), getGHintsMap()); cln->setIndexInfo(getIndexInfo()); QMap<AnnotationGroup*, AnnotationGroup*>remap; cln->rootGroup = new AnnotationGroup(cln, rootGroup->getGroupName(), NULL); remap[rootGroup] = cln->rootGroup; QList<AnnotationGroup*> lst; lst << rootGroup->getSubgroups(); while(!lst.isEmpty()){ AnnotationGroup* gr = lst.takeFirst(); AnnotationGroup* newParent = remap.value(gr->getParentGroup()); assert(newParent); AnnotationGroup* newGr = new AnnotationGroup(cln, gr->getGroupName(), newParent); newParent->subgroups << newGr; remap[gr] = newGr; lst << gr->getSubgroups(); } foreach(Annotation* a, annotations) { Annotation* newA = new Annotation(a->d); newA->obj = cln; cln->annotations << newA; foreach(AnnotationGroup* gr, a->getGroups()) { AnnotationGroup* newGr = remap.value(gr); assert(newGr); newA->groups << newGr; newGr->annotations << newA; } } cln->setModified(false); return cln; } void AnnotationTableObject::addAnnotation(Annotation* a, const QString& groupName) { SAFE_POINT(a->obj == NULL, "Annotation belongs to another object", ); a->obj = this; const QString& aName = a->getAnnotationName(); AnnotationGroup* defaultGroup = rootGroup->getSubgroup(groupName.isEmpty() ? aName : groupName, true); defaultGroup->addAnnotation(a); annotations.append(a); setModified(true); emit si_onAnnotationsAdded(QList<Annotation*>()<<a); } void AnnotationTableObject::addAnnotation(Annotation* a, const QList<QString>& groupsNames) { SAFE_POINT(a->obj == NULL, "Annotation belongs to another object", ); if(groupsNames.isEmpty()){ addAnnotation(a); return; } a->obj = this; const QString& aName = a->getAnnotationName(); foreach(QString groupName, groupsNames){ AnnotationGroup* defaultGroup = rootGroup->getSubgroup(groupName.isEmpty() ? aName : groupName, true); defaultGroup->addAnnotation(a); } annotations.append(a); setModified(true); emit si_onAnnotationsAdded(QList<Annotation*>()<<a); } void AnnotationTableObject::addAnnotations(const QList<Annotation*>& list, const QString& groupName) { if (list.isEmpty()) { return; } annotations << list; GTIMER(c1,t1,"AnnotationTableObject::addAnnotations [populate data tree]"); AnnotationGroup* gr = NULL; if (groupName.isEmpty()) { QString prevName; foreach(Annotation* a, list) { assert(a->obj == NULL); a->obj = this; const QString& grName = a->getAnnotationName(); if (grName != prevName) { gr = rootGroup->getSubgroup(grName, true); prevName = grName; } gr->addAnnotation(a); } } else { gr = rootGroup->getSubgroup(groupName, true); foreach(Annotation* a, list) { assert(a->obj == NULL); a->obj = this; gr->addAnnotation(a); } } t1.stop(); setModified(true); GTIMER(c2,t2,"AnnotationTableObject::addAnnotations [notify]"); emit si_onAnnotationsAdded(list); } void AnnotationTableObject::removeAnnotations(const QList<Annotation*>& annotations) { foreach(Annotation* a, annotations) { _removeAnnotation(a); } emit si_onAnnotationsRemoved(annotations); setModified(true); qDeleteAll(annotations); } void AnnotationTableObject::removeAnnotationsInGroup(const QList<Annotation*>& _annotations, AnnotationGroup *group) { /*annotations = annotations.toSet().subtract(_annotations.toSet()).toList(); foreach(Annotation* a, _annotations) { a->obj = NULL; foreach(AnnotationGroup* ag, a->getGroups()) { ag->annotations.removeOne(a); } }*/ int recv = receivers(SIGNAL(si_onAnnotationsInGroupRemoved(const QList<Annotation*>&, AnnotationGroup*))); annLocker.setToDelete(_annotations, group, recv); DeleteAnnotationsFromObjectTask *task = new DeleteAnnotationsFromObjectTask(_annotations, this, group); AppContext::getTaskScheduler()->registerTopLevelTask(task); /*int recv = receivers(SIGNAL(si_onAnnotationsInGroupRemoved(const QList<Annotation*>&, AnnotationGroup*))); annLocker.setToDelete(_annotations, group, recv); emit si_onAnnotationsInGroupRemoved(_annotations, group); setModified(true);*/ //qDeleteAll(annotations); } void DeleteAnnotationsFromObjectTask::run() { /*aobj->annotations = aobj->annotations.toSet().subtract(anns.toSet()).toList(); foreach(Annotation* a, anns) { a->obj = NULL; foreach(AnnotationGroup* ag, a->getGroups()) { ag->annotations.removeOne(a); } }*/ foreach(Annotation* a, anns) { aobj->_removeAnnotation(a); } } Task::ReportResult DeleteAnnotationsFromObjectTask::report() { aobj->emit_onAnnotationsInGroupRemoved(anns, group); aobj->setModified(true); return ReportResult_Finished; } void AnnotationTableObject::releaseLocker() { annLocker.releaseLocker(); } bool AnnotationTableObject::isLocked() const { return annLocker.isLocked(); } void AnnotationTableObject::removeAnnotation(Annotation* a) { QList<Annotation*> v; v<<a; _removeAnnotation(a); setModified(true); emit si_onAnnotationsRemoved(v); delete a; } void AnnotationTableObject::_removeAnnotation(Annotation* a) { SAFE_POINT(a->getGObject() == this, "Illegal annotation object!",); a->obj = NULL; annotations.removeOne(a); foreach(AnnotationGroup* ag, a->getGroups()) { ag->annotations.removeOne(a); } } void AnnotationTableObject::selectAnnotationsByName(const QString& name, QList<Annotation*>& res) { foreach(Annotation* a, annotations) { if (a->getAnnotationName() == name) { res.append(a); } } } bool AnnotationTableObject::checkConstraints(const GObjectConstraints* c) const { const AnnotationTableObjectConstraints* ac = qobject_cast<const AnnotationTableObjectConstraints*>(c); SAFE_POINT(ac != NULL, "Illegal constraints type!", false); int fitSize = ac->sequenceSizeToFit; foreach(Annotation* a, annotations) { foreach(const U2Region& r, a->getRegions()) { if (r.endPos() > fitSize) { return false; } } } return true; } void AnnotationTableObject::cleanAnnotations() { assert(!annLocker.isLocked()); annLocker.sl_Clean(); } AnnotationTableObjectConstraints::AnnotationTableObjectConstraints(const AnnotationTableObjectConstraints& c, QObject* p) : GObjectConstraints(GObjectTypes::ANNOTATION_TABLE, p), sequenceSizeToFit(c.sequenceSizeToFit) { } AnnotationTableObjectConstraints::AnnotationTableObjectConstraints(QObject* p) : GObjectConstraints(GObjectTypes::ANNOTATION_TABLE, p), sequenceSizeToFit(0) { } bool annotationLessThanByRegion(const Annotation* a1, const Annotation* a2) { assert(!a1->getLocation()->isEmpty()); assert(!a2->getLocation()->isEmpty()); const U2Region& r1 = a1->getRegions().first(); const U2Region& r2 = a2->getRegions().first(); return r1 < r2; } bool annotationGreaterThanByRegion( const Annotation* a1, const Annotation* a2 ) { return annotationLessThanByRegion(a2, a1); } void AnnotationsLocker::setToDelete( const QList<Annotation*>& _anns, AnnotationGroup *_parentGroup, int counter ) { anns = _anns; parentGroup = _parentGroup; deleteCounter = counter; } void AnnotationsLocker::releaseLocker(){ if(deleteCounter) { deleteCounter--; } } bool AnnotationsLocker::isLocked() const{ return deleteCounter != 0; } void AnnotationsLocker::sl_Clean(){ if(deleteCounter == 0) { qDeleteAll(anns); anns.clear(); parentGroup->getParentGroup()->removeSubgroup(parentGroup); } } AnnotationsLocker::AnnotationsLocker(): parentGroup(NULL), deleteCounter(0) { } ////////////////////////////////////////////////////////////////////////// /// Features table object FeaturesTableObject::FeaturesTableObject( const QString& objectName, const U2DbiRef& dbiRef, const QVariantMap& hintsMap) : GObject(GObjectTypes::ANNOTATION_TABLE, objectName+"_features", hintsMap) { aObject = new AnnotationTableObject(objectName, hintsMap); initRootFeature(dbiRef); entityRef = U2EntityRef(dbiRef, rootFeature.id); connect(aObject, SIGNAL( si_onAnnotationsRemoved(const QList<Annotation*>& ) ), SLOT( sl_onAnnotationsRemoved(const QList<Annotation*>& ))); connect(aObject, SIGNAL( si_onAnnotationsInGroupRemoved(const QList<Annotation*>&, AnnotationGroup*) ), SLOT( sl_onAnnotationsInGroupRemoved(const QList<Annotation*>&, AnnotationGroup*))); connect(aObject, SIGNAL( si_onAnnotationModified(const AnnotationModification& ) ), SLOT( sl_onAnnotationModified(const AnnotationModification& ) )); connect(aObject, SIGNAL( si_onGroupRemoved(AnnotationGroup* , AnnotationGroup* ) ), SLOT( sl_onGroupRemoved(AnnotationGroup* , AnnotationGroup* ) )); connect(aObject, SIGNAL( si_onGroupRenamed(AnnotationGroup*, const QString& ) ), SLOT( sl_onGroupRenamed(AnnotationGroup*, const QString& ) )); } void FeaturesTableObject::initRootFeature(const U2DbiRef& dbiRef){ rootFeature.name = getGObjectName(); U2OpStatus2Log os; DbiConnection con(dbiRef, os); CHECK_OP(os, ); U2FeatureDbi* fdbi = con.dbi->getFeatureDbi(); SAFE_POINT(fdbi!=NULL, "Features dbi is NULL", ); fdbi->createFeature(rootFeature, QList<U2FeatureKey>(), os); CHECK_OP(os, ); } FeaturesTableObject::~FeaturesTableObject(){ delete aObject; //TODO: remove root feature } void FeaturesTableObject::addAnnotation( Annotation* a, const QString& groupName ){ aObject->addAnnotation(a, groupName); importToDbi(a); emit si_onAnnotationsAdded(QList<Annotation*>()<<a); } void FeaturesTableObject::addAnnotation( Annotation* a, const QList<QString>& groupsNames ){ aObject->addAnnotation(a, groupsNames); importToDbi(a); emit si_onAnnotationsAdded(QList<Annotation*>()<<a); } void FeaturesTableObject::addAnnotations( const QList<Annotation*>& annotations, const QString& groupName ){ aObject->addAnnotations(annotations, groupName); foreach(Annotation* a, annotations){ importToDbi(a); } emit si_onAnnotationsAdded(annotations); } void FeaturesTableObject::removeAnnotation( Annotation* a ){ U2OpStatus2Log os; synchronizer.removeFeature(a, rootFeature.id, entityRef.dbiRef, os); //CHECK_OP(os, ); aObject->removeAnnotation(a); } void FeaturesTableObject::removeAnnotations( const QList<Annotation*>& annotations ){ U2OpStatus2Log os; foreach(Annotation* a, annotations){ synchronizer.removeFeature(a, rootFeature.id, entityRef.dbiRef, os); //CHECK_OP(os, ); } aObject->removeAnnotations(annotations); } GObject* FeaturesTableObject::clone( const U2DbiRef& ref, U2OpStatus& os ) const{ Q_UNUSED(os); GTIMER(c2,t2,"FeaturesTableObject::clone"); FeaturesTableObject* cln = new FeaturesTableObject(getGObjectName(), ref, getGHintsMap()); cln->setIndexInfo(getIndexInfo()); QMap<AnnotationGroup*, AnnotationGroup*>remap; cln->aObject->rootGroup = new AnnotationGroup(cln->aObject, rootGroup->getGroupName(), NULL); remap[rootGroup] = cln->aObject->rootGroup; QList<AnnotationGroup*> lst; lst << rootGroup->getSubgroups(); while(!lst.isEmpty()){ AnnotationGroup* gr = lst.takeFirst(); AnnotationGroup* newParent = remap.value(gr->getParentGroup()); assert(newParent); AnnotationGroup* newGr = new AnnotationGroup(cln->aObject, gr->getGroupName(), newParent); newParent->subgroups << newGr; remap[gr] = newGr; lst << gr->getSubgroups(); } foreach(Annotation* a, annotations) { Annotation* newA = new Annotation(a->d); newA->obj = cln->aObject; cln->aObject->annotations << newA; foreach(AnnotationGroup* gr, a->getGroups()) { AnnotationGroup* newGr = remap.value(gr); assert(newGr); newA->groups << newGr; newGr->annotations << newA; } } cln->aObject->setModified(false); return cln; } void FeaturesTableObject::selectAnnotationsByName( const QString& name, QList<Annotation*>& res ){ aObject->selectAnnotationsByName(name, res); } bool FeaturesTableObject::checkConstraints( const GObjectConstraints* c ) const{ return aObject->checkConstraints(c); } void FeaturesTableObject::removeAnnotationsInGroup( const QList<Annotation*>& _annotations, AnnotationGroup *group ){ aObject->removeAnnotationsInGroup(_annotations, group); //TODO: features?? connect to remove slot } void FeaturesTableObject::releaseLocker(){ aObject->releaseLocker(); } bool FeaturesTableObject::isLocked() const{ return aObject->isLocked(); } void FeaturesTableObject::cleanAnnotations(){ U2OpStatus2Log os; synchronizer.removeFeature(rootFeature.id, entityRef.dbiRef, os); //CHECK_OP(os, ); aObject->cleanAnnotations(); } void FeaturesTableObject::_removeAnnotation( Annotation* a ){ U2OpStatus2Log os; synchronizer.removeFeature(a, rootFeature.id, entityRef.dbiRef, os); //CHECK_OP(os, ); aObject->_removeAnnotation(a); } void FeaturesTableObject::importToDbi( Annotation* a ){ SAFE_POINT(a->obj != NULL, "Annotation must be assigned to an object", ); U2OpStatus2Log os; synchronizer.exportAnnotationToFeatures(a, rootFeature.id, entityRef.dbiRef, os); CHECK_OP(os, ); } // direct interface to dbi void FeaturesTableObject::addFeature(U2Feature &f, U2OpStatus &os) { addFeature(f, QList<U2FeatureKey>(), os); } void FeaturesTableObject::addFeature(U2Feature &f, QList<U2FeatureKey> keys, U2OpStatus &os) { if(f.parentFeatureId.isEmpty()) { f.parentFeatureId = rootFeature.id; } // TODO: should we set sequenceId too? Seems logical that all subfeatures has same sequenceId // f.sequenceId = rootFeature.sequenceId; DbiConnection con; con.open(entityRef.dbiRef, os); CHECK_OP(os, ); con.dbi->getFeatureDbi()->createFeature(f, keys, os); } U2Feature FeaturesTableObject::getFeature(U2DataId id, U2OpStatus &os) { DbiConnection con; con.open(entityRef.dbiRef, os); CHECK_OP(os, U2Feature()); return con.dbi->getFeatureDbi()->getFeature(id, os); } QList<U2Feature> FeaturesTableObject::getSubfeatures(U2DataId parentFeatureId, U2OpStatus &os, bool recursive) { DbiConnection con; con.open(entityRef.dbiRef, os); CHECK_OP(os, QList<U2Feature>()); return U2FeaturesUtils::getSubFeatures(parentFeatureId, con.dbi->getFeatureDbi(), os, recursive); } //slots void FeaturesTableObject::sl_onAnnotationsRemoved( const QList<Annotation*>& a ){ emit si_onAnnotationsRemoved(a); } void FeaturesTableObject::sl_onAnnotationsInGroupRemoved( const QList<Annotation*>& a, AnnotationGroup* g){ //TODO emit_onAnnotationsInGroupRemoved(a, g); } void FeaturesTableObject::sl_onAnnotationModified( const AnnotationModification& md ){ U2OpStatus2Log os; synchronizer.modifyFeatures(md, rootFeature.id, entityRef.dbiRef, os); emit_onAnnotationModified(md); } void FeaturesTableObject::sl_onGroupCreated( AnnotationGroup* g){ //TODO: how to create an empty group? emit_onGroupCreated(g); } void FeaturesTableObject::sl_onGroupRemoved( AnnotationGroup* p, AnnotationGroup* removed ){ //delete groups from features U2OpStatus2Log os; synchronizer.removeGroup(p, removed, rootFeature.id, entityRef.dbiRef, os); emit_onGroupRemoved(p, removed); } void FeaturesTableObject::sl_onGroupRenamed( AnnotationGroup* g, const QString& oldName ){ //rename group in features U2OpStatus2Log os; synchronizer.renameGroup(g, oldName, rootFeature.id, entityRef.dbiRef, os); emit_onGroupRenamed(g, oldName); } }//namespace
31.534704
153
0.636042
iganna
0018286db252b6fa890c686fde2b3aa074643601
3,702
hpp
C++
include/parser/ValueMgr.hpp
scribelang/scribe-poc
c1ba4dafbb3b38a5b408e068747a5ed0f3e49e25
[ "MIT" ]
null
null
null
include/parser/ValueMgr.hpp
scribelang/scribe-poc
c1ba4dafbb3b38a5b408e068747a5ed0f3e49e25
[ "MIT" ]
null
null
null
include/parser/ValueMgr.hpp
scribelang/scribe-poc
c1ba4dafbb3b38a5b408e068747a5ed0f3e49e25
[ "MIT" ]
null
null
null
/* MIT License Copyright (c) 2021 Scribe Language Repositories 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. */ #ifndef PARSER_VALUEMGR_HPP #define PARSER_VALUEMGR_HPP #include <string> #include <unordered_map> #include <vector> #include "Value.hpp" namespace sc { namespace parser { class RAIIParser; // typedef bool (*intrinsic_fn_t)(TypeMgr &types, Stmt *stmt); // #define INTRINSIC(name) bool intrinsic_##name(TypeMgr &types, Stmt *stmt) // no need to copy unnecessarily - values are immutable class ValueLayer { std::unordered_map<std::string, Value *> vals; public: inline bool add(const std::string &name, Value *val) { if(vals.find(name) != vals.end()) return false; vals[name] = val; return true; } inline Value *get(const std::string &name) { return vals[name]; } inline bool has(const std::string &name) { return vals.find(name) != vals.end(); } }; class ValueSrc { std::vector<ValueLayer> stack; public: inline void pushLayer() { stack.push_back({}); } inline void popLayer() { stack.pop_back(); } inline bool add(const std::string &name, Value *val) { return stack.back().add(name, val); } inline Value *get(const std::string &name) { return stack.back().get(name); } inline bool has(const std::string &name) { return stack.back().has(name); } }; class ValueMgr { RAIIParser *parser; std::unordered_map<std::string, Value *> globals; std::unordered_map<size_t, ValueSrc> srcs; std::vector<ValueSrc *> stack; ValueAllocator vallocator; public: ValueMgr(RAIIParser *parser); inline RAIIParser *getParser() { return parser; } inline void add_src(const size_t &src_id) { if(srcs.find(src_id) == srcs.end()) srcs[src_id] = {}; } inline void push_src(const size_t &src_id) { stack.push_back(&srcs[src_id]); } inline void pop_src() { stack.pop_back(); } inline void pushLayer() { stack.back()->pushLayer(); } inline void popLayer() { stack.back()->popLayer(); } // FIXME: enable global inline bool add_val(const std::string &name, Value *val, const bool &global) { return stack.back()->add(name, val); } inline Value *get_val(const std::string &name) { return stack.back()->get(name); } // FIXME: enable top_only and with_globals inline bool has(const std::string &name, const bool &top_only, const bool &with_globals) { return stack.back()->has(name); } inline Value *get(const int64_t &idata) { return vallocator.get(idata); } inline Value *get(const double &fdata) { return vallocator.get(fdata); } inline Value *get(const std::string &sdata) { return vallocator.get(sdata); } inline Value *get(const std::vector<Value *> &vdata) { return vallocator.get(vdata); } inline Value *get(const std::unordered_map<std::string, Value *> &stdata, const std::vector<std::string> &storder) { return vallocator.get(stdata, storder); } // this is for unknown and void values inline Value *get(const Values &type) { return vallocator.get(type); } inline Value *get(Value *from) { return vallocator.get(from); } inline std::string getStringFromVec(Value *vec) { return parser::getStringFromVec(vec); } inline void updateValue(Value *src, Value *newval) { return vallocator.updateValue(src, newval); } }; } // namespace parser } // namespace sc #endif // PARSER_VALUEMGR_HPP
20.119565
89
0.697731
scribelang
001e703a89d2f94587d933c20950efe2dda20f91
56,473
cpp
C++
src/tier0/threadtools.cpp
DeadZoneLuna/csso-src
6c978ea304ee2df3796bc9c0d2916bac550050d5
[ "Unlicense" ]
4
2021-10-03T05:16:55.000Z
2021-12-28T16:49:27.000Z
src/tier0/threadtools.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
null
null
null
src/tier0/threadtools.cpp
cafeed28/what
08e51d077f0eae50afe3b592543ffa07538126f5
[ "Unlicense" ]
3
2022-02-02T18:09:58.000Z
2022-03-06T18:54:39.000Z
//========= Copyright Valve Corporation, All rights reserved. ============// // // Purpose: // //============================================================================= #include "pch_tier0.h" #include "tier1/strtools.h" #include "tier0/dynfunction.h" #if defined( _WIN32 ) && !defined( _X360 ) #define WIN32_LEAN_AND_MEAN #include <windows.h> #endif #ifdef _WIN32 #include <process.h> #ifdef IS_WINDOWS_PC #include <Mmsystem.h> #pragma comment(lib, "winmm.lib") #endif // IS_WINDOWS_PC #elif defined(POSIX) #if !defined(OSX) #include <sys/fcntl.h> #include <sys/unistd.h> #define sem_unlink( arg ) #define OS_TO_PTHREAD(x) (x) #else #define pthread_yield pthread_yield_np #include <mach/thread_act.h> #include <mach/mach.h> #define OS_TO_PTHREAD(x) pthread_from_mach_thread_np( x ) #endif // !OSX #ifdef LINUX #include <dlfcn.h> // RTLD_NEXT #endif typedef int (*PTHREAD_START_ROUTINE)( void *lpThreadParameter ); typedef PTHREAD_START_ROUTINE LPTHREAD_START_ROUTINE; #include <sched.h> #include <exception> #include <errno.h> #include <signal.h> #include <pthread.h> #include <sys/time.h> #define GetLastError() errno typedef void *LPVOID; #endif #include "tier0/valve_minmax_off.h" #include <memory> #include "tier0/valve_minmax_on.h" #include "tier0/threadtools.h" #include "tier0/vcrmode.h" #ifdef _X360 #include "xbox/xbox_win32stubs.h" #endif #include "tier0/vprof_telemetry.h" // Must be last header... #include "tier0/memdbgon.h" #define THREADS_DEBUG 1 // Need to ensure initialized before other clients call in for main thread ID #ifdef _WIN32 #pragma warning(disable:4073) #pragma init_seg(lib) #endif #ifdef _WIN32 ASSERT_INVARIANT(TT_SIZEOF_CRITICALSECTION == sizeof(CRITICAL_SECTION)); ASSERT_INVARIANT(TT_INFINITE == INFINITE); #endif //----------------------------------------------------------------------------- // Simple thread functions. // Because _beginthreadex uses stdcall, we need to convert to cdecl //----------------------------------------------------------------------------- struct ThreadProcInfo_t { ThreadProcInfo_t( ThreadFunc_t pfnThread, void *pParam ) : pfnThread( pfnThread), pParam( pParam ) { } ThreadFunc_t pfnThread; void * pParam; }; //--------------------------------------------------------- #ifdef _WIN32 static unsigned __stdcall ThreadProcConvert( void *pParam ) #elif defined(POSIX) static void *ThreadProcConvert( void *pParam ) #else #error #endif { ThreadProcInfo_t info = *((ThreadProcInfo_t *)pParam); delete ((ThreadProcInfo_t *)pParam); #ifdef _WIN32 return (*info.pfnThread)(info.pParam); #elif defined(POSIX) return (void *)(*info.pfnThread)(info.pParam); #else #error #endif } //--------------------------------------------------------- ThreadHandle_t CreateSimpleThread( ThreadFunc_t pfnThread, void *pParam, ThreadId_t *pID, unsigned stackSize ) { #ifdef _WIN32 ThreadId_t idIgnored; if ( !pID ) pID = &idIgnored; HANDLE h = VCRHook_CreateThread(NULL, stackSize, (LPTHREAD_START_ROUTINE)ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ), CREATE_SUSPENDED, pID); if ( h != INVALID_HANDLE_VALUE ) { Plat_ApplyHardwareDataBreakpointsToNewThread( *pID ); ResumeThread( h ); } return (ThreadHandle_t)h; #elif defined(POSIX) pthread_t tid; // If we need to create threads that are detached right out of the gate, we would need to do something like this: // pthread_attr_t attr; // int rc = pthread_attr_init(&attr); // rc = pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED); // ... pthread_create( &tid, &attr, ... ) ... // rc = pthread_attr_destroy(&attr); // ... pthread_join will now fail int ret = pthread_create( &tid, NULL, ThreadProcConvert, new ThreadProcInfo_t( pfnThread, pParam ) ); if ( ret ) { // There are only PTHREAD_THREADS_MAX number of threads, and we're probably leaking handles if ret == EAGAIN here? Error( "CreateSimpleThread: pthread_create failed. Someone not calling pthread_detach() or pthread_join. Ret:%d\n", ret ); } if ( pID ) *pID = (ThreadId_t)tid; Plat_ApplyHardwareDataBreakpointsToNewThread( (long unsigned int)tid ); return (ThreadHandle_t)tid; #endif } ThreadHandle_t CreateSimpleThread( ThreadFunc_t pfnThread, void *pParam, unsigned stackSize ) { return CreateSimpleThread( pfnThread, pParam, NULL, stackSize ); } PLATFORM_INTERFACE void ThreadDetach( ThreadHandle_t hThread ) { #if defined( POSIX ) // The resources of this thread will be freed immediately when it terminates, // instead of waiting for another thread to perform PTHREAD_JOIN. pthread_t tid = ( pthread_t )hThread; pthread_detach( tid ); #endif } bool ReleaseThreadHandle( ThreadHandle_t hThread ) { #ifdef _WIN32 return ( CloseHandle( hThread ) != 0 ); #else return true; #endif } //----------------------------------------------------------------------------- // // Wrappers for other simple threading operations // //----------------------------------------------------------------------------- void ThreadSleep(unsigned nMilliseconds) { #ifdef _WIN32 #ifdef IS_WINDOWS_PC static bool bInitialized = false; if ( !bInitialized ) { bInitialized = true; // Set the timer resolution to 1 ms (default is 10.0, 15.6, 2.5, 1.0 or // some other value depending on hardware and software) so that we can // use Sleep( 1 ) to avoid wasting CPU time without missing our frame // rate. timeBeginPeriod( 1 ); } #endif // IS_WINDOWS_PC Sleep( nMilliseconds ); #elif defined(POSIX) usleep( nMilliseconds * 1000 ); #endif } //----------------------------------------------------------------------------- #ifndef ThreadGetCurrentId uint ThreadGetCurrentId() { #ifdef _WIN32 return GetCurrentThreadId(); #elif defined(POSIX) return (uint)pthread_self(); #endif } #endif //----------------------------------------------------------------------------- ThreadHandle_t ThreadGetCurrentHandle() { #ifdef _WIN32 return (ThreadHandle_t)GetCurrentThread(); #elif defined(POSIX) return (ThreadHandle_t)pthread_self(); #endif } // On PS3, this will return true for zombie threads bool ThreadIsThreadIdRunning( ThreadId_t uThreadId ) { #ifdef _WIN32 bool bRunning = true; HANDLE hThread = ::OpenThread( THREAD_QUERY_INFORMATION , false, uThreadId ); if ( hThread ) { DWORD dwExitCode; if( !::GetExitCodeThread( hThread, &dwExitCode ) || dwExitCode != STILL_ACTIVE ) bRunning = false; CloseHandle( hThread ); } else { bRunning = false; } return bRunning; #elif defined( _PS3 ) // will return CELL_OK for zombie threads int priority; return (sys_ppu_thread_get_priority( uThreadId, &priority ) == CELL_OK ); #elif defined(POSIX) pthread_t thread = OS_TO_PTHREAD(uThreadId); if ( thread ) { int iResult = pthread_kill( thread, 0 ); if ( iResult == 0 ) return true; } else { // We really ought not to be passing NULL in to here AssertMsg( false, "ThreadIsThreadIdRunning received a null thread ID" ); } return false; #endif } //----------------------------------------------------------------------------- int ThreadGetPriority( ThreadHandle_t hThread ) { if ( !hThread ) { hThread = ThreadGetCurrentHandle(); } #ifdef _WIN32 return ::GetThreadPriority( (HANDLE)hThread ); #else struct sched_param thread_param; int policy; pthread_getschedparam( (pthread_t)hThread, &policy, &thread_param ); return thread_param.sched_priority; #endif } //----------------------------------------------------------------------------- bool ThreadSetPriority( ThreadHandle_t hThread, int priority ) { if ( !hThread ) { hThread = ThreadGetCurrentHandle(); } #ifdef _WIN32 return ( SetThreadPriority(hThread, priority) != 0 ); #elif defined(POSIX) struct sched_param thread_param; thread_param.sched_priority = priority; pthread_setschedparam( (pthread_t)hThread, SCHED_OTHER, &thread_param ); return true; #endif } //----------------------------------------------------------------------------- void ThreadSetAffinity( ThreadHandle_t hThread, int nAffinityMask ) { if ( !hThread ) { hThread = ThreadGetCurrentHandle(); } #ifdef _WIN32 SetThreadAffinityMask( hThread, nAffinityMask ); #elif defined(POSIX) // cpu_set_t cpuSet; // CPU_ZERO( cpuSet ); // for( int i = 0 ; i < 32; i++ ) // if ( nAffinityMask & ( 1 << i ) ) // CPU_SET( cpuSet, i ); // sched_setaffinity( hThread, sizeof( cpuSet ), &cpuSet ); #endif } //----------------------------------------------------------------------------- uint InitMainThread() { #ifndef LINUX // Skip doing the setname on Linux for the main thread. Here is why... // From Pierre-Loup e-mail about why pthread_setname_np() on the main thread // in Linux will cause some tools to display "MainThrd" as the executable name: // // You have two things in procfs, comm and cmdline. Each of the threads have // a different `comm`, which is the value you set through pthread_setname_np // or prctl(PR_SET_NAME). Top can either display cmdline or comm; it // switched to display comm by default; htop still displays cmdline by // default. Top -c will output cmdline rather than comm. // // If you press 'H' while top is running it will display each thread as a // separate process, so you will have different entries for MainThrd, // MatQueue0, etc with their own CPU usage. But when that mode isn't enabled // it just displays the 'comm' name from the first thread. ThreadSetDebugName( "MainThrd" ); #endif #ifdef _WIN32 return ThreadGetCurrentId(); #elif defined(POSIX) return (uint)pthread_self(); #endif } uint g_ThreadMainThreadID = InitMainThread(); bool ThreadInMainThread() { return ( ThreadGetCurrentId() == g_ThreadMainThreadID ); } //----------------------------------------------------------------------------- void DeclareCurrentThreadIsMainThread() { g_ThreadMainThreadID = ThreadGetCurrentId(); } bool ThreadJoin( ThreadHandle_t hThread, unsigned timeout ) { // You should really never be calling this with a NULL thread handle. If you // are then that probably implies a race condition or threading misunderstanding. Assert( hThread ); if ( !hThread ) { return false; } #ifdef _WIN32 DWORD dwWait = VCRHook_WaitForSingleObject((HANDLE)hThread, timeout); if ( dwWait == WAIT_TIMEOUT) return false; if ( dwWait != WAIT_OBJECT_0 && ( dwWait != WAIT_FAILED && GetLastError() != 0 ) ) { Assert( 0 ); return false; } #elif defined(POSIX) if ( pthread_join( (pthread_t)hThread, NULL ) != 0 ) return false; #endif return true; } #ifdef RAD_TELEMETRY_ENABLED void TelemetryThreadSetDebugName( ThreadId_t id, const char *pszName ); #endif //----------------------------------------------------------------------------- void ThreadSetDebugName( ThreadId_t id, const char *pszName ) { if( !pszName ) return; #ifdef RAD_TELEMETRY_ENABLED TelemetryThreadSetDebugName( id, pszName ); #endif #ifdef _WIN32 if ( Plat_IsInDebugSession() ) { #define MS_VC_EXCEPTION 0x406d1388 typedef struct tagTHREADNAME_INFO { DWORD dwType; // must be 0x1000 LPCSTR szName; // pointer to name (in same addr space) DWORD dwThreadID; // thread ID (-1 caller thread) DWORD dwFlags; // reserved for future use, most be zero } THREADNAME_INFO; THREADNAME_INFO info; info.dwType = 0x1000; info.szName = pszName; info.dwThreadID = id; info.dwFlags = 0; __try { RaiseException(MS_VC_EXCEPTION, 0, sizeof(info) / sizeof(DWORD), (ULONG_PTR *)&info); } __except (EXCEPTION_CONTINUE_EXECUTION) { } } #elif defined( _LINUX ) // As of glibc v2.12, we can use pthread_setname_np. typedef int (pthread_setname_np_func)(pthread_t, const char *); static pthread_setname_np_func *s_pthread_setname_np_func = (pthread_setname_np_func *)dlsym(RTLD_DEFAULT, "pthread_setname_np"); if ( s_pthread_setname_np_func ) { if ( id == (uint32)-1 ) id = pthread_self(); /* pthread_setname_np() in phthread_setname.c has the following code: #define TASK_COMM_LEN 16 size_t name_len = strlen (name); if (name_len >= TASK_COMM_LEN) return ERANGE; So we need to truncate the threadname to 16 or the call will just fail. */ char szThreadName[ 16 ]; strncpy( szThreadName, pszName, ARRAYSIZE( szThreadName ) ); szThreadName[ ARRAYSIZE( szThreadName ) - 1 ] = 0; (*s_pthread_setname_np_func)( id, szThreadName ); } #endif } //----------------------------------------------------------------------------- #ifdef _WIN32 ASSERT_INVARIANT( TW_FAILED == WAIT_FAILED ); ASSERT_INVARIANT( TW_TIMEOUT == WAIT_TIMEOUT ); ASSERT_INVARIANT( WAIT_OBJECT_0 == 0 ); int ThreadWaitForObjects( int nEvents, const HANDLE *pHandles, bool bWaitAll, unsigned timeout ) { return VCRHook_WaitForMultipleObjects( nEvents, pHandles, bWaitAll, timeout ); } #endif //----------------------------------------------------------------------------- // Used to thread LoadLibrary on the 360 //----------------------------------------------------------------------------- static ThreadedLoadLibraryFunc_t s_ThreadedLoadLibraryFunc = 0; PLATFORM_INTERFACE void SetThreadedLoadLibraryFunc( ThreadedLoadLibraryFunc_t func ) { s_ThreadedLoadLibraryFunc = func; } PLATFORM_INTERFACE ThreadedLoadLibraryFunc_t GetThreadedLoadLibraryFunc() { return s_ThreadedLoadLibraryFunc; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CThreadSyncObject::CThreadSyncObject() #ifdef _WIN32 : m_hSyncObject( NULL ), m_bCreatedHandle(false) #elif defined(POSIX) : m_bInitalized( false ) #endif { } //--------------------------------------------------------- CThreadSyncObject::~CThreadSyncObject() { #ifdef _WIN32 if ( m_hSyncObject && m_bCreatedHandle ) { if ( !CloseHandle(m_hSyncObject) ) { Assert( 0 ); } } #elif defined(POSIX) if ( m_bInitalized ) { pthread_cond_destroy( &m_Condition ); pthread_mutex_destroy( &m_Mutex ); m_bInitalized = false; } #endif } //--------------------------------------------------------- bool CThreadSyncObject::operator!() const { #ifdef _WIN32 return !m_hSyncObject; #elif defined(POSIX) return !m_bInitalized; #endif } //--------------------------------------------------------- void CThreadSyncObject::AssertUseable() { #ifdef THREADS_DEBUG #ifdef _WIN32 AssertMsg( m_hSyncObject, "Thread synchronization object is unuseable" ); #elif defined(POSIX) AssertMsg( m_bInitalized, "Thread synchronization object is unuseable" ); #endif #endif } //--------------------------------------------------------- bool CThreadSyncObject::Wait( uint32 dwTimeout ) { #ifdef THREADS_DEBUG AssertUseable(); #endif #ifdef _WIN32 return ( VCRHook_WaitForSingleObject( m_hSyncObject, dwTimeout ) == WAIT_OBJECT_0 ); #elif defined(POSIX) pthread_mutex_lock( &m_Mutex ); bool bRet = false; if ( m_cSet > 0 ) { bRet = true; m_bWakeForEvent = false; } else { volatile int ret = 0; while ( !m_bWakeForEvent && ret != ETIMEDOUT ) { struct timeval tv; gettimeofday( &tv, NULL ); volatile struct timespec tm; uint64 actualTimeout = dwTimeout; if ( dwTimeout == TT_INFINITE && m_bManualReset ) actualTimeout = 10; // just wait 10 msec at most for manual reset events and loop instead volatile uint64 nNanoSec = (uint64)tv.tv_usec*1000 + (uint64)actualTimeout*1000000; tm.tv_sec = tv.tv_sec + nNanoSec /1000000000; tm.tv_nsec = nNanoSec % 1000000000; do { ret = pthread_cond_timedwait( &m_Condition, &m_Mutex, (const timespec *)&tm ); } while( ret == EINTR ); bRet = ( ret == 0 ); if ( m_bManualReset ) { if ( m_cSet ) break; if ( dwTimeout == TT_INFINITE && ret == ETIMEDOUT ) ret = 0; // force the loop to spin back around } } if ( bRet ) m_bWakeForEvent = false; } if ( !m_bManualReset && bRet ) m_cSet = 0; pthread_mutex_unlock( &m_Mutex ); return bRet; #endif } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CThreadEvent::CThreadEvent( bool bManualReset ) { #ifdef _WIN32 m_hSyncObject = CreateEvent( NULL, bManualReset, FALSE, NULL ); m_bCreatedHandle = true; AssertMsg1(m_hSyncObject, "Failed to create event (error 0x%x)", GetLastError() ); #elif defined( POSIX ) pthread_mutexattr_t Attr; pthread_mutexattr_init( &Attr ); pthread_mutex_init( &m_Mutex, &Attr ); pthread_mutexattr_destroy( &Attr ); pthread_cond_init( &m_Condition, NULL ); m_bInitalized = true; m_cSet = 0; m_bWakeForEvent = false; m_bManualReset = bManualReset; #else #error "Implement me" #endif } #ifdef _WIN32 CThreadEvent::CThreadEvent( HANDLE hHandle ) { m_hSyncObject = hHandle; m_bCreatedHandle = false; AssertMsg(m_hSyncObject, "Null event passed into constructor" ); } #endif //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- //--------------------------------------------------------- bool CThreadEvent::Set() { AssertUseable(); #ifdef _WIN32 return ( SetEvent( m_hSyncObject ) != 0 ); #elif defined(POSIX) pthread_mutex_lock( &m_Mutex ); m_cSet = 1; m_bWakeForEvent = true; int ret = pthread_cond_signal( &m_Condition ); pthread_mutex_unlock( &m_Mutex ); return ret == 0; #endif } //--------------------------------------------------------- bool CThreadEvent::Reset() { #ifdef THREADS_DEBUG AssertUseable(); #endif #ifdef _WIN32 return ( ResetEvent( m_hSyncObject ) != 0 ); #elif defined(POSIX) pthread_mutex_lock( &m_Mutex ); m_cSet = 0; m_bWakeForEvent = false; pthread_mutex_unlock( &m_Mutex ); return true; #endif } //--------------------------------------------------------- bool CThreadEvent::Check() { #ifdef THREADS_DEBUG AssertUseable(); #endif return Wait( 0 ); } bool CThreadEvent::Wait( uint32 dwTimeout ) { return CThreadSyncObject::Wait( dwTimeout ); } #ifdef _WIN32 //----------------------------------------------------------------------------- // // CThreadSemaphore // // To get Posix implementation, try http://www-128.ibm.com/developerworks/eserver/library/es-win32linux-sem.html // //----------------------------------------------------------------------------- CThreadSemaphore::CThreadSemaphore( long initialValue, long maxValue ) { if ( maxValue ) { AssertMsg( maxValue > 0, "Invalid max value for semaphore" ); AssertMsg( initialValue >= 0 && initialValue <= maxValue, "Invalid initial value for semaphore" ); m_hSyncObject = CreateSemaphore( NULL, initialValue, maxValue, NULL ); AssertMsg1(m_hSyncObject, "Failed to create semaphore (error 0x%x)", GetLastError()); } else { m_hSyncObject = NULL; } } //--------------------------------------------------------- bool CThreadSemaphore::Release( long releaseCount, long *pPreviousCount ) { #ifdef THRDTOOL_DEBUG AssertUseable(); #endif return ( ReleaseSemaphore( m_hSyncObject, releaseCount, pPreviousCount ) != 0 ); } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CThreadFullMutex::CThreadFullMutex( bool bEstablishInitialOwnership, const char *pszName ) { m_hSyncObject = CreateMutex( NULL, bEstablishInitialOwnership, pszName ); AssertMsg1( m_hSyncObject, "Failed to create mutex (error 0x%x)", GetLastError() ); } //--------------------------------------------------------- bool CThreadFullMutex::Release() { #ifdef THRDTOOL_DEBUG AssertUseable(); #endif return ( ReleaseMutex( m_hSyncObject ) != 0 ); } #endif //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CThreadLocalBase::CThreadLocalBase() { #ifdef _WIN32 m_index = TlsAlloc(); AssertMsg( m_index != 0xFFFFFFFF, "Bad thread local" ); if ( m_index == 0xFFFFFFFF ) Error( "Out of thread local storage!\n" ); #elif defined(POSIX) if ( pthread_key_create( &m_index, NULL ) != 0 ) Error( "Out of thread local storage!\n" ); #endif } //--------------------------------------------------------- CThreadLocalBase::~CThreadLocalBase() { #ifdef _WIN32 if ( m_index != 0xFFFFFFFF ) TlsFree( m_index ); m_index = 0xFFFFFFFF; #elif defined(POSIX) pthread_key_delete( m_index ); #endif } //--------------------------------------------------------- void * CThreadLocalBase::Get() const { #ifdef _WIN32 if ( m_index != 0xFFFFFFFF ) return TlsGetValue( m_index ); AssertMsg( 0, "Bad thread local" ); return NULL; #elif defined(POSIX) void *value = pthread_getspecific( m_index ); return value; #endif } //--------------------------------------------------------- void CThreadLocalBase::Set( void *value ) { #ifdef _WIN32 if (m_index != 0xFFFFFFFF) TlsSetValue(m_index, value); else AssertMsg( 0, "Bad thread local" ); #elif defined(POSIX) if ( pthread_setspecific( m_index, value ) != 0 ) AssertMsg( 0, "Bad thread local" ); #endif } //----------------------------------------------------------------------------- //----------------------------------------------------------------------------- #ifdef _WIN32 #ifdef _X360 #define TO_INTERLOCK_PARAM(p) ((long *)p) #define TO_INTERLOCK_PTR_PARAM(p) ((void **)p) #else #define TO_INTERLOCK_PARAM(p) (p) #define TO_INTERLOCK_PTR_PARAM(p) (p) #endif #ifndef USE_INTRINSIC_INTERLOCKED long ThreadInterlockedIncrement( long volatile *pDest ) { Assert( (size_t)pDest % 4 == 0 ); return InterlockedIncrement( TO_INTERLOCK_PARAM(pDest) ); } long ThreadInterlockedDecrement( long volatile *pDest ) { Assert( (size_t)pDest % 4 == 0 ); return InterlockedDecrement( TO_INTERLOCK_PARAM(pDest) ); } long ThreadInterlockedExchange( long volatile *pDest, long value ) { Assert( (size_t)pDest % 4 == 0 ); return InterlockedExchange( TO_INTERLOCK_PARAM(pDest), value ); } long ThreadInterlockedExchangeAdd( long volatile *pDest, long value ) { Assert( (size_t)pDest % 4 == 0 ); return InterlockedExchangeAdd( TO_INTERLOCK_PARAM(pDest), value ); } long ThreadInterlockedCompareExchange( long volatile *pDest, long value, long comperand ) { Assert( (size_t)pDest % 4 == 0 ); return InterlockedCompareExchange( TO_INTERLOCK_PARAM(pDest), value, comperand ); } bool ThreadInterlockedAssignIf( long volatile *pDest, long value, long comperand ) { Assert( (size_t)pDest % 4 == 0 ); #if !(defined(_WIN64) || defined (_X360)) __asm { mov eax,comperand mov ecx,pDest mov edx,value lock cmpxchg [ecx],edx mov eax,0 setz al } #else return ( InterlockedCompareExchange( TO_INTERLOCK_PARAM(pDest), value, comperand ) == comperand ); #endif } #endif #if !defined( USE_INTRINSIC_INTERLOCKED ) || defined( _WIN64 ) void *ThreadInterlockedExchangePointer( void * volatile *pDest, void *value ) { Assert( (size_t)pDest % 4 == 0 ); return InterlockedExchangePointer( TO_INTERLOCK_PARAM(pDest), value ); } void *ThreadInterlockedCompareExchangePointer( void * volatile *pDest, void *value, void *comperand ) { Assert( (size_t)pDest % 4 == 0 ); return InterlockedCompareExchangePointer( TO_INTERLOCK_PTR_PARAM(pDest), value, comperand ); } bool ThreadInterlockedAssignPointerIf( void * volatile *pDest, void *value, void *comperand ) { Assert( (size_t)pDest % 4 == 0 ); #if !(defined(_WIN64) || defined (_X360)) __asm { mov eax,comperand mov ecx,pDest mov edx,value lock cmpxchg [ecx],edx mov eax,0 setz al } #else return ( InterlockedCompareExchangePointer( TO_INTERLOCK_PTR_PARAM(pDest), value, comperand ) == comperand ); #endif } #endif int64 ThreadInterlockedCompareExchange64( int64 volatile *pDest, int64 value, int64 comperand ) { Assert( (size_t)pDest % 8 == 0 ); #if defined(_WIN64) || defined (_X360) return InterlockedCompareExchange64( pDest, value, comperand ); #else __asm { lea esi,comperand; lea edi,value; mov eax,[esi]; mov edx,4[esi]; mov ebx,[edi]; mov ecx,4[edi]; mov esi,pDest; lock CMPXCHG8B [esi]; } #endif } bool ThreadInterlockedAssignIf64(volatile int64 *pDest, int64 value, int64 comperand ) { Assert( (size_t)pDest % 8 == 0 ); #if defined(PLATFORM_WINDOWS_PC32 ) __asm { lea esi,comperand; lea edi,value; mov eax,[esi]; mov edx,4[esi]; mov ebx,[edi]; mov ecx,4[edi]; mov esi,pDest; lock CMPXCHG8B [esi]; mov eax,0; setz al; } #else return ( ThreadInterlockedCompareExchange64( pDest, value, comperand ) == comperand ); #endif } #if defined( PLATFORM_64BITS ) #if _MSC_VER < 1500 // This intrinsic isn't supported on VS2005. extern "C" unsigned char _InterlockedCompareExchange128( int64 volatile * Destination, int64 ExchangeHigh, int64 ExchangeLow, int64 * ComparandResult ); #endif bool ThreadInterlockedAssignIf128( volatile int128 *pDest, const int128 &value, const int128 &comperand ) { Assert( ( (size_t)pDest % 16 ) == 0 ); volatile int64 *pDest64 = ( volatile int64 * )pDest; int64 *pValue64 = ( int64 * )&value; int64 *pComperand64 = ( int64 * )&comperand; // Description: // The CMPXCHG16B instruction compares the 128-bit value in the RDX:RAX and RCX:RBX registers // with a 128-bit memory location. If the values are equal, the zero flag (ZF) is set, // and the RCX:RBX value is copied to the memory location. // Otherwise, the ZF flag is cleared, and the memory value is copied to RDX:RAX. // _InterlockedCompareExchange128: http://msdn.microsoft.com/en-us/library/bb514094.aspx return _InterlockedCompareExchange128( pDest64, pValue64[1], pValue64[0], pComperand64 ) == 1; } #endif // PLATFORM_64BITS int64 ThreadInterlockedIncrement64( int64 volatile *pDest ) { Assert( (size_t)pDest % 8 == 0 ); int64 Old; do { Old = *pDest; } while (ThreadInterlockedCompareExchange64(pDest, Old + 1, Old) != Old); return Old + 1; } int64 ThreadInterlockedDecrement64( int64 volatile *pDest ) { Assert( (size_t)pDest % 8 == 0 ); int64 Old; do { Old = *pDest; } while (ThreadInterlockedCompareExchange64(pDest, Old - 1, Old) != Old); return Old - 1; } int64 ThreadInterlockedExchange64( int64 volatile *pDest, int64 value ) { Assert( (size_t)pDest % 8 == 0 ); int64 Old; do { Old = *pDest; } while (ThreadInterlockedCompareExchange64(pDest, value, Old) != Old); return Old; } int64 ThreadInterlockedExchangeAdd64( int64 volatile *pDest, int64 value ) { Assert( (size_t)pDest % 8 == 0 ); int64 Old; do { Old = *pDest; } while (ThreadInterlockedCompareExchange64(pDest, Old + value, Old) != Old); return Old; } #elif defined(GNUC) #ifdef OSX #include <libkern/OSAtomic.h> #endif long ThreadInterlockedIncrement( long volatile *pDest ) { return __sync_fetch_and_add( pDest, 1 ) + 1; } long ThreadInterlockedDecrement( long volatile *pDest ) { return __sync_fetch_and_sub( pDest, 1 ) - 1; } long ThreadInterlockedExchange( long volatile *pDest, long value ) { return __sync_lock_test_and_set( pDest, value ); } long ThreadInterlockedExchangeAdd( long volatile *pDest, long value ) { return __sync_fetch_and_add( pDest, value ); } long ThreadInterlockedCompareExchange( long volatile *pDest, long value, long comperand ) { return __sync_val_compare_and_swap( pDest, comperand, value ); } bool ThreadInterlockedAssignIf( long volatile *pDest, long value, long comperand ) { return __sync_bool_compare_and_swap( pDest, comperand, value ); } void *ThreadInterlockedExchangePointer( void * volatile *pDest, void *value ) { return __sync_lock_test_and_set( pDest, value ); } void *ThreadInterlockedCompareExchangePointer( void *volatile *pDest, void *value, void *comperand ) { return __sync_val_compare_and_swap( pDest, comperand, value ); } bool ThreadInterlockedAssignPointerIf( void * volatile *pDest, void *value, void *comperand ) { return __sync_bool_compare_and_swap( pDest, comperand, value ); } int64 ThreadInterlockedCompareExchange64( int64 volatile *pDest, int64 value, int64 comperand ) { #if defined(OSX) int64 retVal = *pDest; if ( OSAtomicCompareAndSwap64( comperand, value, pDest ) ) retVal = *pDest; return retVal; #else return __sync_val_compare_and_swap( pDest, comperand, value ); #endif } bool ThreadInterlockedAssignIf64( int64 volatile * pDest, int64 value, int64 comperand ) { return __sync_bool_compare_and_swap( pDest, comperand, value ); } int64 ThreadInterlockedExchange64( int64 volatile *pDest, int64 value ) { Assert( (size_t)pDest % 8 == 0 ); int64 Old; do { Old = *pDest; } while (ThreadInterlockedCompareExchange64(pDest, value, Old) != Old); return Old; } #else // This will perform horribly, #error "Falling back to mutexed interlocked operations, you really don't have intrinsics you can use?"ß CThreadMutex g_InterlockedMutex; long ThreadInterlockedIncrement( long volatile *pDest ) { AUTO_LOCK( g_InterlockedMutex ); return ++(*pDest); } long ThreadInterlockedDecrement( long volatile *pDest ) { AUTO_LOCK( g_InterlockedMutex ); return --(*pDest); } long ThreadInterlockedExchange( long volatile *pDest, long value ) { AUTO_LOCK( g_InterlockedMutex ); long retVal = *pDest; *pDest = value; return retVal; } void *ThreadInterlockedExchangePointer( void * volatile *pDest, void *value ) { AUTO_LOCK( g_InterlockedMutex ); void *retVal = *pDest; *pDest = value; return retVal; } long ThreadInterlockedExchangeAdd( long volatile *pDest, long value ) { AUTO_LOCK( g_InterlockedMutex ); long retVal = *pDest; *pDest += value; return retVal; } long ThreadInterlockedCompareExchange( long volatile *pDest, long value, long comperand ) { AUTO_LOCK( g_InterlockedMutex ); long retVal = *pDest; if ( *pDest == comperand ) *pDest = value; return retVal; } void *ThreadInterlockedCompareExchangePointer( void * volatile *pDest, void *value, void *comperand ) { AUTO_LOCK( g_InterlockedMutex ); void *retVal = *pDest; if ( *pDest == comperand ) *pDest = value; return retVal; } int64 ThreadInterlockedCompareExchange64( int64 volatile *pDest, int64 value, int64 comperand ) { Assert( (size_t)pDest % 8 == 0 ); AUTO_LOCK( g_InterlockedMutex ); int64 retVal = *pDest; if ( *pDest == comperand ) *pDest = value; return retVal; } int64 ThreadInterlockedExchange64( int64 volatile *pDest, int64 value ) { Assert( (size_t)pDest % 8 == 0 ); int64 Old; do { Old = *pDest; } while (ThreadInterlockedCompareExchange64(pDest, value, Old) != Old); return Old; } bool ThreadInterlockedAssignIf64(volatile int64 *pDest, int64 value, int64 comperand ) { Assert( (size_t)pDest % 8 == 0 ); return ( ThreadInterlockedCompareExchange64( pDest, value, comperand ) == comperand ); } bool ThreadInterlockedAssignIf( long volatile *pDest, long value, long comperand ) { Assert( (size_t)pDest % 4 == 0 ); return ( ThreadInterlockedCompareExchange( pDest, value, comperand ) == comperand ); } #endif //----------------------------------------------------------------------------- #if defined(_WIN32) && defined(THREAD_PROFILER) void ThreadNotifySyncNoop(void *p) {} #define MAP_THREAD_PROFILER_CALL( from, to ) \ void from(void *p) \ { \ static CDynamicFunction<void (*)(void *)> dynFunc( "libittnotify.dll", #to, ThreadNotifySyncNoop ); \ (*dynFunc)(p); \ } MAP_THREAD_PROFILER_CALL( ThreadNotifySyncPrepare, __itt_notify_sync_prepare ); MAP_THREAD_PROFILER_CALL( ThreadNotifySyncCancel, __itt_notify_sync_cancel ); MAP_THREAD_PROFILER_CALL( ThreadNotifySyncAcquired, __itt_notify_sync_acquired ); MAP_THREAD_PROFILER_CALL( ThreadNotifySyncReleasing, __itt_notify_sync_releasing ); #endif //----------------------------------------------------------------------------- // // CThreadMutex // //----------------------------------------------------------------------------- #ifndef POSIX CThreadMutex::CThreadMutex() { #ifdef THREAD_MUTEX_TRACING_ENABLED memset( &m_CriticalSection, 0, sizeof(m_CriticalSection) ); #endif InitializeCriticalSectionAndSpinCount((CRITICAL_SECTION *)&m_CriticalSection, 4000); #ifdef THREAD_MUTEX_TRACING_SUPPORTED // These need to be initialized unconditionally in case mixing release & debug object modules // Lock and unlock may be emitted as COMDATs, in which case may get spurious output m_currentOwnerID = m_lockCount = 0; m_bTrace = false; #endif } CThreadMutex::~CThreadMutex() { DeleteCriticalSection((CRITICAL_SECTION *)&m_CriticalSection); } #endif // !POSIX #if defined( _WIN32 ) && !defined( _X360 ) typedef BOOL (WINAPI*TryEnterCriticalSectionFunc_t)(LPCRITICAL_SECTION); static CDynamicFunction<TryEnterCriticalSectionFunc_t> DynTryEnterCriticalSection( "Kernel32.dll", "TryEnterCriticalSection" ); #elif defined( _X360 ) #define DynTryEnterCriticalSection TryEnterCriticalSection #endif bool CThreadMutex::TryLock() { #if defined( _WIN32 ) #ifdef THREAD_MUTEX_TRACING_ENABLED uint thisThreadID = ThreadGetCurrentId(); if ( m_bTrace && m_currentOwnerID && ( m_currentOwnerID != thisThreadID ) ) Msg( "Thread %u about to try-wait for lock %p owned by %u\n", ThreadGetCurrentId(), (CRITICAL_SECTION *)&m_CriticalSection, m_currentOwnerID ); #endif if ( DynTryEnterCriticalSection != NULL ) { if ( (*DynTryEnterCriticalSection )( (CRITICAL_SECTION *)&m_CriticalSection ) != FALSE ) { #ifdef THREAD_MUTEX_TRACING_ENABLED if (m_lockCount == 0) { // we now own it for the first time. Set owner information m_currentOwnerID = thisThreadID; if ( m_bTrace ) Msg( "Thread %u now owns lock 0x%p\n", m_currentOwnerID, (CRITICAL_SECTION *)&m_CriticalSection ); } m_lockCount++; #endif return true; } return false; } Lock(); return true; #elif defined( POSIX ) return pthread_mutex_trylock( &m_Mutex ) == 0; #else #error "Implement me!" return true; #endif } //----------------------------------------------------------------------------- // // CThreadFastMutex // //----------------------------------------------------------------------------- #define THREAD_SPIN (8*1024) void CThreadFastMutex::Lock( const uint32 threadId, unsigned nSpinSleepTime ) volatile { int i; if ( nSpinSleepTime != TT_INFINITE ) { for ( i = THREAD_SPIN; i != 0; --i ) { if ( TryLock( threadId ) ) { return; } ThreadPause(); } for ( i = THREAD_SPIN; i != 0; --i ) { if ( TryLock( threadId ) ) { return; } ThreadPause(); if ( i % 1024 == 0 ) { ThreadSleep( 0 ); } } #ifdef _WIN32 if ( !nSpinSleepTime && GetThreadPriority( GetCurrentThread() ) > THREAD_PRIORITY_NORMAL ) { nSpinSleepTime = 1; } else #endif if ( nSpinSleepTime ) { for ( i = THREAD_SPIN; i != 0; --i ) { if ( TryLock( threadId ) ) { return; } ThreadPause(); ThreadSleep( 0 ); } } for ( ;; ) // coded as for instead of while to make easy to breakpoint success { if ( TryLock( threadId ) ) { return; } ThreadPause(); ThreadSleep( nSpinSleepTime ); } } else { for ( ;; ) // coded as for instead of while to make easy to breakpoint success { if ( TryLock( threadId ) ) { return; } ThreadPause(); } } } //----------------------------------------------------------------------------- // // CThreadRWLock // //----------------------------------------------------------------------------- void CThreadRWLock::WaitForRead() { m_nPendingReaders++; do { m_mutex.Unlock(); m_CanRead.Wait(); m_mutex.Lock(); } while (m_nWriters); m_nPendingReaders--; } void CThreadRWLock::LockForWrite() { m_mutex.Lock(); bool bWait = ( m_nWriters != 0 || m_nActiveReaders != 0 ); m_nWriters++; m_CanRead.Reset(); m_mutex.Unlock(); if ( bWait ) { m_CanWrite.Wait(); } } void CThreadRWLock::UnlockWrite() { m_mutex.Lock(); m_nWriters--; if ( m_nWriters == 0) { if ( m_nPendingReaders ) { m_CanRead.Set(); } } else { m_CanWrite.Set(); } m_mutex.Unlock(); } //----------------------------------------------------------------------------- // // CThreadSpinRWLock // //----------------------------------------------------------------------------- void CThreadSpinRWLock::SpinLockForWrite( const uint32 threadId ) { int i; for ( i = 1000; i != 0; --i ) { if ( TryLockForWrite( threadId ) ) { return; } ThreadPause(); } for ( i = 20000; i != 0; --i ) { if ( TryLockForWrite( threadId ) ) { return; } ThreadPause(); ThreadSleep( 0 ); } for ( ;; ) // coded as for instead of while to make easy to breakpoint success { if ( TryLockForWrite( threadId ) ) { return; } ThreadPause(); ThreadSleep( 1 ); } } void CThreadSpinRWLock::LockForRead() { int i; // In order to grab a read lock, the number of readers must not change and no thread can own the write lock LockInfo_t oldValue; LockInfo_t newValue; oldValue.m_nReaders = m_lockInfo.m_nReaders; oldValue.m_writerId = 0; newValue.m_nReaders = oldValue.m_nReaders + 1; newValue.m_writerId = 0; if( m_nWriters == 0 && AssignIf( newValue, oldValue ) ) return; ThreadPause(); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders + 1; for ( i = 1000; i != 0; --i ) { if( m_nWriters == 0 && AssignIf( newValue, oldValue ) ) return; ThreadPause(); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders + 1; } for ( i = 20000; i != 0; --i ) { if( m_nWriters == 0 && AssignIf( newValue, oldValue ) ) return; ThreadPause(); ThreadSleep( 0 ); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders + 1; } for ( ;; ) // coded as for instead of while to make easy to breakpoint success { if( m_nWriters == 0 && AssignIf( newValue, oldValue ) ) return; ThreadPause(); ThreadSleep( 1 ); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders + 1; } } void CThreadSpinRWLock::UnlockRead() { int i; Assert( m_lockInfo.m_nReaders > 0 && m_lockInfo.m_writerId == 0 ); LockInfo_t oldValue; LockInfo_t newValue; oldValue.m_nReaders = m_lockInfo.m_nReaders; oldValue.m_writerId = 0; newValue.m_nReaders = oldValue.m_nReaders - 1; newValue.m_writerId = 0; if( AssignIf( newValue, oldValue ) ) return; ThreadPause(); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders - 1; for ( i = 500; i != 0; --i ) { if( AssignIf( newValue, oldValue ) ) return; ThreadPause(); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders - 1; } for ( i = 20000; i != 0; --i ) { if( AssignIf( newValue, oldValue ) ) return; ThreadPause(); ThreadSleep( 0 ); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders - 1; } for ( ;; ) // coded as for instead of while to make easy to breakpoint success { if( AssignIf( newValue, oldValue ) ) return; ThreadPause(); ThreadSleep( 1 ); oldValue.m_nReaders = m_lockInfo.m_nReaders; newValue.m_nReaders = oldValue.m_nReaders - 1; } } void CThreadSpinRWLock::UnlockWrite() { Assert( m_lockInfo.m_writerId == ThreadGetCurrentId() && m_lockInfo.m_nReaders == 0 ); static const LockInfo_t newValue = { 0, 0 }; #if defined(_X360) // X360TBD: Serious Perf implications, not yet. __sync(); #endif ThreadInterlockedExchange64( (int64 *)&m_lockInfo, *((int64 *)&newValue) ); m_nWriters--; } //----------------------------------------------------------------------------- // // CThread // //----------------------------------------------------------------------------- CThreadLocalPtr<CThread> g_pCurThread; //--------------------------------------------------------- CThread::CThread() : #ifdef _WIN32 m_hThread( NULL ), #endif m_threadId( 0 ), m_result( 0 ), m_flags( 0 ) { m_szName[0] = 0; } //--------------------------------------------------------- CThread::~CThread() { #ifdef _WIN32 if (m_hThread) #elif defined(POSIX) if ( m_threadId ) #endif { if ( IsAlive() ) { Msg( "Illegal termination of worker thread! Threads must negotiate an end to the thread before the CThread object is destroyed.\n" ); #ifdef _WIN32 DoNewAssertDialog( __FILE__, __LINE__, "Illegal termination of worker thread! Threads must negotiate an end to the thread before the CThread object is destroyed.\n" ); #endif if ( GetCurrentCThread() == this ) { Stop(); // BUGBUG: Alfred - this doesn't make sense, this destructor fires from the hosting thread not the thread itself!! } } #ifdef _WIN32 // Now that the worker thread has exited (which we know because we presumably waited // on the thread handle for it to exit) we can finally close the thread handle. We // cannot do this any earlier, and certainly not in CThread::ThreadProc(). CloseHandle( m_hThread ); #endif } } //--------------------------------------------------------- const char *CThread::GetName() { AUTO_LOCK( m_Lock ); if ( !m_szName[0] ) { #ifdef _WIN32 _snprintf( m_szName, sizeof(m_szName) - 1, "Thread(%p/%p)", this, m_hThread ); #elif defined(POSIX) _snprintf( m_szName, sizeof(m_szName) - 1, "Thread(0x%x/0x%x)", (uint)this, (uint)m_threadId ); #endif m_szName[sizeof(m_szName) - 1] = 0; } return m_szName; } //--------------------------------------------------------- void CThread::SetName(const char *pszName) { AUTO_LOCK( m_Lock ); strncpy( m_szName, pszName, sizeof(m_szName) - 1 ); m_szName[sizeof(m_szName) - 1] = 0; } //--------------------------------------------------------- bool CThread::Start( unsigned nBytesStack ) { AUTO_LOCK( m_Lock ); if ( IsAlive() ) { AssertMsg( 0, "Tried to create a thread that has already been created!" ); return false; } bool bInitSuccess = false; CThreadEvent createComplete; ThreadInit_t init = { this, &createComplete, &bInitSuccess }; #ifdef _WIN32 HANDLE hThread; m_hThread = hThread = (HANDLE)VCRHook_CreateThread( NULL, nBytesStack, (LPTHREAD_START_ROUTINE)GetThreadProc(), new ThreadInit_t(init), CREATE_SUSPENDED, &m_threadId ); if ( !hThread ) { AssertMsg1( 0, "Failed to create thread (error 0x%x)", GetLastError() ); return false; } Plat_ApplyHardwareDataBreakpointsToNewThread( m_threadId ); ResumeThread( hThread ); #elif defined(POSIX) pthread_attr_t attr; pthread_attr_init( &attr ); // From http://www.kernel.org/doc/man-pages/online/pages/man3/pthread_attr_setstacksize.3.html // A thread's stack size is fixed at the time of thread creation. Only the main thread can dynamically grow its stack. pthread_attr_setstacksize( &attr, MAX( nBytesStack, 1024u*1024 ) ); if ( pthread_create( &m_threadId, &attr, (void *(*)(void *))GetThreadProc(), new ThreadInit_t( init ) ) != 0 ) { AssertMsg1( 0, "Failed to create thread (error 0x%x)", GetLastError() ); return false; } Plat_ApplyHardwareDataBreakpointsToNewThread( (long unsigned int)m_threadId ); bInitSuccess = true; #endif #if !defined( OSX ) ThreadSetDebugName( m_threadId, m_szName ); #endif if ( !WaitForCreateComplete( &createComplete ) ) { Msg( "Thread failed to initialize\n" ); #ifdef _WIN32 CloseHandle( m_hThread ); m_hThread = NULL; m_threadId = 0; #elif defined(POSIX) m_threadId = 0; #endif return false; } if ( !bInitSuccess ) { Msg( "Thread failed to initialize\n" ); #ifdef _WIN32 CloseHandle( m_hThread ); m_hThread = NULL; m_threadId = 0; #elif defined(POSIX) m_threadId = 0; #endif return false; } #ifdef _WIN32 if ( !m_hThread ) { Msg( "Thread exited immediately\n" ); } #endif #ifdef _WIN32 return !!m_hThread; #elif defined(POSIX) return !!m_threadId; #endif } //--------------------------------------------------------- // // Return true if the thread exists. false otherwise // bool CThread::IsAlive() { #ifdef _WIN32 DWORD dwExitCode; return ( m_hThread && GetExitCodeThread( m_hThread, &dwExitCode ) && dwExitCode == STILL_ACTIVE ); #elif defined(POSIX) return m_threadId; #endif } //--------------------------------------------------------- bool CThread::Join(unsigned timeout) { #ifdef _WIN32 if ( m_hThread ) #elif defined(POSIX) if ( m_threadId ) #endif { AssertMsg(GetCurrentCThread() != this, _T("Thread cannot be joined with self")); #ifdef _WIN32 return ThreadJoin( (ThreadHandle_t)m_hThread ); #elif defined(POSIX) return ThreadJoin( (ThreadHandle_t)m_threadId ); #endif } return true; } //--------------------------------------------------------- #ifdef _WIN32 HANDLE CThread::GetThreadHandle() { return m_hThread; } #endif #if defined( _WIN32 ) || defined( LINUX ) //--------------------------------------------------------- uint CThread::GetThreadId() { return m_threadId; } #endif //--------------------------------------------------------- int CThread::GetResult() { return m_result; } //--------------------------------------------------------- // // Forcibly, abnormally, but relatively cleanly stop the thread // void CThread::Stop(int exitCode) { if ( !IsAlive() ) return; if ( GetCurrentCThread() == this ) { m_result = exitCode; if ( !( m_flags & SUPPORT_STOP_PROTOCOL ) ) { OnExit(); g_pCurThread = (int)NULL; #ifdef _WIN32 CloseHandle( m_hThread ); m_hThread = NULL; #endif Cleanup(); } throw exitCode; } else AssertMsg( 0, "Only thread can stop self: Use a higher-level protocol"); } //--------------------------------------------------------- int CThread::GetPriority() const { #ifdef _WIN32 return GetThreadPriority(m_hThread); #elif defined(POSIX) struct sched_param thread_param; int policy; pthread_getschedparam( m_threadId, &policy, &thread_param ); return thread_param.sched_priority; #endif } //--------------------------------------------------------- bool CThread::SetPriority(int priority) { #ifdef _WIN32 return ThreadSetPriority( (ThreadHandle_t)m_hThread, priority ); #else return ThreadSetPriority( (ThreadHandle_t)m_threadId, priority ); #endif } //--------------------------------------------------------- void CThread::SuspendCooperative() { if ( ThreadGetCurrentId() == (ThreadId_t)m_threadId ) { m_SuspendEventSignal.Set(); m_nSuspendCount = 1; m_SuspendEvent.Wait(); m_nSuspendCount = 0; } else { Assert( !"Suspend not called from worker thread, this would be a bug" ); } } //--------------------------------------------------------- void CThread::ResumeCooperative() { Assert( m_nSuspendCount == 1 ); m_SuspendEvent.Set(); } void CThread::BWaitForThreadSuspendCooperative() { m_SuspendEventSignal.Wait(); } #ifndef LINUX //--------------------------------------------------------- unsigned int CThread::Suspend() { #ifdef _WIN32 return ( SuspendThread(m_hThread) != 0 ); #elif defined(OSX) int susCount = m_nSuspendCount++; while ( thread_suspend( pthread_mach_thread_np(m_threadId) ) != KERN_SUCCESS ) { }; return ( susCount) != 0; #else #error #endif } //--------------------------------------------------------- unsigned int CThread::Resume() { #ifdef _WIN32 return ( ResumeThread(m_hThread) != 0 ); #elif defined(OSX) int susCount = m_nSuspendCount++; while ( thread_resume( pthread_mach_thread_np(m_threadId) ) != KERN_SUCCESS ) { }; return ( susCount - 1) != 0; #else #error #endif } #endif //--------------------------------------------------------- bool CThread::Terminate(int exitCode) { #ifndef _X360 #ifdef _WIN32 // I hope you know what you're doing! if (!TerminateThread(m_hThread, exitCode)) return false; CloseHandle( m_hThread ); m_hThread = NULL; Cleanup(); #elif defined(POSIX) pthread_kill( m_threadId, SIGKILL ); Cleanup(); #endif return true; #else AssertMsg( 0, "Cannot terminate a thread on the Xbox!" ); return false; #endif } //--------------------------------------------------------- // // Get the Thread object that represents the current thread, if any. // Can return NULL if the current thread was not created using // CThread // CThread *CThread::GetCurrentCThread() { return g_pCurThread; } //--------------------------------------------------------- // // Offer a context switch. Under Win32, equivalent to Sleep(0) // void CThread::Yield() { #ifdef _WIN32 ::Sleep(0); #elif defined(POSIX) pthread_yield(); #endif } //--------------------------------------------------------- // // This method causes the current thread to yield and not to be // scheduled for further execution until a certain amount of real // time has elapsed, more or less. // void CThread::Sleep(unsigned duration) { #ifdef _WIN32 ::Sleep(duration); #elif defined(POSIX) usleep( duration * 1000 ); #endif } //--------------------------------------------------------- bool CThread::Init() { return true; } //--------------------------------------------------------- void CThread::OnExit() { } //--------------------------------------------------------- void CThread::Cleanup() { m_threadId = 0; } //--------------------------------------------------------- bool CThread::WaitForCreateComplete(CThreadEvent * pEvent) { // Force serialized thread creation... if (!pEvent->Wait(60000)) { AssertMsg( 0, "Probably deadlock or failure waiting for thread to initialize." ); return false; } return true; } //--------------------------------------------------------- bool CThread::IsThreadRunning() { #ifdef _PS3 // ThreadIsThreadIdRunning() doesn't work on PS3 if the thread is in a zombie state return m_eventTheadExit.Check(); #else return ThreadIsThreadIdRunning( (ThreadId_t)m_threadId ); #endif } //--------------------------------------------------------- CThread::ThreadProc_t CThread::GetThreadProc() { return ThreadProc; } //--------------------------------------------------------- unsigned __stdcall CThread::ThreadProc(LPVOID pv) { std::auto_ptr<ThreadInit_t> pInit((ThreadInit_t *)pv); #ifdef _X360 // Make sure all threads are consistent w.r.t floating-point math SetupFPUControlWord(); #endif CThread *pThread = pInit->pThread; g_pCurThread = pThread; g_pCurThread->m_pStackBase = AlignValue( &pThread, 4096 ); pInit->pThread->m_result = -1; bool bInitSuccess = true; if ( pInit->pfInitSuccess ) *(pInit->pfInitSuccess) = false; try { bInitSuccess = pInit->pThread->Init(); } catch (...) { pInit->pInitCompleteEvent->Set(); throw; } if ( pInit->pfInitSuccess ) *(pInit->pfInitSuccess) = bInitSuccess; pInit->pInitCompleteEvent->Set(); if (!bInitSuccess) return 0; if ( pInit->pThread->m_flags & SUPPORT_STOP_PROTOCOL ) { try { pInit->pThread->m_result = pInit->pThread->Run(); } catch (...) { } } else { pInit->pThread->m_result = pInit->pThread->Run(); } pInit->pThread->OnExit(); g_pCurThread = (int)NULL; pInit->pThread->Cleanup(); return pInit->pThread->m_result; } //----------------------------------------------------------------------------- // //----------------------------------------------------------------------------- CWorkerThread::CWorkerThread() : m_EventSend(true), // must be manual-reset for PeekCall() m_EventComplete(true), // must be manual-reset to handle multiple wait with thread properly m_Param(0), m_pParamFunctor(NULL), m_ReturnVal(0) { } //--------------------------------------------------------- int CWorkerThread::CallWorker(unsigned dw, unsigned timeout, bool fBoostWorkerPriorityToMaster, CFunctor *pParamFunctor) { return Call(dw, timeout, fBoostWorkerPriorityToMaster, NULL, pParamFunctor); } //--------------------------------------------------------- int CWorkerThread::CallMaster(unsigned dw, unsigned timeout) { return Call(dw, timeout, false); } //--------------------------------------------------------- CThreadEvent &CWorkerThread::GetCallHandle() { return m_EventSend; } //--------------------------------------------------------- unsigned CWorkerThread::GetCallParam( CFunctor **ppParamFunctor ) const { if( ppParamFunctor ) *ppParamFunctor = m_pParamFunctor; return m_Param; } //--------------------------------------------------------- int CWorkerThread::BoostPriority() { int iInitialPriority = GetPriority(); const int iNewPriority = ThreadGetPriority( (ThreadHandle_t)GetThreadID() ); if (iNewPriority > iInitialPriority) ThreadSetPriority( (ThreadHandle_t)GetThreadID(), iNewPriority); return iInitialPriority; } //--------------------------------------------------------- static uint32 __stdcall DefaultWaitFunc( int nEvents, CThreadEvent * const *pEvents, int bWaitAll, uint32 timeout ) { return ThreadWaitForEvents( nEvents, pEvents, bWaitAll!=0, timeout ); // return VCRHook_WaitForMultipleObjects( nHandles, (const void **)pHandles, bWaitAll, timeout ); } int CWorkerThread::Call(unsigned dwParam, unsigned timeout, bool fBoostPriority, WaitFunc_t pfnWait, CFunctor *pParamFunctor) { AssertMsg(!m_EventSend.Check(), "Cannot perform call if there's an existing call pending" ); AUTO_LOCK( m_Lock ); if (!IsAlive()) return WTCR_FAIL; int iInitialPriority = 0; if (fBoostPriority) { iInitialPriority = BoostPriority(); } // set the parameter, signal the worker thread, wait for the completion to be signaled m_Param = dwParam; m_pParamFunctor = pParamFunctor; m_EventComplete.Reset(); m_EventSend.Set(); WaitForReply( timeout, pfnWait ); // MWD: Investigate why setting thread priorities is killing the 360 #ifndef _X360 if (fBoostPriority) SetPriority(iInitialPriority); #endif return m_ReturnVal; } //--------------------------------------------------------- // // Wait for a request from the client // //--------------------------------------------------------- int CWorkerThread::WaitForReply( unsigned timeout ) { return WaitForReply( timeout, NULL ); } int CWorkerThread::WaitForReply( unsigned timeout, WaitFunc_t pfnWait ) { if (!pfnWait) { pfnWait = DefaultWaitFunc; } #ifdef WIN32 CThreadEvent threadEvent( GetThreadHandle() ); #endif CThreadEvent *waits[] = { #ifdef WIN32 &threadEvent, #endif &m_EventComplete }; unsigned result; bool bInDebugger = Plat_IsInDebugSession(); do { #ifdef WIN32 // Make sure the thread handle hasn't been closed if ( !GetThreadHandle() ) { result = WAIT_OBJECT_0 + 1; break; } #endif result = (*pfnWait)((sizeof(waits) / sizeof(waits[0])), waits, false, (timeout != TT_INFINITE) ? timeout : 30000); AssertMsg(timeout != TT_INFINITE || result != WAIT_TIMEOUT, "Possible hung thread, call to thread timed out"); } while ( bInDebugger && ( timeout == TT_INFINITE && result == WAIT_TIMEOUT ) ); if ( result != WAIT_OBJECT_0 + 1 ) { if (result == WAIT_TIMEOUT) m_ReturnVal = WTCR_TIMEOUT; else if (result == WAIT_OBJECT_0) { DevMsg( 2, "Thread failed to respond, probably exited\n"); m_EventSend.Reset(); m_ReturnVal = WTCR_TIMEOUT; } else { m_EventSend.Reset(); m_ReturnVal = WTCR_THREAD_GONE; } } return m_ReturnVal; } //--------------------------------------------------------- // // Wait for a request from the client // //--------------------------------------------------------- bool CWorkerThread::WaitForCall(unsigned * pResult) { return WaitForCall(TT_INFINITE, pResult); } //--------------------------------------------------------- bool CWorkerThread::WaitForCall(unsigned dwTimeout, unsigned * pResult) { bool returnVal = m_EventSend.Wait(dwTimeout); if (pResult) *pResult = m_Param; return returnVal; } //--------------------------------------------------------- // // is there a request? // bool CWorkerThread::PeekCall(unsigned * pParam, CFunctor **ppParamFunctor) { if (!m_EventSend.Check()) { return false; } else { if (pParam) { *pParam = m_Param; } if( ppParamFunctor ) { *ppParamFunctor = m_pParamFunctor; } return true; } } //--------------------------------------------------------- // // Reply to the request // void CWorkerThread::Reply(unsigned dw) { m_Param = 0; m_ReturnVal = dw; // The request is now complete so PeekCall() should fail from // now on // // This event should be reset BEFORE we signal the client m_EventSend.Reset(); // Tell the client we're finished m_EventComplete.Set(); } //-----------------------------------------------------------------------------
23.481497
170
0.623307
DeadZoneLuna
0023c903be9762a71077fa56c9ebf7852679051a
87
cpp
C++
externals/kokkos/core/unit_test/default/TestDefaultDeviceTypeInit_16.cpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
1
2019-10-15T19:26:22.000Z
2019-10-15T19:26:22.000Z
externals/kokkos/core/unit_test/default/TestDefaultDeviceTypeInit_16.cpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
16
2019-04-15T20:52:05.000Z
2020-01-24T05:13:25.000Z
externals/kokkos/core/unit_test/default/TestDefaultDeviceTypeInit_16.cpp
meng630/GMD_E3SM_SCM
990f84598b79f9b4763c3a825a7d25f4e0f5a565
[ "FTL", "zlib-acknowledgement", "RSA-MD" ]
1
2019-11-25T14:06:26.000Z
2019-11-25T14:06:26.000Z
#define KOKKOS_DEFAULTDEVICETYPE_INIT_TEST_16 #include <TestDefaultDeviceTypeInit.hpp>
29
45
0.896552
meng630
002552e0e85d1523eda90ef58e511c09fd902c1a
799
hpp
C++
include/pkmn/enums/egg_group.hpp
ncorgan/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
4
2017-06-10T13:21:44.000Z
2019-10-30T21:20:19.000Z
include/pkmn/enums/egg_group.hpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
12
2017-04-05T11:13:34.000Z
2018-06-03T14:31:03.000Z
include/pkmn/enums/egg_group.hpp
PMArkive/libpkmn
c683bf8b85b03eef74a132b5cfdce9be0969d523
[ "MIT" ]
2
2019-01-22T21:02:31.000Z
2019-10-30T21:20:20.000Z
/* * Copyright (c) 2018 Nicholas Corgan (n.corgan@gmail.com) * * Distributed under the MIT License (MIT) (See accompanying file LICENSE.txt * or copy at http://opensource.org/licenses/MIT) */ #ifndef PKMN_ENUMS_EGG_GROUP_HPP #define PKMN_ENUMS_EGG_GROUP_HPP #include <utility> namespace pkmn { enum class e_egg_group { NONE = 0, MONSTER = 1, WATER1 = 2, BUG = 3, FLYING = 4, GROUND = 5, FAIRY = 6, PLANT = 7, HUMANSHAPE = 8, WATER3 = 9, MINERAL = 10, INDETERMINATE = 11, WATER2 = 12, DITTO = 13, DRAGON = 14, UNDISCOVERED = 15, }; using egg_group_pair_t = std::pair<pkmn::e_egg_group, pkmn::e_egg_group>; } #endif /* PKMN_ENUMS_EGG_GROUP_HPP */
20.487179
77
0.579474
ncorgan
002e5930b51f0073fcb5ec059980da4b3a5449b6
433
cpp
C++
misc/md5.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
misc/md5.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
misc/md5.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
unsigned k[64],r[64]={7,12,17,22,7,12,17,22,7,12,17,22,7,12,17,22,5,9,14,20,5 ,9,14,20,5,9,14,20,5,9,14,20,4,11,16,23,4,11,16,23,4,11,16,23,4,11,16,23, 6,10,15,21,6,10,15,21,6,10,15,21,6,10,15,21}; #include<cmath> #include<cstring> const char *md5(char a[]) { static char res[33]; for(i=0;i<63;i++) k[i]=floor(abs(sin(i+1))*(1ll<<32)); n=strlen(a); a[n++]=128; while(n%64!=56) a[n++]=0; }
27.0625
77
0.542725
dk00
002ffe877490ef43d0206adc11aade85d3f56abc
3,493
cpp
C++
RtkServer/mainwindow.cpp
CORAL-CMU/Qt
85f29279e70121d5108c6d9295b2ba09826fba85
[ "MIT" ]
null
null
null
RtkServer/mainwindow.cpp
CORAL-CMU/Qt
85f29279e70121d5108c6d9295b2ba09826fba85
[ "MIT" ]
null
null
null
RtkServer/mainwindow.cpp
CORAL-CMU/Qt
85f29279e70121d5108c6d9295b2ba09826fba85
[ "MIT" ]
2
2021-01-22T14:58:10.000Z
2021-12-24T17:22:42.000Z
#include "mainwindow.h" #include "ui_mainwindow.h" #define GPGGASTR "$GPGGA,000637.10,4026.4183386,N,07956.1275614,W,5,06,1.0,308.021,M,-34.121,M,1.1,*7C" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); client = new QNtripClient(); client->addr="209.255.196.164"; client->port="2101"; client->user="CMU"; client->passwd="CMU"; client->loadCasterList(); connect(client,SIGNAL(signalRtkReceived(QByteArray)),this,SLOT(slotRtkReceived(QByteArray))); server = new QNtripServer("CMU", "CMU"); connect(server,SIGNAL(signalNewConnection(QString)),this,SLOT(slotNewConnection(QString))); connect(server,SIGNAL(signalUpdateGPGGA(QString)),this,SLOT(slotUpdateGPGGA(QString))); connect(server,SIGNAL(signalClientDisconnect(QString)),this,SLOT(slotClientDisconnect(QString))); } MainWindow::~MainWindow() { delete ui; } void MainWindow::on_setcaster_clicked() { QList<QString> casters; for(int i=0;i<client->casterlist.size();i++) { casters.push_back(client->casterlist[i].identifier); } QString caster = QInputDialog::getItem(this,"Select Caster","Caster Identifier:", casters); casterid = casters.indexOf(caster); client->mntpnt = client->casterlist[casterid].mountpoint; client->encodeNtripPath(); ui->casterinfo->setText(client->ntrippath); server->caster = client->casterlist[casterid]; } void MainWindow::on_triggerrtk_clicked() { if(ui->triggerrtk->text()==QString("Start RTK")) { client->startReceiveRtk(casterid, GPGGASTR); ui->setcaster->setEnabled(false); ui->triggerrtk->setText("Stop RTK"); } else if(ui->triggerrtk->text()==QString("Stop RTK")) { client->stopReceiveRtk(); ui->setcaster->setEnabled(true); ui->triggerrtk->setText("Start RTK"); } } void MainWindow::slotRtkReceived(QByteArray rtk) { if(ui->showrtk->isChecked()) { QString content=QString("[%1]\n%2") .arg(QTime::currentTime().toString("HH:mm:ss:zzz")) .arg(QString(rtk)); ui->rtkview->append(content); } server->sendRtk(rtk); } void MainWindow::slotNewConnection(QString peer) { QString content=QString("[%1]\n%2 Connected") .arg(QTime::currentTime().toString("HH:mm:ss:zzz")) .arg(peer); ui->serverlog->append(content); } void MainWindow::slotUpdateGPGGA(QString GPGGA) { client->stopReceiveRtk(); this->thread()->sleep(2); client->startReceiveRtk(casterid, GPGGA); QString content=QString("[%1]\n%2") .arg(QTime::currentTime().toString("HH:mm:ss:zzz")) .arg(GPGGA); ui->serverlog->append(content); } void MainWindow::slotClientDisconnect(QString peer) { QString content=QString("[%1]\n%2 Disconnected") .arg(QTime::currentTime().toString("HH:mm:ss:zzz")) .arg(peer); ui->serverlog->append(content); } void MainWindow::on_triggerserver_clicked() { if(ui->triggerserver->text()==QString("Open Server")) { server->openServer(QHostAddress::Any,12346); ui->triggerserver->setText("Close Server"); } else if(ui->triggerserver->text()==QString("Close Server")) { server->closeServer(); ui->triggerserver->setText("Open Server"); } }
30.112069
104
0.6284
CORAL-CMU
0031dd4a87c00acaa7a66eeac4932568affff836
2,097
cpp
C++
savefinalmoviedialog.cpp
chennes/Stop_Motion_Animation
282c65a38053202c4e35735a0bf0a53797dc1481
[ "MIT" ]
3
2015-09-28T13:14:06.000Z
2019-11-28T13:23:10.000Z
savefinalmoviedialog.cpp
chennes/Stop_Motion_Animation
282c65a38053202c4e35735a0bf0a53797dc1481
[ "MIT" ]
42
2017-03-26T15:22:37.000Z
2019-04-05T13:42:00.000Z
savefinalmoviedialog.cpp
chennes/Stop_Motion_Animation
282c65a38053202c4e35735a0bf0a53797dc1481
[ "MIT" ]
null
null
null
#include "savefinalmoviedialog.h" #include "ui_savefinalmoviedialog.h" #include "settings.h" #include <QFileDialog> SaveFinalMovieDialog::SaveFinalMovieDialog(QWidget *parent) : QDialog(parent), ui(new Ui::SaveFinalMovieDialog) { ui->setupUi(this); } SaveFinalMovieDialog::~SaveFinalMovieDialog() { delete ui; } void SaveFinalMovieDialog::reset(const QString &filename, const QString &title, const QString &credits) { Settings settings; // Title duration double titleScreenDuration = settings.Get("settings/titleScreenDuration").toDouble(); // Credits duration double creditsDuration = settings.Get("settings/creditsDuration").toDouble(); ui->movieSaveLocationLabel->setText(filename); if (titleScreenDuration > 0) { if (title.length() > 0) { ui->movieTitleLineEdit->setText(title); } else { ui->movieTitleLineEdit->clear(); ui->movieTitleLineEdit->setPlaceholderText("Enter a title here"); } } else { ui->movieTitleLineEdit->hide(); ui->movieTitleLabel->hide(); } if (creditsDuration > 0) { if (credits.length() > 0) { ui->creditsPlainTextEdit->setPlainText(credits); } else { ui->creditsPlainTextEdit->clear(); ui->creditsPlainTextEdit->setPlaceholderText("Type your credits in here"); } } else { ui->creditsPlainTextEdit->hide(); ui->creditsLabel->hide(); } adjustSize(); } QString SaveFinalMovieDialog::filename() const { return ui->movieSaveLocationLabel->text(); } QString SaveFinalMovieDialog::movieTitle() const { return ui->movieTitleLineEdit->text(); } QString SaveFinalMovieDialog::credits() const { return ui->creditsPlainTextEdit->toPlainText(); } void SaveFinalMovieDialog::on_changeLocationButton_clicked() { QString newFilename = QFileDialog::getSaveFileName(this, "Save movie to...", "", "Movie files (*.mp4);;All files (*.*)"); if (newFilename.length() > 0) { ui->movieSaveLocationLabel->setText(newFilename); } }
26.544304
125
0.664759
chennes
00408717f68559db68f82d23584f4cf23a8b0a5d
667
cpp
C++
torch_mlu/csrc/aten/operators/cnnl/alias.cpp
Cambricon/catch
2625da389f25a67066d20fb6b0c38250ef98f8ab
[ "BSD-2-Clause" ]
20
2022-03-01T11:40:51.000Z
2022-03-30T08:17:47.000Z
torch_mlu/csrc/aten/operators/cnnl/alias.cpp
Cambricon/catch
2625da389f25a67066d20fb6b0c38250ef98f8ab
[ "BSD-2-Clause" ]
null
null
null
torch_mlu/csrc/aten/operators/cnnl/alias.cpp
Cambricon/catch
2625da389f25a67066d20fb6b0c38250ef98f8ab
[ "BSD-2-Clause" ]
null
null
null
#include "aten/operators/cnnl/cnnl_kernel.h" #include "aten/operators/cnnl/internal/cnnl_internal.h" namespace torch_mlu { namespace cnnl { namespace ops { at::Tensor cnnl_alias(const at::Tensor& self) { at::Tensor self_; auto impl = c10::make_intrusive<MLUTensorImpl>(at::Storage(self.storage()), self.key_set(), self.dtype()); impl->set_storage_offset(self.storage_offset()); impl->set_sizes_and_strides(self.sizes(), self.strides()); self_ = at::Tensor(std::move(impl)); return self_; } } // namespace ops } // namespace cnnl } // namespace torch_mlu
30.318182
78
0.62069
Cambricon
00464c5a92c00871f4d4193630101fe0ed9827fa
600,257
cc
C++
fbench/src/grpcclient/third_party/googleapis/gens/google/privacy/dlp/v2/storage.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/privacy/dlp/v2/storage.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
fbench/src/grpcclient/third_party/googleapis/gens/google/privacy/dlp/v2/storage.pb.cc
kashiish/vespa
307de4bb24463d0f36cd8391a7b8df75bd0949b2
[ "Apache-2.0" ]
null
null
null
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/privacy/dlp/v2/storage.proto #include "google/privacy/dlp/v2/storage.pb.h" #include <algorithm> #include <google/protobuf/stubs/common.h> #include <google/protobuf/io/coded_stream.h> #include <google/protobuf/extension_set.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> // @@protoc_insertion_point(includes) #include <google/protobuf/port_def.inc> extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_DetectionRule_LikelihoodAdjustment_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_DetectionRule_Proximity_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_SurrogateType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_HybridOptions_LabelsEntry_DoNotUse_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_InfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Key_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_KindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_PartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_BigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_CloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_CloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_CustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_DatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_StoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<1> scc_info_TableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_BigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_CustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_DatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_HybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_Key_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<2> scc_info_StorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto ::google::protobuf::internal::SCCInfo<3> scc_info_CustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto; extern PROTOBUF_INTERNAL_EXPORT_google_2fprotobuf_2ftimestamp_2eproto ::google::protobuf::internal::SCCInfo<0> scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto; namespace google { namespace privacy { namespace dlp { namespace v2 { class InfoTypeDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<InfoType> _instance; } _InfoType_default_instance_; class StoredTypeDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<StoredType> _instance; } _StoredType_default_instance_; class CustomInfoType_Dictionary_WordListDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_Dictionary_WordList> _instance; } _CustomInfoType_Dictionary_WordList_default_instance_; class CustomInfoType_DictionaryDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_Dictionary> _instance; const ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList* word_list_; const ::google::privacy::dlp::v2::CloudStoragePath* cloud_storage_path_; } _CustomInfoType_Dictionary_default_instance_; class CustomInfoType_RegexDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_Regex> _instance; } _CustomInfoType_Regex_default_instance_; class CustomInfoType_SurrogateTypeDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_SurrogateType> _instance; } _CustomInfoType_SurrogateType_default_instance_; class CustomInfoType_DetectionRule_ProximityDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_DetectionRule_Proximity> _instance; } _CustomInfoType_DetectionRule_Proximity_default_instance_; class CustomInfoType_DetectionRule_LikelihoodAdjustmentDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_DetectionRule_LikelihoodAdjustment> _instance; int fixed_likelihood_; ::google::protobuf::int32 relative_likelihood_; } _CustomInfoType_DetectionRule_LikelihoodAdjustment_default_instance_; class CustomInfoType_DetectionRule_HotwordRuleDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_DetectionRule_HotwordRule> _instance; } _CustomInfoType_DetectionRule_HotwordRule_default_instance_; class CustomInfoType_DetectionRuleDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType_DetectionRule> _instance; const ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule* hotword_rule_; } _CustomInfoType_DetectionRule_default_instance_; class CustomInfoTypeDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CustomInfoType> _instance; const ::google::privacy::dlp::v2::CustomInfoType_Dictionary* dictionary_; const ::google::privacy::dlp::v2::CustomInfoType_Regex* regex_; const ::google::privacy::dlp::v2::CustomInfoType_SurrogateType* surrogate_type_; const ::google::privacy::dlp::v2::StoredType* stored_type_; } _CustomInfoType_default_instance_; class FieldIdDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<FieldId> _instance; } _FieldId_default_instance_; class PartitionIdDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<PartitionId> _instance; } _PartitionId_default_instance_; class KindExpressionDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<KindExpression> _instance; } _KindExpression_default_instance_; class DatastoreOptionsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<DatastoreOptions> _instance; } _DatastoreOptions_default_instance_; class CloudStorageRegexFileSetDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CloudStorageRegexFileSet> _instance; } _CloudStorageRegexFileSet_default_instance_; class CloudStorageOptions_FileSetDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CloudStorageOptions_FileSet> _instance; } _CloudStorageOptions_FileSet_default_instance_; class CloudStorageOptionsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CloudStorageOptions> _instance; } _CloudStorageOptions_default_instance_; class CloudStorageFileSetDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CloudStorageFileSet> _instance; } _CloudStorageFileSet_default_instance_; class CloudStoragePathDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<CloudStoragePath> _instance; } _CloudStoragePath_default_instance_; class BigQueryOptionsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BigQueryOptions> _instance; } _BigQueryOptions_default_instance_; class StorageConfig_TimespanConfigDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<StorageConfig_TimespanConfig> _instance; } _StorageConfig_TimespanConfig_default_instance_; class StorageConfigDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<StorageConfig> _instance; const ::google::privacy::dlp::v2::DatastoreOptions* datastore_options_; const ::google::privacy::dlp::v2::CloudStorageOptions* cloud_storage_options_; const ::google::privacy::dlp::v2::BigQueryOptions* big_query_options_; const ::google::privacy::dlp::v2::HybridOptions* hybrid_options_; } _StorageConfig_default_instance_; class HybridOptions_LabelsEntry_DoNotUseDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HybridOptions_LabelsEntry_DoNotUse> _instance; } _HybridOptions_LabelsEntry_DoNotUse_default_instance_; class HybridOptionsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<HybridOptions> _instance; } _HybridOptions_default_instance_; class BigQueryKeyDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BigQueryKey> _instance; } _BigQueryKey_default_instance_; class DatastoreKeyDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<DatastoreKey> _instance; } _DatastoreKey_default_instance_; class Key_PathElementDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Key_PathElement> _instance; ::google::protobuf::int64 id_; ::google::protobuf::internal::ArenaStringPtr name_; } _Key_PathElement_default_instance_; class KeyDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<Key> _instance; } _Key_default_instance_; class RecordKeyDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<RecordKey> _instance; const ::google::privacy::dlp::v2::DatastoreKey* datastore_key_; const ::google::privacy::dlp::v2::BigQueryKey* big_query_key_; } _RecordKey_default_instance_; class BigQueryTableDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BigQueryTable> _instance; } _BigQueryTable_default_instance_; class BigQueryFieldDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<BigQueryField> _instance; } _BigQueryField_default_instance_; class EntityIdDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<EntityId> _instance; } _EntityId_default_instance_; class TableOptionsDefaultTypeInternal { public: ::google::protobuf::internal::ExplicitlyConstructed<TableOptions> _instance; } _TableOptions_default_instance_; } // namespace v2 } // namespace dlp } // namespace privacy } // namespace google static void InitDefaultsInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_InfoType_default_instance_; new (ptr) ::google::privacy::dlp::v2::InfoType(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::InfoType::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_InfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsStoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_StoredType_default_instance_; new (ptr) ::google::privacy::dlp::v2::StoredType(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::StoredType::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_StoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsStoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto.base,}}; static void InitDefaultsCustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_Dictionary_WordList_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsCustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_Dictionary_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_Dictionary(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_Dictionary::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_CustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsCustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_CustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsCustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_Regex_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_Regex(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_Regex::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsCustomInfoType_SurrogateType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_SurrogateType_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_SurrogateType(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_SurrogateType::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_SurrogateType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCustomInfoType_SurrogateType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsCustomInfoType_DetectionRule_Proximity_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_Proximity_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_DetectionRule_Proximity_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCustomInfoType_DetectionRule_Proximity_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsCustomInfoType_DetectionRule_LikelihoodAdjustment_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_LikelihoodAdjustment_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CustomInfoType_DetectionRule_LikelihoodAdjustment_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCustomInfoType_DetectionRule_LikelihoodAdjustment_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsCustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_HotwordRule_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<3> scc_info_CustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 3, InitDefaultsCustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_CustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CustomInfoType_DetectionRule_Proximity_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CustomInfoType_DetectionRule_LikelihoodAdjustment_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsCustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType_DetectionRule(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType_DetectionRule::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_CustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_CustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsCustomInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CustomInfoType_default_instance_; new (ptr) ::google::privacy::dlp::v2::CustomInfoType(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CustomInfoType::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<6> scc_info_CustomInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 6, InitDefaultsCustomInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_InfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CustomInfoType_SurrogateType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_StoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsFieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_FieldId_default_instance_; new (ptr) ::google::privacy::dlp::v2::FieldId(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::FieldId::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsFieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsPartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_PartitionId_default_instance_; new (ptr) ::google::privacy::dlp::v2::PartitionId(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::PartitionId::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_PartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsPartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsKindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_KindExpression_default_instance_; new (ptr) ::google::privacy::dlp::v2::KindExpression(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::KindExpression::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_KindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsKindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsDatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_DatastoreOptions_default_instance_; new (ptr) ::google::privacy::dlp::v2::DatastoreOptions(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::DatastoreOptions::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_DatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsDatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_PartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_KindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsCloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CloudStorageRegexFileSet_default_instance_; new (ptr) ::google::privacy::dlp::v2::CloudStorageRegexFileSet(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CloudStorageRegexFileSet::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsCloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CloudStorageOptions_FileSet_default_instance_; new (ptr) ::google::privacy::dlp::v2::CloudStorageOptions_FileSet(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CloudStorageOptions_FileSet::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_CloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_CloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsCloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CloudStorageOptions_default_instance_; new (ptr) ::google::privacy::dlp::v2::CloudStorageOptions(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CloudStorageOptions::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_CloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsCloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_CloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsCloudStorageFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CloudStorageFileSet_default_instance_; new (ptr) ::google::privacy::dlp::v2::CloudStorageFileSet(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CloudStorageFileSet::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CloudStorageFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCloudStorageFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsCloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_CloudStoragePath_default_instance_; new (ptr) ::google::privacy::dlp::v2::CloudStoragePath(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::CloudStoragePath::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_CloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsCloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsBigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_BigQueryOptions_default_instance_; new (ptr) ::google::privacy::dlp::v2::BigQueryOptions(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::BigQueryOptions::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_BigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsBigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsStorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_StorageConfig_TimespanConfig_default_instance_; new (ptr) ::google::privacy::dlp::v2::StorageConfig_TimespanConfig(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::StorageConfig_TimespanConfig::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_StorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsStorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_Timestamp_google_2fprotobuf_2ftimestamp_2eproto.base, &scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsStorageConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_StorageConfig_default_instance_; new (ptr) ::google::privacy::dlp::v2::StorageConfig(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::StorageConfig::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<5> scc_info_StorageConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 5, InitDefaultsStorageConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_DatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_CloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_BigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_HybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_StorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsHybridOptions_LabelsEntry_DoNotUse_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_HybridOptions_LabelsEntry_DoNotUse_default_instance_; new (ptr) ::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse(); } ::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_HybridOptions_LabelsEntry_DoNotUse_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsHybridOptions_LabelsEntry_DoNotUse_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsHybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_HybridOptions_default_instance_; new (ptr) ::google::privacy::dlp::v2::HybridOptions(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::HybridOptions::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_HybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsHybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_HybridOptions_LabelsEntry_DoNotUse_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_TableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsBigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_BigQueryKey_default_instance_; new (ptr) ::google::privacy::dlp::v2::BigQueryKey(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::BigQueryKey::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_BigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsBigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsDatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_DatastoreKey_default_instance_; new (ptr) ::google::privacy::dlp::v2::DatastoreKey(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::DatastoreKey::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_DatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsDatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_Key_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsKey_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_Key_PathElement_default_instance_; new (ptr) ::google::privacy::dlp::v2::Key_PathElement(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::Key_PathElement::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_Key_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsKey_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_Key_default_instance_; new (ptr) ::google::privacy::dlp::v2::Key(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::Key::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_Key_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_PartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_Key_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsRecordKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_RecordKey_default_instance_; new (ptr) ::google::privacy::dlp::v2::RecordKey(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::RecordKey::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_RecordKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsRecordKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_DatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_BigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsBigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_BigQueryTable_default_instance_; new (ptr) ::google::privacy::dlp::v2::BigQueryTable(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::BigQueryTable::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<0> scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 0, InitDefaultsBigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, {}}; static void InitDefaultsBigQueryField_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_BigQueryField_default_instance_; new (ptr) ::google::privacy::dlp::v2::BigQueryField(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::BigQueryField::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<2> scc_info_BigQueryField_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 2, InitDefaultsBigQueryField_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base, &scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsEntityId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_EntityId_default_instance_; new (ptr) ::google::privacy::dlp::v2::EntityId(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::EntityId::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_EntityId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsEntityId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; static void InitDefaultsTableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { GOOGLE_PROTOBUF_VERIFY_VERSION; { void* ptr = &::google::privacy::dlp::v2::_TableOptions_default_instance_; new (ptr) ::google::privacy::dlp::v2::TableOptions(); ::google::protobuf::internal::OnShutdownDestroyMessage(ptr); } ::google::privacy::dlp::v2::TableOptions::InitAsDefaultInstance(); } ::google::protobuf::internal::SCCInfo<1> scc_info_TableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = {{ATOMIC_VAR_INIT(::google::protobuf::internal::SCCInfoBase::kUninitialized), 1, InitDefaultsTableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto}, { &scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base,}}; void InitDefaults_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { ::google::protobuf::internal::InitSCC(&scc_info_InfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_StoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_SurrogateType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_DetectionRule_Proximity_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_DetectionRule_LikelihoodAdjustment_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CustomInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_PartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_KindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_DatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CloudStorageFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_CloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_BigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_StorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_StorageConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_HybridOptions_LabelsEntry_DoNotUse_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_HybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_BigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_DatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_Key_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_Key_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_RecordKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_BigQueryField_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_EntityId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::google::protobuf::internal::InitSCC(&scc_info_TableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); } ::google::protobuf::Metadata file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[34]; const ::google::protobuf::EnumDescriptor* file_level_enum_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[5]; constexpr ::google::protobuf::ServiceDescriptor const** file_level_service_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = nullptr; const ::google::protobuf::uint32 TableStruct_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto::offsets[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::InfoType, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::InfoType, name_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StoredType, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StoredType, name_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StoredType, create_time_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList, words_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Dictionary, _internal_metadata_), ~0u, // no _extensions_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Dictionary, _oneof_case_[0]), ~0u, // no _weak_field_map_ offsetof(::google::privacy::dlp::v2::CustomInfoType_DictionaryDefaultTypeInternal, word_list_), offsetof(::google::privacy::dlp::v2::CustomInfoType_DictionaryDefaultTypeInternal, cloud_storage_path_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Dictionary, source_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Regex, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Regex, pattern_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_Regex, group_indexes_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_SurrogateType, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity, window_before_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity, window_after_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment, _internal_metadata_), ~0u, // no _extensions_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment, _oneof_case_[0]), ~0u, // no _weak_field_map_ offsetof(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustmentDefaultTypeInternal, fixed_likelihood_), offsetof(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustmentDefaultTypeInternal, relative_likelihood_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment, adjustment_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule, hotword_regex_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule, proximity_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule, likelihood_adjustment_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule, _internal_metadata_), ~0u, // no _extensions_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule, _oneof_case_[0]), ~0u, // no _weak_field_map_ offsetof(::google::privacy::dlp::v2::CustomInfoType_DetectionRuleDefaultTypeInternal, hotword_rule_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType_DetectionRule, type_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType, _internal_metadata_), ~0u, // no _extensions_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType, _oneof_case_[0]), ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType, info_type_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType, likelihood_), offsetof(::google::privacy::dlp::v2::CustomInfoTypeDefaultTypeInternal, dictionary_), offsetof(::google::privacy::dlp::v2::CustomInfoTypeDefaultTypeInternal, regex_), offsetof(::google::privacy::dlp::v2::CustomInfoTypeDefaultTypeInternal, surrogate_type_), offsetof(::google::privacy::dlp::v2::CustomInfoTypeDefaultTypeInternal, stored_type_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType, detection_rules_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType, exclusion_type_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CustomInfoType, type_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::FieldId, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::FieldId, name_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::PartitionId, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::PartitionId, project_id_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::PartitionId, namespace_id_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::KindExpression, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::KindExpression, name_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::DatastoreOptions, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::DatastoreOptions, partition_id_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::DatastoreOptions, kind_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageRegexFileSet, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageRegexFileSet, bucket_name_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageRegexFileSet, include_regex_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageRegexFileSet, exclude_regex_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions_FileSet, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions_FileSet, url_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions_FileSet, regex_file_set_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions, file_set_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions, bytes_limit_per_file_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions, bytes_limit_per_file_percent_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions, file_types_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions, sample_method_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageOptions, files_limit_percent_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageFileSet, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStorageFileSet, url_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStoragePath, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::CloudStoragePath, path_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryOptions, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryOptions, table_reference_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryOptions, identifying_fields_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryOptions, rows_limit_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryOptions, rows_limit_percent_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryOptions, sample_method_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryOptions, excluded_fields_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig_TimespanConfig, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig_TimespanConfig, start_time_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig_TimespanConfig, end_time_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig_TimespanConfig, timestamp_field_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig_TimespanConfig, enable_auto_population_of_timespan_config_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig, _internal_metadata_), ~0u, // no _extensions_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig, _oneof_case_[0]), ~0u, // no _weak_field_map_ offsetof(::google::privacy::dlp::v2::StorageConfigDefaultTypeInternal, datastore_options_), offsetof(::google::privacy::dlp::v2::StorageConfigDefaultTypeInternal, cloud_storage_options_), offsetof(::google::privacy::dlp::v2::StorageConfigDefaultTypeInternal, big_query_options_), offsetof(::google::privacy::dlp::v2::StorageConfigDefaultTypeInternal, hybrid_options_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig, timespan_config_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::StorageConfig, type_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse, _has_bits_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse, key_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse, value_), 0, 1, ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions, description_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions, required_finding_label_keys_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions, labels_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::HybridOptions, table_options_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryKey, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryKey, table_reference_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryKey, row_number_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::DatastoreKey, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::DatastoreKey, entity_key_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::Key_PathElement, _internal_metadata_), ~0u, // no _extensions_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::Key_PathElement, _oneof_case_[0]), ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::Key_PathElement, kind_), offsetof(::google::privacy::dlp::v2::Key_PathElementDefaultTypeInternal, id_), offsetof(::google::privacy::dlp::v2::Key_PathElementDefaultTypeInternal, name_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::Key_PathElement, id_type_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::Key, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::Key, partition_id_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::Key, path_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::RecordKey, _internal_metadata_), ~0u, // no _extensions_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::RecordKey, _oneof_case_[0]), ~0u, // no _weak_field_map_ offsetof(::google::privacy::dlp::v2::RecordKeyDefaultTypeInternal, datastore_key_), offsetof(::google::privacy::dlp::v2::RecordKeyDefaultTypeInternal, big_query_key_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::RecordKey, id_values_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::RecordKey, type_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryTable, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryTable, project_id_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryTable, dataset_id_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryTable, table_id_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryField, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryField, table_), PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::BigQueryField, field_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::EntityId, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::EntityId, field_), ~0u, // no _has_bits_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::TableOptions, _internal_metadata_), ~0u, // no _extensions_ ~0u, // no _oneof_case_ ~0u, // no _weak_field_map_ PROTOBUF_FIELD_OFFSET(::google::privacy::dlp::v2::TableOptions, identifying_fields_), }; static const ::google::protobuf::internal::MigrationSchema schemas[] PROTOBUF_SECTION_VARIABLE(protodesc_cold) = { { 0, -1, sizeof(::google::privacy::dlp::v2::InfoType)}, { 6, -1, sizeof(::google::privacy::dlp::v2::StoredType)}, { 13, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList)}, { 19, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_Dictionary)}, { 27, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_Regex)}, { 34, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_SurrogateType)}, { 39, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity)}, { 46, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment)}, { 54, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule)}, { 62, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType_DetectionRule)}, { 69, -1, sizeof(::google::privacy::dlp::v2::CustomInfoType)}, { 83, -1, sizeof(::google::privacy::dlp::v2::FieldId)}, { 89, -1, sizeof(::google::privacy::dlp::v2::PartitionId)}, { 96, -1, sizeof(::google::privacy::dlp::v2::KindExpression)}, { 102, -1, sizeof(::google::privacy::dlp::v2::DatastoreOptions)}, { 109, -1, sizeof(::google::privacy::dlp::v2::CloudStorageRegexFileSet)}, { 117, -1, sizeof(::google::privacy::dlp::v2::CloudStorageOptions_FileSet)}, { 124, -1, sizeof(::google::privacy::dlp::v2::CloudStorageOptions)}, { 135, -1, sizeof(::google::privacy::dlp::v2::CloudStorageFileSet)}, { 141, -1, sizeof(::google::privacy::dlp::v2::CloudStoragePath)}, { 147, -1, sizeof(::google::privacy::dlp::v2::BigQueryOptions)}, { 158, -1, sizeof(::google::privacy::dlp::v2::StorageConfig_TimespanConfig)}, { 167, -1, sizeof(::google::privacy::dlp::v2::StorageConfig)}, { 178, 185, sizeof(::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse)}, { 187, -1, sizeof(::google::privacy::dlp::v2::HybridOptions)}, { 196, -1, sizeof(::google::privacy::dlp::v2::BigQueryKey)}, { 203, -1, sizeof(::google::privacy::dlp::v2::DatastoreKey)}, { 209, -1, sizeof(::google::privacy::dlp::v2::Key_PathElement)}, { 218, -1, sizeof(::google::privacy::dlp::v2::Key)}, { 225, -1, sizeof(::google::privacy::dlp::v2::RecordKey)}, { 234, -1, sizeof(::google::privacy::dlp::v2::BigQueryTable)}, { 242, -1, sizeof(::google::privacy::dlp::v2::BigQueryField)}, { 249, -1, sizeof(::google::privacy::dlp::v2::EntityId)}, { 255, -1, sizeof(::google::privacy::dlp::v2::TableOptions)}, }; static ::google::protobuf::Message const * const file_default_instances[] = { reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_InfoType_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_StoredType_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_Dictionary_WordList_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_Dictionary_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_Regex_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_SurrogateType_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_Proximity_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_LikelihoodAdjustment_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_HotwordRule_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CustomInfoType_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_FieldId_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_PartitionId_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_KindExpression_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_DatastoreOptions_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CloudStorageRegexFileSet_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CloudStorageOptions_FileSet_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CloudStorageOptions_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CloudStorageFileSet_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_CloudStoragePath_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_BigQueryOptions_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_StorageConfig_TimespanConfig_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_StorageConfig_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_HybridOptions_LabelsEntry_DoNotUse_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_HybridOptions_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_BigQueryKey_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_DatastoreKey_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_Key_PathElement_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_Key_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_RecordKey_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_BigQueryTable_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_BigQueryField_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_EntityId_default_instance_), reinterpret_cast<const ::google::protobuf::Message*>(&::google::privacy::dlp::v2::_TableOptions_default_instance_), }; ::google::protobuf::internal::AssignDescriptorsTable assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = { {}, AddDescriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, "google/privacy/dlp/v2/storage.proto", schemas, file_default_instances, TableStruct_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto::offsets, file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, 34, file_level_enum_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, file_level_service_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, }; const char descriptor_table_protodef_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[] = "\n#google/privacy/dlp/v2/storage.proto\022\025g" "oogle.privacy.dlp.v2\032\031google/api/resourc" "e.proto\032\037google/protobuf/timestamp.proto" "\032\034google/api/annotations.proto\"\030\n\010InfoTy" "pe\022\014\n\004name\030\001 \001(\t\"K\n\nStoredType\022\014\n\004name\030\001" " \001(\t\022/\n\013create_time\030\002 \001(\0132\032.google.proto" "buf.Timestamp\"\310\013\n\016CustomInfoType\0222\n\tinfo" "_type\030\001 \001(\0132\037.google.privacy.dlp.v2.Info" "Type\0225\n\nlikelihood\030\006 \001(\0162!.google.privac" "y.dlp.v2.Likelihood\022F\n\ndictionary\030\002 \001(\0132" "0.google.privacy.dlp.v2.CustomInfoType.D" "ictionaryH\000\022<\n\005regex\030\003 \001(\0132+.google.priv" "acy.dlp.v2.CustomInfoType.RegexH\000\022M\n\016sur" "rogate_type\030\004 \001(\01323.google.privacy.dlp.v" "2.CustomInfoType.SurrogateTypeH\000\0228\n\013stor" "ed_type\030\005 \001(\0132!.google.privacy.dlp.v2.St" "oredTypeH\000\022L\n\017detection_rules\030\007 \003(\01323.go" "ogle.privacy.dlp.v2.CustomInfoType.Detec" "tionRule\022K\n\016exclusion_type\030\010 \001(\01623.googl" "e.privacy.dlp.v2.CustomInfoType.Exclusio" "nType\032\310\001\n\nDictionary\022N\n\tword_list\030\001 \001(\0132" "9.google.privacy.dlp.v2.CustomInfoType.D" "ictionary.WordListH\000\022E\n\022cloud_storage_pa" "th\030\003 \001(\0132\'.google.privacy.dlp.v2.CloudSt" "oragePathH\000\032\031\n\010WordList\022\r\n\005words\030\001 \003(\tB\010" "\n\006source\032/\n\005Regex\022\017\n\007pattern\030\001 \001(\t\022\025\n\rgr" "oup_indexes\030\002 \003(\005\032\017\n\rSurrogateType\032\276\004\n\rD" "etectionRule\022W\n\014hotword_rule\030\001 \001(\0132\?.goo" "gle.privacy.dlp.v2.CustomInfoType.Detect" "ionRule.HotwordRuleH\000\0328\n\tProximity\022\025\n\rwi" "ndow_before\030\001 \001(\005\022\024\n\014window_after\030\002 \001(\005\032" "\202\001\n\024LikelihoodAdjustment\022=\n\020fixed_likeli" "hood\030\001 \001(\0162!.google.privacy.dlp.v2.Likel" "ihoodH\000\022\035\n\023relative_likelihood\030\002 \001(\005H\000B\014" "\n\nadjustment\032\214\002\n\013HotwordRule\022B\n\rhotword_" "regex\030\001 \001(\0132+.google.privacy.dlp.v2.Cust" "omInfoType.Regex\022P\n\tproximity\030\002 \001(\0132=.go" "ogle.privacy.dlp.v2.CustomInfoType.Detec" "tionRule.Proximity\022g\n\025likelihood_adjustm" "ent\030\003 \001(\0132H.google.privacy.dlp.v2.Custom" "InfoType.DetectionRule.LikelihoodAdjustm" "entB\006\n\004type\"K\n\rExclusionType\022\036\n\032EXCLUSIO" "N_TYPE_UNSPECIFIED\020\000\022\032\n\026EXCLUSION_TYPE_E" "XCLUDE\020\001B\006\n\004type\"\027\n\007FieldId\022\014\n\004name\030\001 \001(" "\t\"7\n\013PartitionId\022\022\n\nproject_id\030\002 \001(\t\022\024\n\014" "namespace_id\030\004 \001(\t\"\036\n\016KindExpression\022\014\n\004" "name\030\001 \001(\t\"\201\001\n\020DatastoreOptions\0228\n\014parti" "tion_id\030\001 \001(\0132\".google.privacy.dlp.v2.Pa" "rtitionId\0223\n\004kind\030\002 \001(\0132%.google.privacy" ".dlp.v2.KindExpression\"]\n\030CloudStorageRe" "gexFileSet\022\023\n\013bucket_name\030\001 \001(\t\022\025\n\rinclu" "de_regex\030\002 \003(\t\022\025\n\rexclude_regex\030\003 \003(\t\"\354\003" "\n\023CloudStorageOptions\022D\n\010file_set\030\001 \001(\0132" "2.google.privacy.dlp.v2.CloudStorageOpti" "ons.FileSet\022\034\n\024bytes_limit_per_file\030\004 \001(" "\003\022$\n\034bytes_limit_per_file_percent\030\010 \001(\005\022" "3\n\nfile_types\030\005 \003(\0162\037.google.privacy.dlp" ".v2.FileType\022N\n\rsample_method\030\006 \001(\01627.go" "ogle.privacy.dlp.v2.CloudStorageOptions." "SampleMethod\022\033\n\023files_limit_percent\030\007 \001(" "\005\032_\n\007FileSet\022\013\n\003url\030\001 \001(\t\022G\n\016regex_file_" "set\030\002 \001(\0132/.google.privacy.dlp.v2.CloudS" "torageRegexFileSet\"H\n\014SampleMethod\022\035\n\031SA" "MPLE_METHOD_UNSPECIFIED\020\000\022\007\n\003TOP\020\001\022\020\n\014RA" "NDOM_START\020\002\"\"\n\023CloudStorageFileSet\022\013\n\003u" "rl\030\001 \001(\t\" \n\020CloudStoragePath\022\014\n\004path\030\001 \001" "(\t\"\213\003\n\017BigQueryOptions\022=\n\017table_referenc" "e\030\001 \001(\0132$.google.privacy.dlp.v2.BigQuery" "Table\022:\n\022identifying_fields\030\002 \003(\0132\036.goog" "le.privacy.dlp.v2.FieldId\022\022\n\nrows_limit\030" "\003 \001(\003\022\032\n\022rows_limit_percent\030\006 \001(\005\022J\n\rsam" "ple_method\030\004 \001(\01623.google.privacy.dlp.v2" ".BigQueryOptions.SampleMethod\0227\n\017exclude" "d_fields\030\005 \003(\0132\036.google.privacy.dlp.v2.F" "ieldId\"H\n\014SampleMethod\022\035\n\031SAMPLE_METHOD_" "UNSPECIFIED\020\000\022\007\n\003TOP\020\001\022\020\n\014RANDOM_START\020\002" "\"\332\004\n\rStorageConfig\022D\n\021datastore_options\030" "\002 \001(\0132\'.google.privacy.dlp.v2.DatastoreO" "ptionsH\000\022K\n\025cloud_storage_options\030\003 \001(\0132" "*.google.privacy.dlp.v2.CloudStorageOpti" "onsH\000\022C\n\021big_query_options\030\004 \001(\0132&.googl" "e.privacy.dlp.v2.BigQueryOptionsH\000\022>\n\016hy" "brid_options\030\t \001(\0132$.google.privacy.dlp." "v2.HybridOptionsH\000\022L\n\017timespan_config\030\006 " "\001(\01323.google.privacy.dlp.v2.StorageConfi" "g.TimespanConfig\032\332\001\n\016TimespanConfig\022.\n\ns" "tart_time\030\001 \001(\0132\032.google.protobuf.Timest" "amp\022,\n\010end_time\030\002 \001(\0132\032.google.protobuf." "Timestamp\0227\n\017timestamp_field\030\003 \001(\0132\036.goo" "gle.privacy.dlp.v2.FieldId\0221\n)enable_aut" "o_population_of_timespan_config\030\004 \001(\010B\006\n" "\004type\"\366\001\n\rHybridOptions\022\023\n\013description\030\001" " \001(\t\022#\n\033required_finding_label_keys\030\002 \003(" "\t\022@\n\006labels\030\003 \003(\01320.google.privacy.dlp.v" "2.HybridOptions.LabelsEntry\022:\n\rtable_opt" "ions\030\004 \001(\0132#.google.privacy.dlp.v2.Table" "Options\032-\n\013LabelsEntry\022\013\n\003key\030\001 \001(\t\022\r\n\005v" "alue\030\002 \001(\t:\0028\001\"`\n\013BigQueryKey\022=\n\017table_r" "eference\030\001 \001(\0132$.google.privacy.dlp.v2.B" "igQueryTable\022\022\n\nrow_number\030\002 \001(\003\">\n\014Data" "storeKey\022.\n\nentity_key\030\001 \001(\0132\032.google.pr" "ivacy.dlp.v2.Key\"\273\001\n\003Key\0228\n\014partition_id" "\030\001 \001(\0132\".google.privacy.dlp.v2.Partition" "Id\0224\n\004path\030\002 \003(\0132&.google.privacy.dlp.v2" ".Key.PathElement\032D\n\013PathElement\022\014\n\004kind\030" "\001 \001(\t\022\014\n\002id\030\002 \001(\003H\000\022\016\n\004name\030\003 \001(\tH\000B\t\n\007i" "d_type\"\241\001\n\tRecordKey\022<\n\rdatastore_key\030\002 " "\001(\0132#.google.privacy.dlp.v2.DatastoreKey" "H\000\022;\n\rbig_query_key\030\003 \001(\0132\".google.priva" "cy.dlp.v2.BigQueryKeyH\000\022\021\n\tid_values\030\005 \003" "(\tB\006\n\004type\"I\n\rBigQueryTable\022\022\n\nproject_i" "d\030\001 \001(\t\022\022\n\ndataset_id\030\002 \001(\t\022\020\n\010table_id\030" "\003 \001(\t\"s\n\rBigQueryField\0223\n\005table\030\001 \001(\0132$." "google.privacy.dlp.v2.BigQueryTable\022-\n\005f" "ield\030\002 \001(\0132\036.google.privacy.dlp.v2.Field" "Id\"9\n\010EntityId\022-\n\005field\030\001 \001(\0132\036.google.p" "rivacy.dlp.v2.FieldId\"J\n\014TableOptions\022:\n" "\022identifying_fields\030\001 \003(\0132\036.google.priva" "cy.dlp.v2.FieldId*t\n\nLikelihood\022\032\n\026LIKEL" "IHOOD_UNSPECIFIED\020\000\022\021\n\rVERY_UNLIKELY\020\001\022\014" "\n\010UNLIKELY\020\002\022\014\n\010POSSIBLE\020\003\022\n\n\006LIKELY\020\004\022\017" "\n\013VERY_LIKELY\020\005*\177\n\010FileType\022\031\n\025FILE_TYPE" "_UNSPECIFIED\020\000\022\017\n\013BINARY_FILE\020\001\022\r\n\tTEXT_" "FILE\020\002\022\t\n\005IMAGE\020\003\022\010\n\004WORD\020\005\022\007\n\003PDF\020\006\022\010\n\004" "AVRO\020\007\022\007\n\003CSV\020\010\022\007\n\003TSV\020\tB\250\001\n\031com.google." "privacy.dlp.v2B\nDlpStorageP\001Z8google.gol" "ang.org/genproto/googleapis/privacy/dlp/" "v2;dlp\252\002\023Google.Cloud.Dlp.V2\312\002\023Google\\Cl" "oud\\Dlp\\V2\352\002\026Google::Cloud::Dlp::V2b\006pro" "to3" ; ::google::protobuf::internal::DescriptorTable descriptor_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = { false, InitDefaults_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, descriptor_table_protodef_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, "google/privacy/dlp/v2/storage.proto", &assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, 5163, }; void AddDescriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto() { static constexpr ::google::protobuf::internal::InitFunc deps[3] = { ::AddDescriptors_google_2fapi_2fresource_2eproto, ::AddDescriptors_google_2fprotobuf_2ftimestamp_2eproto, ::AddDescriptors_google_2fapi_2fannotations_2eproto, }; ::google::protobuf::internal::AddDescriptors(&descriptor_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto, deps, 3); } // Force running AddDescriptors() at dynamic initialization time. static bool dynamic_init_dummy_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto = []() { AddDescriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto(); return true; }(); namespace google { namespace privacy { namespace dlp { namespace v2 { const ::google::protobuf::EnumDescriptor* CustomInfoType_ExclusionType_descriptor() { ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return file_level_enum_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[0]; } bool CustomInfoType_ExclusionType_IsValid(int value) { switch (value) { case 0: case 1: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const CustomInfoType_ExclusionType CustomInfoType::EXCLUSION_TYPE_UNSPECIFIED; const CustomInfoType_ExclusionType CustomInfoType::EXCLUSION_TYPE_EXCLUDE; const CustomInfoType_ExclusionType CustomInfoType::ExclusionType_MIN; const CustomInfoType_ExclusionType CustomInfoType::ExclusionType_MAX; const int CustomInfoType::ExclusionType_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 const ::google::protobuf::EnumDescriptor* CloudStorageOptions_SampleMethod_descriptor() { ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return file_level_enum_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[1]; } bool CloudStorageOptions_SampleMethod_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const CloudStorageOptions_SampleMethod CloudStorageOptions::SAMPLE_METHOD_UNSPECIFIED; const CloudStorageOptions_SampleMethod CloudStorageOptions::TOP; const CloudStorageOptions_SampleMethod CloudStorageOptions::RANDOM_START; const CloudStorageOptions_SampleMethod CloudStorageOptions::SampleMethod_MIN; const CloudStorageOptions_SampleMethod CloudStorageOptions::SampleMethod_MAX; const int CloudStorageOptions::SampleMethod_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 const ::google::protobuf::EnumDescriptor* BigQueryOptions_SampleMethod_descriptor() { ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return file_level_enum_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[2]; } bool BigQueryOptions_SampleMethod_IsValid(int value) { switch (value) { case 0: case 1: case 2: return true; default: return false; } } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const BigQueryOptions_SampleMethod BigQueryOptions::SAMPLE_METHOD_UNSPECIFIED; const BigQueryOptions_SampleMethod BigQueryOptions::TOP; const BigQueryOptions_SampleMethod BigQueryOptions::RANDOM_START; const BigQueryOptions_SampleMethod BigQueryOptions::SampleMethod_MIN; const BigQueryOptions_SampleMethod BigQueryOptions::SampleMethod_MAX; const int BigQueryOptions::SampleMethod_ARRAYSIZE; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 const ::google::protobuf::EnumDescriptor* Likelihood_descriptor() { ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return file_level_enum_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[3]; } bool Likelihood_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 4: case 5: return true; default: return false; } } const ::google::protobuf::EnumDescriptor* FileType_descriptor() { ::google::protobuf::internal::AssignDescriptors(&assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return file_level_enum_descriptors_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[4]; } bool FileType_IsValid(int value) { switch (value) { case 0: case 1: case 2: case 3: case 5: case 6: case 7: case 8: case 9: return true; default: return false; } } // =================================================================== void InfoType::InitAsDefaultInstance() { } class InfoType::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int InfoType::kNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 InfoType::InfoType() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.InfoType) } InfoType::InfoType(const InfoType& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.InfoType) } void InfoType::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_InfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } InfoType::~InfoType() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.InfoType) SharedDtor(); } void InfoType::SharedDtor() { name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void InfoType::SetCachedSize(int size) const { _cached_size_.Set(size); } const InfoType& InfoType::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_InfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void InfoType::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.InfoType) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* InfoType::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<InfoType*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.InfoType.name"); object = msg->mutable_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool InfoType::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.InfoType) 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) == (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, "google.privacy.dlp.v2.InfoType.name")); } 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:google.privacy.dlp.v2.InfoType) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.InfoType) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void InfoType::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.InfoType) ::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, "google.privacy.dlp.v2.InfoType.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.InfoType) } ::google::protobuf::uint8* InfoType::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.InfoType) ::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, "google.privacy.dlp.v2.InfoType.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.InfoType) return target; } size_t InfoType::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.InfoType) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // 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 InfoType::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.InfoType) GOOGLE_DCHECK_NE(&from, this); const InfoType* source = ::google::protobuf::DynamicCastToGenerated<InfoType>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.InfoType) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.InfoType) MergeFrom(*source); } } void InfoType::MergeFrom(const InfoType& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.InfoType) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } } void InfoType::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.InfoType) if (&from == this) return; Clear(); MergeFrom(from); } void InfoType::CopyFrom(const InfoType& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.InfoType) if (&from == this) return; Clear(); MergeFrom(from); } bool InfoType::IsInitialized() const { return true; } void InfoType::Swap(InfoType* other) { if (other == this) return; InternalSwap(other); } void InfoType::InternalSwap(InfoType* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata InfoType::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void StoredType::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_StoredType_default_instance_._instance.get_mutable()->create_time_ = const_cast< ::google::protobuf::Timestamp*>( ::google::protobuf::Timestamp::internal_default_instance()); } class StoredType::HasBitSetters { public: static const ::google::protobuf::Timestamp& create_time(const StoredType* msg); }; const ::google::protobuf::Timestamp& StoredType::HasBitSetters::create_time(const StoredType* msg) { return *msg->create_time_; } void StoredType::clear_create_time() { if (GetArenaNoVirtual() == nullptr && create_time_ != nullptr) { delete create_time_; } create_time_ = nullptr; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int StoredType::kNameFieldNumber; const int StoredType::kCreateTimeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 StoredType::StoredType() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.StoredType) } StoredType::StoredType(const StoredType& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } if (from.has_create_time()) { create_time_ = new ::google::protobuf::Timestamp(*from.create_time_); } else { create_time_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.StoredType) } void StoredType::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_StoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); create_time_ = nullptr; } StoredType::~StoredType() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.StoredType) SharedDtor(); } void StoredType::SharedDtor() { name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete create_time_; } void StoredType::SetCachedSize(int size) const { _cached_size_.Set(size); } const StoredType& StoredType::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_StoredType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void StoredType::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.StoredType) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == nullptr && create_time_ != nullptr) { delete create_time_; } create_time_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* StoredType::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<StoredType*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.StoredType.name"); object = msg->mutable_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // .google.protobuf.Timestamp create_time = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::Timestamp::_InternalParse; object = msg->mutable_create_time(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool StoredType::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.StoredType) 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) == (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, "google.privacy.dlp.v2.StoredType.name")); } else { goto handle_unusual; } break; } // .google.protobuf.Timestamp create_time = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_create_time())); } 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:google.privacy.dlp.v2.StoredType) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.StoredType) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void StoredType::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.StoredType) ::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, "google.privacy.dlp.v2.StoredType.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } // .google.protobuf.Timestamp create_time = 2; if (this->has_create_time()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::create_time(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.StoredType) } ::google::protobuf::uint8* StoredType::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.StoredType) ::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, "google.privacy.dlp.v2.StoredType.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } // .google.protobuf.Timestamp create_time = 2; if (this->has_create_time()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::create_time(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.StoredType) return target; } size_t StoredType::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.StoredType) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string name = 1; if (this->name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); } // .google.protobuf.Timestamp create_time = 2; if (this->has_create_time()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *create_time_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void StoredType::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.StoredType) GOOGLE_DCHECK_NE(&from, this); const StoredType* source = ::google::protobuf::DynamicCastToGenerated<StoredType>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.StoredType) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.StoredType) MergeFrom(*source); } } void StoredType::MergeFrom(const StoredType& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.StoredType) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } if (from.has_create_time()) { mutable_create_time()->::google::protobuf::Timestamp::MergeFrom(from.create_time()); } } void StoredType::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.StoredType) if (&from == this) return; Clear(); MergeFrom(from); } void StoredType::CopyFrom(const StoredType& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.StoredType) if (&from == this) return; Clear(); MergeFrom(from); } bool StoredType::IsInitialized() const { return true; } void StoredType::Swap(StoredType* other) { if (other == this) return; InternalSwap(other); } void StoredType::InternalSwap(StoredType* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(create_time_, other->create_time_); } ::google::protobuf::Metadata StoredType::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_Dictionary_WordList::InitAsDefaultInstance() { } class CustomInfoType_Dictionary_WordList::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType_Dictionary_WordList::kWordsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_Dictionary_WordList::CustomInfoType_Dictionary_WordList() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) } CustomInfoType_Dictionary_WordList::CustomInfoType_Dictionary_WordList(const CustomInfoType_Dictionary_WordList& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), words_(from.words_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) } void CustomInfoType_Dictionary_WordList::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); } CustomInfoType_Dictionary_WordList::~CustomInfoType_Dictionary_WordList() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) SharedDtor(); } void CustomInfoType_Dictionary_WordList::SharedDtor() { } void CustomInfoType_Dictionary_WordList::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_Dictionary_WordList& CustomInfoType_Dictionary_WordList::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_Dictionary_WordList_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_Dictionary_WordList::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; words_.Clear(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_Dictionary_WordList::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_Dictionary_WordList*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // repeated string words = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList.words"); object = msg->add_words(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_Dictionary_WordList::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) 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 string words = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_words())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->words(this->words_size() - 1).data(), static_cast<int>(this->words(this->words_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList.words")); } 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:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_Dictionary_WordList::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated string words = 1; for (int i = 0, n = this->words_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->words(i).data(), static_cast<int>(this->words(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList.words"); ::google::protobuf::internal::WireFormatLite::WriteString( 1, this->words(i), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) } ::google::protobuf::uint8* CustomInfoType_Dictionary_WordList::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated string words = 1; for (int i = 0, n = this->words_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->words(i).data(), static_cast<int>(this->words(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList.words"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(1, this->words(i), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) return target; } size_t CustomInfoType_Dictionary_WordList::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string words = 1; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->words_size()); for (int i = 0, n = this->words_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->words(i)); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_Dictionary_WordList::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_Dictionary_WordList* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_Dictionary_WordList>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) MergeFrom(*source); } } void CustomInfoType_Dictionary_WordList::MergeFrom(const CustomInfoType_Dictionary_WordList& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; words_.MergeFrom(from.words_); } void CustomInfoType_Dictionary_WordList::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_Dictionary_WordList::CopyFrom(const CustomInfoType_Dictionary_WordList& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_Dictionary_WordList::IsInitialized() const { return true; } void CustomInfoType_Dictionary_WordList::Swap(CustomInfoType_Dictionary_WordList* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_Dictionary_WordList::InternalSwap(CustomInfoType_Dictionary_WordList* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); words_.InternalSwap(CastToBase(&other->words_)); } ::google::protobuf::Metadata CustomInfoType_Dictionary_WordList::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_Dictionary::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_CustomInfoType_Dictionary_default_instance_.word_list_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList*>( ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList::internal_default_instance()); ::google::privacy::dlp::v2::_CustomInfoType_Dictionary_default_instance_.cloud_storage_path_ = const_cast< ::google::privacy::dlp::v2::CloudStoragePath*>( ::google::privacy::dlp::v2::CloudStoragePath::internal_default_instance()); } class CustomInfoType_Dictionary::HasBitSetters { public: static const ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList& word_list(const CustomInfoType_Dictionary* msg); static const ::google::privacy::dlp::v2::CloudStoragePath& cloud_storage_path(const CustomInfoType_Dictionary* msg); }; const ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList& CustomInfoType_Dictionary::HasBitSetters::word_list(const CustomInfoType_Dictionary* msg) { return *msg->source_.word_list_; } const ::google::privacy::dlp::v2::CloudStoragePath& CustomInfoType_Dictionary::HasBitSetters::cloud_storage_path(const CustomInfoType_Dictionary* msg) { return *msg->source_.cloud_storage_path_; } void CustomInfoType_Dictionary::set_allocated_word_list(::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList* word_list) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_source(); if (word_list) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { word_list = ::google::protobuf::internal::GetOwnedMessage( message_arena, word_list, submessage_arena); } set_has_word_list(); source_.word_list_ = word_list; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.CustomInfoType.Dictionary.word_list) } void CustomInfoType_Dictionary::set_allocated_cloud_storage_path(::google::privacy::dlp::v2::CloudStoragePath* cloud_storage_path) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_source(); if (cloud_storage_path) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { cloud_storage_path = ::google::protobuf::internal::GetOwnedMessage( message_arena, cloud_storage_path, submessage_arena); } set_has_cloud_storage_path(); source_.cloud_storage_path_ = cloud_storage_path; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.CustomInfoType.Dictionary.cloud_storage_path) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType_Dictionary::kWordListFieldNumber; const int CustomInfoType_Dictionary::kCloudStoragePathFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_Dictionary::CustomInfoType_Dictionary() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.Dictionary) } CustomInfoType_Dictionary::CustomInfoType_Dictionary(const CustomInfoType_Dictionary& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_source(); switch (from.source_case()) { case kWordList: { mutable_word_list()->::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList::MergeFrom(from.word_list()); break; } case kCloudStoragePath: { mutable_cloud_storage_path()->::google::privacy::dlp::v2::CloudStoragePath::MergeFrom(from.cloud_storage_path()); break; } case SOURCE_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.Dictionary) } void CustomInfoType_Dictionary::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); clear_has_source(); } CustomInfoType_Dictionary::~CustomInfoType_Dictionary() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.Dictionary) SharedDtor(); } void CustomInfoType_Dictionary::SharedDtor() { if (has_source()) { clear_source(); } } void CustomInfoType_Dictionary::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_Dictionary& CustomInfoType_Dictionary::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_Dictionary_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_Dictionary::clear_source() { // @@protoc_insertion_point(one_of_clear_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) switch (source_case()) { case kWordList: { delete source_.word_list_; break; } case kCloudStoragePath: { delete source_.cloud_storage_path_; break; } case SOURCE_NOT_SET: { break; } } _oneof_case_[0] = SOURCE_NOT_SET; } void CustomInfoType_Dictionary::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; clear_source(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_Dictionary::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_Dictionary*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList word_list = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList::_InternalParse; object = msg->mutable_word_list(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.CloudStoragePath cloud_storage_path = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CloudStoragePath::_InternalParse; object = msg->mutable_cloud_storage_path(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_Dictionary::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) 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)) { // .google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList word_list = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_word_list())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CloudStoragePath cloud_storage_path = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_cloud_storage_path())); } 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:google.privacy.dlp.v2.CustomInfoType.Dictionary) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.Dictionary) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_Dictionary::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList word_list = 1; if (has_word_list()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::word_list(this), output); } // .google.privacy.dlp.v2.CloudStoragePath cloud_storage_path = 3; if (has_cloud_storage_path()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, HasBitSetters::cloud_storage_path(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.Dictionary) } ::google::protobuf::uint8* CustomInfoType_Dictionary::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList word_list = 1; if (has_word_list()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::word_list(this), target); } // .google.privacy.dlp.v2.CloudStoragePath cloud_storage_path = 3; if (has_cloud_storage_path()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, HasBitSetters::cloud_storage_path(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.Dictionary) return target; } size_t CustomInfoType_Dictionary::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; switch (source_case()) { // .google.privacy.dlp.v2.CustomInfoType.Dictionary.WordList word_list = 1; case kWordList: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *source_.word_list_); break; } // .google.privacy.dlp.v2.CloudStoragePath cloud_storage_path = 3; case kCloudStoragePath: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *source_.cloud_storage_path_); break; } case SOURCE_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_Dictionary::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_Dictionary* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_Dictionary>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.Dictionary) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.Dictionary) MergeFrom(*source); } } void CustomInfoType_Dictionary::MergeFrom(const CustomInfoType_Dictionary& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; switch (from.source_case()) { case kWordList: { mutable_word_list()->::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList::MergeFrom(from.word_list()); break; } case kCloudStoragePath: { mutable_cloud_storage_path()->::google::privacy::dlp::v2::CloudStoragePath::MergeFrom(from.cloud_storage_path()); break; } case SOURCE_NOT_SET: { break; } } } void CustomInfoType_Dictionary::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_Dictionary::CopyFrom(const CustomInfoType_Dictionary& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.Dictionary) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_Dictionary::IsInitialized() const { return true; } void CustomInfoType_Dictionary::Swap(CustomInfoType_Dictionary* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_Dictionary::InternalSwap(CustomInfoType_Dictionary* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(source_, other->source_); swap(_oneof_case_[0], other->_oneof_case_[0]); } ::google::protobuf::Metadata CustomInfoType_Dictionary::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_Regex::InitAsDefaultInstance() { } class CustomInfoType_Regex::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType_Regex::kPatternFieldNumber; const int CustomInfoType_Regex::kGroupIndexesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_Regex::CustomInfoType_Regex() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.Regex) } CustomInfoType_Regex::CustomInfoType_Regex(const CustomInfoType_Regex& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), group_indexes_(from.group_indexes_) { _internal_metadata_.MergeFrom(from._internal_metadata_); pattern_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.pattern().size() > 0) { pattern_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.pattern_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.Regex) } void CustomInfoType_Regex::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); pattern_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } CustomInfoType_Regex::~CustomInfoType_Regex() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.Regex) SharedDtor(); } void CustomInfoType_Regex::SharedDtor() { pattern_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void CustomInfoType_Regex::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_Regex& CustomInfoType_Regex::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_Regex_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_Regex::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.Regex) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; group_indexes_.Clear(); pattern_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_Regex::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_Regex*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string pattern = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CustomInfoType.Regex.pattern"); object = msg->mutable_pattern(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // repeated int32 group_indexes = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) == 18) { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::PackedInt32Parser; object = msg->mutable_group_indexes(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; if (size) ptr = parser_till_end(ptr, newend, object, ctx); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } else if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; do { msg->add_group_indexes(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 16 && (ptr += 1)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_Regex::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.Regex) 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 pattern = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_pattern())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->pattern().data(), static_cast<int>(this->pattern().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CustomInfoType.Regex.pattern")); } else { goto handle_unusual; } break; } // repeated int32 group_indexes = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPackedPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, this->mutable_group_indexes()))); } else if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadRepeatedPrimitiveNoInline< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( 1, 18u, input, this->mutable_group_indexes()))); } 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:google.privacy.dlp.v2.CustomInfoType.Regex) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.Regex) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_Regex::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.Regex) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string pattern = 1; if (this->pattern().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->pattern().data(), static_cast<int>(this->pattern().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CustomInfoType.Regex.pattern"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->pattern(), output); } // repeated int32 group_indexes = 2; if (this->group_indexes_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag(2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_group_indexes_cached_byte_size_.load( std::memory_order_relaxed)); } for (int i = 0, n = this->group_indexes_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteInt32NoTag( this->group_indexes(i), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.Regex) } ::google::protobuf::uint8* CustomInfoType_Regex::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.Regex) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string pattern = 1; if (this->pattern().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->pattern().data(), static_cast<int>(this->pattern().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CustomInfoType.Regex.pattern"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->pattern(), target); } // repeated int32 group_indexes = 2; if (this->group_indexes_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 2, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _group_indexes_cached_byte_size_.load(std::memory_order_relaxed), target); target = ::google::protobuf::internal::WireFormatLite:: WriteInt32NoTagToArray(this->group_indexes_, target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.Regex) return target; } size_t CustomInfoType_Regex::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.Regex) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated int32 group_indexes = 2; { size_t data_size = ::google::protobuf::internal::WireFormatLite:: Int32Size(this->group_indexes_); 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); _group_indexes_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // string pattern = 1; if (this->pattern().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->pattern()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_Regex::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.Regex) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_Regex* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_Regex>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.Regex) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.Regex) MergeFrom(*source); } } void CustomInfoType_Regex::MergeFrom(const CustomInfoType_Regex& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.Regex) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; group_indexes_.MergeFrom(from.group_indexes_); if (from.pattern().size() > 0) { pattern_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.pattern_); } } void CustomInfoType_Regex::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.Regex) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_Regex::CopyFrom(const CustomInfoType_Regex& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.Regex) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_Regex::IsInitialized() const { return true; } void CustomInfoType_Regex::Swap(CustomInfoType_Regex* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_Regex::InternalSwap(CustomInfoType_Regex* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); group_indexes_.InternalSwap(&other->group_indexes_); pattern_.Swap(&other->pattern_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata CustomInfoType_Regex::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_SurrogateType::InitAsDefaultInstance() { } class CustomInfoType_SurrogateType::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_SurrogateType::CustomInfoType_SurrogateType() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.SurrogateType) } CustomInfoType_SurrogateType::CustomInfoType_SurrogateType(const CustomInfoType_SurrogateType& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.SurrogateType) } void CustomInfoType_SurrogateType::SharedCtor() { } CustomInfoType_SurrogateType::~CustomInfoType_SurrogateType() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.SurrogateType) SharedDtor(); } void CustomInfoType_SurrogateType::SharedDtor() { } void CustomInfoType_SurrogateType::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_SurrogateType& CustomInfoType_SurrogateType::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_SurrogateType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_SurrogateType::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_SurrogateType::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_SurrogateType*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { default: { if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_SurrogateType::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) for (;;) { ::std::pair<::google::protobuf::uint32, bool> p = input->ReadTagWithCutoffNoLastTag(127u); tag = p.first; if (!p.second) goto handle_unusual; handle_unusual: if (tag == 0) { goto success; } DO_(::google::protobuf::internal::WireFormat::SkipField( input, tag, _internal_metadata_.mutable_unknown_fields())); } success: // @@protoc_insertion_point(parse_success:google.privacy.dlp.v2.CustomInfoType.SurrogateType) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.SurrogateType) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_SurrogateType::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.SurrogateType) } ::google::protobuf::uint8* CustomInfoType_SurrogateType::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.SurrogateType) return target; } size_t CustomInfoType_SurrogateType::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_SurrogateType::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_SurrogateType* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_SurrogateType>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.SurrogateType) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.SurrogateType) MergeFrom(*source); } } void CustomInfoType_SurrogateType::MergeFrom(const CustomInfoType_SurrogateType& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; } void CustomInfoType_SurrogateType::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_SurrogateType::CopyFrom(const CustomInfoType_SurrogateType& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.SurrogateType) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_SurrogateType::IsInitialized() const { return true; } void CustomInfoType_SurrogateType::Swap(CustomInfoType_SurrogateType* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_SurrogateType::InternalSwap(CustomInfoType_SurrogateType* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); } ::google::protobuf::Metadata CustomInfoType_SurrogateType::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_DetectionRule_Proximity::InitAsDefaultInstance() { } class CustomInfoType_DetectionRule_Proximity::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType_DetectionRule_Proximity::kWindowBeforeFieldNumber; const int CustomInfoType_DetectionRule_Proximity::kWindowAfterFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_DetectionRule_Proximity::CustomInfoType_DetectionRule_Proximity() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) } CustomInfoType_DetectionRule_Proximity::CustomInfoType_DetectionRule_Proximity(const CustomInfoType_DetectionRule_Proximity& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); ::memcpy(&window_before_, &from.window_before_, static_cast<size_t>(reinterpret_cast<char*>(&window_after_) - reinterpret_cast<char*>(&window_before_)) + sizeof(window_after_)); // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) } void CustomInfoType_DetectionRule_Proximity::SharedCtor() { ::memset(&window_before_, 0, static_cast<size_t>( reinterpret_cast<char*>(&window_after_) - reinterpret_cast<char*>(&window_before_)) + sizeof(window_after_)); } CustomInfoType_DetectionRule_Proximity::~CustomInfoType_DetectionRule_Proximity() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) SharedDtor(); } void CustomInfoType_DetectionRule_Proximity::SharedDtor() { } void CustomInfoType_DetectionRule_Proximity::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_DetectionRule_Proximity& CustomInfoType_DetectionRule_Proximity::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_DetectionRule_Proximity_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_DetectionRule_Proximity::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; ::memset(&window_before_, 0, static_cast<size_t>( reinterpret_cast<char*>(&window_after_) - reinterpret_cast<char*>(&window_before_)) + sizeof(window_after_)); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_DetectionRule_Proximity::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_DetectionRule_Proximity*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // int32 window_before = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; msg->set_window_before(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // int32 window_after = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; msg->set_window_after(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_DetectionRule_Proximity::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) 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)) { // int32 window_before = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &window_before_))); } else { goto handle_unusual; } break; } // int32 window_after = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &window_after_))); } 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:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_DetectionRule_Proximity::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 window_before = 1; if (this->window_before() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(1, this->window_before(), output); } // int32 window_after = 2; if (this->window_after() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->window_after(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) } ::google::protobuf::uint8* CustomInfoType_DetectionRule_Proximity::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // int32 window_before = 1; if (this->window_before() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(1, this->window_before(), target); } // int32 window_after = 2; if (this->window_after() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->window_after(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) return target; } size_t CustomInfoType_DetectionRule_Proximity::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // int32 window_before = 1; if (this->window_before() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->window_before()); } // int32 window_after = 2; if (this->window_after() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->window_after()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_DetectionRule_Proximity::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_DetectionRule_Proximity* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_DetectionRule_Proximity>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) MergeFrom(*source); } } void CustomInfoType_DetectionRule_Proximity::MergeFrom(const CustomInfoType_DetectionRule_Proximity& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.window_before() != 0) { set_window_before(from.window_before()); } if (from.window_after() != 0) { set_window_after(from.window_after()); } } void CustomInfoType_DetectionRule_Proximity::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_DetectionRule_Proximity::CopyFrom(const CustomInfoType_DetectionRule_Proximity& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_DetectionRule_Proximity::IsInitialized() const { return true; } void CustomInfoType_DetectionRule_Proximity::Swap(CustomInfoType_DetectionRule_Proximity* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_DetectionRule_Proximity::InternalSwap(CustomInfoType_DetectionRule_Proximity* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(window_before_, other->window_before_); swap(window_after_, other->window_after_); } ::google::protobuf::Metadata CustomInfoType_DetectionRule_Proximity::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_DetectionRule_LikelihoodAdjustment::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_LikelihoodAdjustment_default_instance_.fixed_likelihood_ = 0; ::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_LikelihoodAdjustment_default_instance_.relative_likelihood_ = 0; } class CustomInfoType_DetectionRule_LikelihoodAdjustment::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType_DetectionRule_LikelihoodAdjustment::kFixedLikelihoodFieldNumber; const int CustomInfoType_DetectionRule_LikelihoodAdjustment::kRelativeLikelihoodFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_DetectionRule_LikelihoodAdjustment::CustomInfoType_DetectionRule_LikelihoodAdjustment() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) } CustomInfoType_DetectionRule_LikelihoodAdjustment::CustomInfoType_DetectionRule_LikelihoodAdjustment(const CustomInfoType_DetectionRule_LikelihoodAdjustment& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_adjustment(); switch (from.adjustment_case()) { case kFixedLikelihood: { set_fixed_likelihood(from.fixed_likelihood()); break; } case kRelativeLikelihood: { set_relative_likelihood(from.relative_likelihood()); break; } case ADJUSTMENT_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) } void CustomInfoType_DetectionRule_LikelihoodAdjustment::SharedCtor() { clear_has_adjustment(); } CustomInfoType_DetectionRule_LikelihoodAdjustment::~CustomInfoType_DetectionRule_LikelihoodAdjustment() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) SharedDtor(); } void CustomInfoType_DetectionRule_LikelihoodAdjustment::SharedDtor() { if (has_adjustment()) { clear_adjustment(); } } void CustomInfoType_DetectionRule_LikelihoodAdjustment::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_DetectionRule_LikelihoodAdjustment& CustomInfoType_DetectionRule_LikelihoodAdjustment::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_DetectionRule_LikelihoodAdjustment_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_DetectionRule_LikelihoodAdjustment::clear_adjustment() { // @@protoc_insertion_point(one_of_clear_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) switch (adjustment_case()) { case kFixedLikelihood: { // No need to clear break; } case kRelativeLikelihood: { // No need to clear break; } case ADJUSTMENT_NOT_SET: { break; } } _oneof_case_[0] = ADJUSTMENT_NOT_SET; } void CustomInfoType_DetectionRule_LikelihoodAdjustment::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; clear_adjustment(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_DetectionRule_LikelihoodAdjustment::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_DetectionRule_LikelihoodAdjustment*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.Likelihood fixed_likelihood = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 8) goto handle_unusual; ::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr); msg->set_fixed_likelihood(static_cast<::google::privacy::dlp::v2::Likelihood>(val)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // int32 relative_likelihood = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; msg->set_relative_likelihood(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_DetectionRule_LikelihoodAdjustment::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) 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)) { // .google.privacy.dlp.v2.Likelihood fixed_likelihood = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (8 & 0xFF)) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_fixed_likelihood(static_cast< ::google::privacy::dlp::v2::Likelihood >(value)); } else { goto handle_unusual; } break; } // int32 relative_likelihood = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) { clear_adjustment(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &adjustment_.relative_likelihood_))); set_has_relative_likelihood(); } 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:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_DetectionRule_LikelihoodAdjustment::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.Likelihood fixed_likelihood = 1; if (has_fixed_likelihood()) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 1, this->fixed_likelihood(), output); } // int32 relative_likelihood = 2; if (has_relative_likelihood()) { ::google::protobuf::internal::WireFormatLite::WriteInt32(2, this->relative_likelihood(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) } ::google::protobuf::uint8* CustomInfoType_DetectionRule_LikelihoodAdjustment::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.Likelihood fixed_likelihood = 1; if (has_fixed_likelihood()) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 1, this->fixed_likelihood(), target); } // int32 relative_likelihood = 2; if (has_relative_likelihood()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(2, this->relative_likelihood(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) return target; } size_t CustomInfoType_DetectionRule_LikelihoodAdjustment::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; switch (adjustment_case()) { // .google.privacy.dlp.v2.Likelihood fixed_likelihood = 1; case kFixedLikelihood: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->fixed_likelihood()); break; } // int32 relative_likelihood = 2; case kRelativeLikelihood: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->relative_likelihood()); break; } case ADJUSTMENT_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_DetectionRule_LikelihoodAdjustment::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_DetectionRule_LikelihoodAdjustment* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_DetectionRule_LikelihoodAdjustment>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) MergeFrom(*source); } } void CustomInfoType_DetectionRule_LikelihoodAdjustment::MergeFrom(const CustomInfoType_DetectionRule_LikelihoodAdjustment& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; switch (from.adjustment_case()) { case kFixedLikelihood: { set_fixed_likelihood(from.fixed_likelihood()); break; } case kRelativeLikelihood: { set_relative_likelihood(from.relative_likelihood()); break; } case ADJUSTMENT_NOT_SET: { break; } } } void CustomInfoType_DetectionRule_LikelihoodAdjustment::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_DetectionRule_LikelihoodAdjustment::CopyFrom(const CustomInfoType_DetectionRule_LikelihoodAdjustment& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_DetectionRule_LikelihoodAdjustment::IsInitialized() const { return true; } void CustomInfoType_DetectionRule_LikelihoodAdjustment::Swap(CustomInfoType_DetectionRule_LikelihoodAdjustment* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_DetectionRule_LikelihoodAdjustment::InternalSwap(CustomInfoType_DetectionRule_LikelihoodAdjustment* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(adjustment_, other->adjustment_); swap(_oneof_case_[0], other->_oneof_case_[0]); } ::google::protobuf::Metadata CustomInfoType_DetectionRule_LikelihoodAdjustment::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_DetectionRule_HotwordRule::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_HotwordRule_default_instance_._instance.get_mutable()->hotword_regex_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_Regex*>( ::google::privacy::dlp::v2::CustomInfoType_Regex::internal_default_instance()); ::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_HotwordRule_default_instance_._instance.get_mutable()->proximity_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity*>( ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity::internal_default_instance()); ::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_HotwordRule_default_instance_._instance.get_mutable()->likelihood_adjustment_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment*>( ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment::internal_default_instance()); } class CustomInfoType_DetectionRule_HotwordRule::HasBitSetters { public: static const ::google::privacy::dlp::v2::CustomInfoType_Regex& hotword_regex(const CustomInfoType_DetectionRule_HotwordRule* msg); static const ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity& proximity(const CustomInfoType_DetectionRule_HotwordRule* msg); static const ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment& likelihood_adjustment(const CustomInfoType_DetectionRule_HotwordRule* msg); }; const ::google::privacy::dlp::v2::CustomInfoType_Regex& CustomInfoType_DetectionRule_HotwordRule::HasBitSetters::hotword_regex(const CustomInfoType_DetectionRule_HotwordRule* msg) { return *msg->hotword_regex_; } const ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity& CustomInfoType_DetectionRule_HotwordRule::HasBitSetters::proximity(const CustomInfoType_DetectionRule_HotwordRule* msg) { return *msg->proximity_; } const ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment& CustomInfoType_DetectionRule_HotwordRule::HasBitSetters::likelihood_adjustment(const CustomInfoType_DetectionRule_HotwordRule* msg) { return *msg->likelihood_adjustment_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType_DetectionRule_HotwordRule::kHotwordRegexFieldNumber; const int CustomInfoType_DetectionRule_HotwordRule::kProximityFieldNumber; const int CustomInfoType_DetectionRule_HotwordRule::kLikelihoodAdjustmentFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_DetectionRule_HotwordRule::CustomInfoType_DetectionRule_HotwordRule() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) } CustomInfoType_DetectionRule_HotwordRule::CustomInfoType_DetectionRule_HotwordRule(const CustomInfoType_DetectionRule_HotwordRule& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_hotword_regex()) { hotword_regex_ = new ::google::privacy::dlp::v2::CustomInfoType_Regex(*from.hotword_regex_); } else { hotword_regex_ = nullptr; } if (from.has_proximity()) { proximity_ = new ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity(*from.proximity_); } else { proximity_ = nullptr; } if (from.has_likelihood_adjustment()) { likelihood_adjustment_ = new ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment(*from.likelihood_adjustment_); } else { likelihood_adjustment_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) } void CustomInfoType_DetectionRule_HotwordRule::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&hotword_regex_, 0, static_cast<size_t>( reinterpret_cast<char*>(&likelihood_adjustment_) - reinterpret_cast<char*>(&hotword_regex_)) + sizeof(likelihood_adjustment_)); } CustomInfoType_DetectionRule_HotwordRule::~CustomInfoType_DetectionRule_HotwordRule() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) SharedDtor(); } void CustomInfoType_DetectionRule_HotwordRule::SharedDtor() { if (this != internal_default_instance()) delete hotword_regex_; if (this != internal_default_instance()) delete proximity_; if (this != internal_default_instance()) delete likelihood_adjustment_; } void CustomInfoType_DetectionRule_HotwordRule::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_DetectionRule_HotwordRule& CustomInfoType_DetectionRule_HotwordRule::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_DetectionRule_HotwordRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_DetectionRule_HotwordRule::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && hotword_regex_ != nullptr) { delete hotword_regex_; } hotword_regex_ = nullptr; if (GetArenaNoVirtual() == nullptr && proximity_ != nullptr) { delete proximity_; } proximity_ = nullptr; if (GetArenaNoVirtual() == nullptr && likelihood_adjustment_ != nullptr) { delete likelihood_adjustment_; } likelihood_adjustment_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_DetectionRule_HotwordRule::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_DetectionRule_HotwordRule*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.CustomInfoType.Regex hotword_regex = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_Regex::_InternalParse; object = msg->mutable_hotword_regex(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity proximity = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity::_InternalParse; object = msg->mutable_proximity(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment likelihood_adjustment = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment::_InternalParse; object = msg->mutable_likelihood_adjustment(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_DetectionRule_HotwordRule::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) 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)) { // .google.privacy.dlp.v2.CustomInfoType.Regex hotword_regex = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_hotword_regex())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity proximity = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_proximity())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment likelihood_adjustment = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_likelihood_adjustment())); } 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:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_DetectionRule_HotwordRule::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CustomInfoType.Regex hotword_regex = 1; if (this->has_hotword_regex()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::hotword_regex(this), output); } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity proximity = 2; if (this->has_proximity()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::proximity(this), output); } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment likelihood_adjustment = 3; if (this->has_likelihood_adjustment()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, HasBitSetters::likelihood_adjustment(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) } ::google::protobuf::uint8* CustomInfoType_DetectionRule_HotwordRule::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CustomInfoType.Regex hotword_regex = 1; if (this->has_hotword_regex()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::hotword_regex(this), target); } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity proximity = 2; if (this->has_proximity()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::proximity(this), target); } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment likelihood_adjustment = 3; if (this->has_likelihood_adjustment()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, HasBitSetters::likelihood_adjustment(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) return target; } size_t CustomInfoType_DetectionRule_HotwordRule::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.privacy.dlp.v2.CustomInfoType.Regex hotword_regex = 1; if (this->has_hotword_regex()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *hotword_regex_); } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.Proximity proximity = 2; if (this->has_proximity()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *proximity_); } // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.LikelihoodAdjustment likelihood_adjustment = 3; if (this->has_likelihood_adjustment()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *likelihood_adjustment_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_DetectionRule_HotwordRule::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_DetectionRule_HotwordRule* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_DetectionRule_HotwordRule>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) MergeFrom(*source); } } void CustomInfoType_DetectionRule_HotwordRule::MergeFrom(const CustomInfoType_DetectionRule_HotwordRule& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) 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_hotword_regex()) { mutable_hotword_regex()->::google::privacy::dlp::v2::CustomInfoType_Regex::MergeFrom(from.hotword_regex()); } if (from.has_proximity()) { mutable_proximity()->::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity::MergeFrom(from.proximity()); } if (from.has_likelihood_adjustment()) { mutable_likelihood_adjustment()->::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment::MergeFrom(from.likelihood_adjustment()); } } void CustomInfoType_DetectionRule_HotwordRule::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_DetectionRule_HotwordRule::CopyFrom(const CustomInfoType_DetectionRule_HotwordRule& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_DetectionRule_HotwordRule::IsInitialized() const { return true; } void CustomInfoType_DetectionRule_HotwordRule::Swap(CustomInfoType_DetectionRule_HotwordRule* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_DetectionRule_HotwordRule::InternalSwap(CustomInfoType_DetectionRule_HotwordRule* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(hotword_regex_, other->hotword_regex_); swap(proximity_, other->proximity_); swap(likelihood_adjustment_, other->likelihood_adjustment_); } ::google::protobuf::Metadata CustomInfoType_DetectionRule_HotwordRule::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType_DetectionRule::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_CustomInfoType_DetectionRule_default_instance_.hotword_rule_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule*>( ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule::internal_default_instance()); } class CustomInfoType_DetectionRule::HasBitSetters { public: static const ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule& hotword_rule(const CustomInfoType_DetectionRule* msg); }; const ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule& CustomInfoType_DetectionRule::HasBitSetters::hotword_rule(const CustomInfoType_DetectionRule* msg) { return *msg->type_.hotword_rule_; } void CustomInfoType_DetectionRule::set_allocated_hotword_rule(::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule* hotword_rule) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (hotword_rule) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { hotword_rule = ::google::protobuf::internal::GetOwnedMessage( message_arena, hotword_rule, submessage_arena); } set_has_hotword_rule(); type_.hotword_rule_ = hotword_rule; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.CustomInfoType.DetectionRule.hotword_rule) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType_DetectionRule::kHotwordRuleFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType_DetectionRule::CustomInfoType_DetectionRule() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule) } CustomInfoType_DetectionRule::CustomInfoType_DetectionRule(const CustomInfoType_DetectionRule& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_type(); switch (from.type_case()) { case kHotwordRule: { mutable_hotword_rule()->::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule::MergeFrom(from.hotword_rule()); break; } case TYPE_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule) } void CustomInfoType_DetectionRule::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); clear_has_type(); } CustomInfoType_DetectionRule::~CustomInfoType_DetectionRule() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType.DetectionRule) SharedDtor(); } void CustomInfoType_DetectionRule::SharedDtor() { if (has_type()) { clear_type(); } } void CustomInfoType_DetectionRule::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType_DetectionRule& CustomInfoType_DetectionRule::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_DetectionRule_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType_DetectionRule::clear_type() { // @@protoc_insertion_point(one_of_clear_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) switch (type_case()) { case kHotwordRule: { delete type_.hotword_rule_; break; } case TYPE_NOT_SET: { break; } } _oneof_case_[0] = TYPE_NOT_SET; } void CustomInfoType_DetectionRule::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; clear_type(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType_DetectionRule::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType_DetectionRule*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule hotword_rule = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule::_InternalParse; object = msg->mutable_hotword_rule(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType_DetectionRule::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) 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)) { // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule hotword_rule = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_hotword_rule())); } 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:google.privacy.dlp.v2.CustomInfoType.DetectionRule) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType.DetectionRule) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType_DetectionRule::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule hotword_rule = 1; if (has_hotword_rule()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::hotword_rule(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule) } ::google::protobuf::uint8* CustomInfoType_DetectionRule::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule hotword_rule = 1; if (has_hotword_rule()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::hotword_rule(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType.DetectionRule) return target; } size_t CustomInfoType_DetectionRule::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; switch (type_case()) { // .google.privacy.dlp.v2.CustomInfoType.DetectionRule.HotwordRule hotword_rule = 1; case kHotwordRule: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.hotword_rule_); break; } case TYPE_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType_DetectionRule::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType_DetectionRule* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType_DetectionRule>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType.DetectionRule) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType.DetectionRule) MergeFrom(*source); } } void CustomInfoType_DetectionRule::MergeFrom(const CustomInfoType_DetectionRule& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; switch (from.type_case()) { case kHotwordRule: { mutable_hotword_rule()->::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule::MergeFrom(from.hotword_rule()); break; } case TYPE_NOT_SET: { break; } } } void CustomInfoType_DetectionRule::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType_DetectionRule::CopyFrom(const CustomInfoType_DetectionRule& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType.DetectionRule) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType_DetectionRule::IsInitialized() const { return true; } void CustomInfoType_DetectionRule::Swap(CustomInfoType_DetectionRule* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType_DetectionRule::InternalSwap(CustomInfoType_DetectionRule* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(type_, other->type_); swap(_oneof_case_[0], other->_oneof_case_[0]); } ::google::protobuf::Metadata CustomInfoType_DetectionRule::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CustomInfoType::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_CustomInfoType_default_instance_._instance.get_mutable()->info_type_ = const_cast< ::google::privacy::dlp::v2::InfoType*>( ::google::privacy::dlp::v2::InfoType::internal_default_instance()); ::google::privacy::dlp::v2::_CustomInfoType_default_instance_.dictionary_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_Dictionary*>( ::google::privacy::dlp::v2::CustomInfoType_Dictionary::internal_default_instance()); ::google::privacy::dlp::v2::_CustomInfoType_default_instance_.regex_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_Regex*>( ::google::privacy::dlp::v2::CustomInfoType_Regex::internal_default_instance()); ::google::privacy::dlp::v2::_CustomInfoType_default_instance_.surrogate_type_ = const_cast< ::google::privacy::dlp::v2::CustomInfoType_SurrogateType*>( ::google::privacy::dlp::v2::CustomInfoType_SurrogateType::internal_default_instance()); ::google::privacy::dlp::v2::_CustomInfoType_default_instance_.stored_type_ = const_cast< ::google::privacy::dlp::v2::StoredType*>( ::google::privacy::dlp::v2::StoredType::internal_default_instance()); } class CustomInfoType::HasBitSetters { public: static const ::google::privacy::dlp::v2::InfoType& info_type(const CustomInfoType* msg); static const ::google::privacy::dlp::v2::CustomInfoType_Dictionary& dictionary(const CustomInfoType* msg); static const ::google::privacy::dlp::v2::CustomInfoType_Regex& regex(const CustomInfoType* msg); static const ::google::privacy::dlp::v2::CustomInfoType_SurrogateType& surrogate_type(const CustomInfoType* msg); static const ::google::privacy::dlp::v2::StoredType& stored_type(const CustomInfoType* msg); }; const ::google::privacy::dlp::v2::InfoType& CustomInfoType::HasBitSetters::info_type(const CustomInfoType* msg) { return *msg->info_type_; } const ::google::privacy::dlp::v2::CustomInfoType_Dictionary& CustomInfoType::HasBitSetters::dictionary(const CustomInfoType* msg) { return *msg->type_.dictionary_; } const ::google::privacy::dlp::v2::CustomInfoType_Regex& CustomInfoType::HasBitSetters::regex(const CustomInfoType* msg) { return *msg->type_.regex_; } const ::google::privacy::dlp::v2::CustomInfoType_SurrogateType& CustomInfoType::HasBitSetters::surrogate_type(const CustomInfoType* msg) { return *msg->type_.surrogate_type_; } const ::google::privacy::dlp::v2::StoredType& CustomInfoType::HasBitSetters::stored_type(const CustomInfoType* msg) { return *msg->type_.stored_type_; } void CustomInfoType::set_allocated_dictionary(::google::privacy::dlp::v2::CustomInfoType_Dictionary* dictionary) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (dictionary) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { dictionary = ::google::protobuf::internal::GetOwnedMessage( message_arena, dictionary, submessage_arena); } set_has_dictionary(); type_.dictionary_ = dictionary; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.CustomInfoType.dictionary) } void CustomInfoType::set_allocated_regex(::google::privacy::dlp::v2::CustomInfoType_Regex* regex) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (regex) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { regex = ::google::protobuf::internal::GetOwnedMessage( message_arena, regex, submessage_arena); } set_has_regex(); type_.regex_ = regex; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.CustomInfoType.regex) } void CustomInfoType::set_allocated_surrogate_type(::google::privacy::dlp::v2::CustomInfoType_SurrogateType* surrogate_type) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (surrogate_type) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { surrogate_type = ::google::protobuf::internal::GetOwnedMessage( message_arena, surrogate_type, submessage_arena); } set_has_surrogate_type(); type_.surrogate_type_ = surrogate_type; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.CustomInfoType.surrogate_type) } void CustomInfoType::set_allocated_stored_type(::google::privacy::dlp::v2::StoredType* stored_type) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (stored_type) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { stored_type = ::google::protobuf::internal::GetOwnedMessage( message_arena, stored_type, submessage_arena); } set_has_stored_type(); type_.stored_type_ = stored_type; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.CustomInfoType.stored_type) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CustomInfoType::kInfoTypeFieldNumber; const int CustomInfoType::kLikelihoodFieldNumber; const int CustomInfoType::kDictionaryFieldNumber; const int CustomInfoType::kRegexFieldNumber; const int CustomInfoType::kSurrogateTypeFieldNumber; const int CustomInfoType::kStoredTypeFieldNumber; const int CustomInfoType::kDetectionRulesFieldNumber; const int CustomInfoType::kExclusionTypeFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CustomInfoType::CustomInfoType() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CustomInfoType) } CustomInfoType::CustomInfoType(const CustomInfoType& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), detection_rules_(from.detection_rules_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_info_type()) { info_type_ = new ::google::privacy::dlp::v2::InfoType(*from.info_type_); } else { info_type_ = nullptr; } ::memcpy(&likelihood_, &from.likelihood_, static_cast<size_t>(reinterpret_cast<char*>(&exclusion_type_) - reinterpret_cast<char*>(&likelihood_)) + sizeof(exclusion_type_)); clear_has_type(); switch (from.type_case()) { case kDictionary: { mutable_dictionary()->::google::privacy::dlp::v2::CustomInfoType_Dictionary::MergeFrom(from.dictionary()); break; } case kRegex: { mutable_regex()->::google::privacy::dlp::v2::CustomInfoType_Regex::MergeFrom(from.regex()); break; } case kSurrogateType: { mutable_surrogate_type()->::google::privacy::dlp::v2::CustomInfoType_SurrogateType::MergeFrom(from.surrogate_type()); break; } case kStoredType: { mutable_stored_type()->::google::privacy::dlp::v2::StoredType::MergeFrom(from.stored_type()); break; } case TYPE_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CustomInfoType) } void CustomInfoType::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CustomInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&info_type_, 0, static_cast<size_t>( reinterpret_cast<char*>(&exclusion_type_) - reinterpret_cast<char*>(&info_type_)) + sizeof(exclusion_type_)); clear_has_type(); } CustomInfoType::~CustomInfoType() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CustomInfoType) SharedDtor(); } void CustomInfoType::SharedDtor() { if (this != internal_default_instance()) delete info_type_; if (has_type()) { clear_type(); } } void CustomInfoType::SetCachedSize(int size) const { _cached_size_.Set(size); } const CustomInfoType& CustomInfoType::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CustomInfoType_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CustomInfoType::clear_type() { // @@protoc_insertion_point(one_of_clear_start:google.privacy.dlp.v2.CustomInfoType) switch (type_case()) { case kDictionary: { delete type_.dictionary_; break; } case kRegex: { delete type_.regex_; break; } case kSurrogateType: { delete type_.surrogate_type_; break; } case kStoredType: { delete type_.stored_type_; break; } case TYPE_NOT_SET: { break; } } _oneof_case_[0] = TYPE_NOT_SET; } void CustomInfoType::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CustomInfoType) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; detection_rules_.Clear(); if (GetArenaNoVirtual() == nullptr && info_type_ != nullptr) { delete info_type_; } info_type_ = nullptr; ::memset(&likelihood_, 0, static_cast<size_t>( reinterpret_cast<char*>(&exclusion_type_) - reinterpret_cast<char*>(&likelihood_)) + sizeof(exclusion_type_)); clear_type(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CustomInfoType::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CustomInfoType*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.InfoType info_type = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::InfoType::_InternalParse; object = msg->mutable_info_type(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.CustomInfoType.Dictionary dictionary = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_Dictionary::_InternalParse; object = msg->mutable_dictionary(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.CustomInfoType.Regex regex = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_Regex::_InternalParse; object = msg->mutable_regex(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.CustomInfoType.SurrogateType surrogate_type = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_SurrogateType::_InternalParse; object = msg->mutable_surrogate_type(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.StoredType stored_type = 5; case 5: { if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::StoredType::_InternalParse; object = msg->mutable_stored_type(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.Likelihood likelihood = 6; case 6: { if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual; ::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr); msg->set_likelihood(static_cast<::google::privacy::dlp::v2::Likelihood>(val)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // repeated .google.privacy.dlp.v2.CustomInfoType.DetectionRule detection_rules = 7; case 7: { if (static_cast<::google::protobuf::uint8>(tag) != 58) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CustomInfoType_DetectionRule::_InternalParse; object = msg->add_detection_rules(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 58 && (ptr += 1)); break; } // .google.privacy.dlp.v2.CustomInfoType.ExclusionType exclusion_type = 8; case 8: { if (static_cast<::google::protobuf::uint8>(tag) != 64) goto handle_unusual; ::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr); msg->set_exclusion_type(static_cast<::google::privacy::dlp::v2::CustomInfoType_ExclusionType>(val)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CustomInfoType::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CustomInfoType) 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)) { // .google.privacy.dlp.v2.InfoType info_type = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_info_type())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CustomInfoType.Dictionary dictionary = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_dictionary())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CustomInfoType.Regex regex = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_regex())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CustomInfoType.SurrogateType surrogate_type = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_surrogate_type())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.StoredType stored_type = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_stored_type())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.Likelihood likelihood = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == (48 & 0xFF)) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_likelihood(static_cast< ::google::privacy::dlp::v2::Likelihood >(value)); } else { goto handle_unusual; } break; } // repeated .google.privacy.dlp.v2.CustomInfoType.DetectionRule detection_rules = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == (58 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_detection_rules())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CustomInfoType.ExclusionType exclusion_type = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == (64 & 0xFF)) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_exclusion_type(static_cast< ::google::privacy::dlp::v2::CustomInfoType_ExclusionType >(value)); } 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:google.privacy.dlp.v2.CustomInfoType) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CustomInfoType) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CustomInfoType::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CustomInfoType) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.InfoType info_type = 1; if (this->has_info_type()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::info_type(this), output); } // .google.privacy.dlp.v2.CustomInfoType.Dictionary dictionary = 2; if (has_dictionary()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::dictionary(this), output); } // .google.privacy.dlp.v2.CustomInfoType.Regex regex = 3; if (has_regex()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, HasBitSetters::regex(this), output); } // .google.privacy.dlp.v2.CustomInfoType.SurrogateType surrogate_type = 4; if (has_surrogate_type()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, HasBitSetters::surrogate_type(this), output); } // .google.privacy.dlp.v2.StoredType stored_type = 5; if (has_stored_type()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, HasBitSetters::stored_type(this), output); } // .google.privacy.dlp.v2.Likelihood likelihood = 6; if (this->likelihood() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 6, this->likelihood(), output); } // repeated .google.privacy.dlp.v2.CustomInfoType.DetectionRule detection_rules = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->detection_rules_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 7, this->detection_rules(static_cast<int>(i)), output); } // .google.privacy.dlp.v2.CustomInfoType.ExclusionType exclusion_type = 8; if (this->exclusion_type() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 8, this->exclusion_type(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CustomInfoType) } ::google::protobuf::uint8* CustomInfoType::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CustomInfoType) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.InfoType info_type = 1; if (this->has_info_type()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::info_type(this), target); } // .google.privacy.dlp.v2.CustomInfoType.Dictionary dictionary = 2; if (has_dictionary()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::dictionary(this), target); } // .google.privacy.dlp.v2.CustomInfoType.Regex regex = 3; if (has_regex()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, HasBitSetters::regex(this), target); } // .google.privacy.dlp.v2.CustomInfoType.SurrogateType surrogate_type = 4; if (has_surrogate_type()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, HasBitSetters::surrogate_type(this), target); } // .google.privacy.dlp.v2.StoredType stored_type = 5; if (has_stored_type()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 5, HasBitSetters::stored_type(this), target); } // .google.privacy.dlp.v2.Likelihood likelihood = 6; if (this->likelihood() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 6, this->likelihood(), target); } // repeated .google.privacy.dlp.v2.CustomInfoType.DetectionRule detection_rules = 7; for (unsigned int i = 0, n = static_cast<unsigned int>(this->detection_rules_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 7, this->detection_rules(static_cast<int>(i)), target); } // .google.privacy.dlp.v2.CustomInfoType.ExclusionType exclusion_type = 8; if (this->exclusion_type() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 8, this->exclusion_type(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CustomInfoType) return target; } size_t CustomInfoType::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CustomInfoType) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.privacy.dlp.v2.CustomInfoType.DetectionRule detection_rules = 7; { unsigned int count = static_cast<unsigned int>(this->detection_rules_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->detection_rules(static_cast<int>(i))); } } // .google.privacy.dlp.v2.InfoType info_type = 1; if (this->has_info_type()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *info_type_); } // .google.privacy.dlp.v2.Likelihood likelihood = 6; if (this->likelihood() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->likelihood()); } // .google.privacy.dlp.v2.CustomInfoType.ExclusionType exclusion_type = 8; if (this->exclusion_type() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->exclusion_type()); } switch (type_case()) { // .google.privacy.dlp.v2.CustomInfoType.Dictionary dictionary = 2; case kDictionary: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.dictionary_); break; } // .google.privacy.dlp.v2.CustomInfoType.Regex regex = 3; case kRegex: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.regex_); break; } // .google.privacy.dlp.v2.CustomInfoType.SurrogateType surrogate_type = 4; case kSurrogateType: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.surrogate_type_); break; } // .google.privacy.dlp.v2.StoredType stored_type = 5; case kStoredType: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.stored_type_); break; } case TYPE_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CustomInfoType::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CustomInfoType) GOOGLE_DCHECK_NE(&from, this); const CustomInfoType* source = ::google::protobuf::DynamicCastToGenerated<CustomInfoType>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CustomInfoType) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CustomInfoType) MergeFrom(*source); } } void CustomInfoType::MergeFrom(const CustomInfoType& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CustomInfoType) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; detection_rules_.MergeFrom(from.detection_rules_); if (from.has_info_type()) { mutable_info_type()->::google::privacy::dlp::v2::InfoType::MergeFrom(from.info_type()); } if (from.likelihood() != 0) { set_likelihood(from.likelihood()); } if (from.exclusion_type() != 0) { set_exclusion_type(from.exclusion_type()); } switch (from.type_case()) { case kDictionary: { mutable_dictionary()->::google::privacy::dlp::v2::CustomInfoType_Dictionary::MergeFrom(from.dictionary()); break; } case kRegex: { mutable_regex()->::google::privacy::dlp::v2::CustomInfoType_Regex::MergeFrom(from.regex()); break; } case kSurrogateType: { mutable_surrogate_type()->::google::privacy::dlp::v2::CustomInfoType_SurrogateType::MergeFrom(from.surrogate_type()); break; } case kStoredType: { mutable_stored_type()->::google::privacy::dlp::v2::StoredType::MergeFrom(from.stored_type()); break; } case TYPE_NOT_SET: { break; } } } void CustomInfoType::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CustomInfoType) if (&from == this) return; Clear(); MergeFrom(from); } void CustomInfoType::CopyFrom(const CustomInfoType& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CustomInfoType) if (&from == this) return; Clear(); MergeFrom(from); } bool CustomInfoType::IsInitialized() const { return true; } void CustomInfoType::Swap(CustomInfoType* other) { if (other == this) return; InternalSwap(other); } void CustomInfoType::InternalSwap(CustomInfoType* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&detection_rules_)->InternalSwap(CastToBase(&other->detection_rules_)); swap(info_type_, other->info_type_); swap(likelihood_, other->likelihood_); swap(exclusion_type_, other->exclusion_type_); swap(type_, other->type_); swap(_oneof_case_[0], other->_oneof_case_[0]); } ::google::protobuf::Metadata CustomInfoType::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void FieldId::InitAsDefaultInstance() { } class FieldId::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int FieldId::kNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 FieldId::FieldId() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.FieldId) } FieldId::FieldId(const FieldId& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.FieldId) } void FieldId::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } FieldId::~FieldId() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.FieldId) SharedDtor(); } void FieldId::SharedDtor() { name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void FieldId::SetCachedSize(int size) const { _cached_size_.Set(size); } const FieldId& FieldId::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_FieldId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void FieldId::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.FieldId) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* FieldId::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<FieldId*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.FieldId.name"); object = msg->mutable_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool FieldId::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.FieldId) 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) == (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, "google.privacy.dlp.v2.FieldId.name")); } 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:google.privacy.dlp.v2.FieldId) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.FieldId) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void FieldId::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.FieldId) ::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, "google.privacy.dlp.v2.FieldId.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.FieldId) } ::google::protobuf::uint8* FieldId::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.FieldId) ::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, "google.privacy.dlp.v2.FieldId.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.FieldId) return target; } size_t FieldId::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.FieldId) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // 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 FieldId::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.FieldId) GOOGLE_DCHECK_NE(&from, this); const FieldId* source = ::google::protobuf::DynamicCastToGenerated<FieldId>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.FieldId) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.FieldId) MergeFrom(*source); } } void FieldId::MergeFrom(const FieldId& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.FieldId) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } } void FieldId::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.FieldId) if (&from == this) return; Clear(); MergeFrom(from); } void FieldId::CopyFrom(const FieldId& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.FieldId) if (&from == this) return; Clear(); MergeFrom(from); } bool FieldId::IsInitialized() const { return true; } void FieldId::Swap(FieldId* other) { if (other == this) return; InternalSwap(other); } void FieldId::InternalSwap(FieldId* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata FieldId::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void PartitionId::InitAsDefaultInstance() { } class PartitionId::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int PartitionId::kProjectIdFieldNumber; const int PartitionId::kNamespaceIdFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 PartitionId::PartitionId() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.PartitionId) } PartitionId::PartitionId(const PartitionId& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.project_id().size() > 0) { project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_); } namespace_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.namespace_id().size() > 0) { namespace_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.namespace_id_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.PartitionId) } void PartitionId::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_PartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); namespace_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } PartitionId::~PartitionId() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.PartitionId) SharedDtor(); } void PartitionId::SharedDtor() { project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); namespace_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void PartitionId::SetCachedSize(int size) const { _cached_size_.Set(size); } const PartitionId& PartitionId::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_PartitionId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void PartitionId::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.PartitionId) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); namespace_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* PartitionId::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<PartitionId*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string project_id = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.PartitionId.project_id"); object = msg->mutable_project_id(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string namespace_id = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.PartitionId.namespace_id"); object = msg->mutable_namespace_id(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool PartitionId::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.PartitionId) 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 project_id = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_project_id())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->project_id().data(), static_cast<int>(this->project_id().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.PartitionId.project_id")); } else { goto handle_unusual; } break; } // string namespace_id = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_namespace_id())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->namespace_id().data(), static_cast<int>(this->namespace_id().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.PartitionId.namespace_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:google.privacy.dlp.v2.PartitionId) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.PartitionId) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void PartitionId::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.PartitionId) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string project_id = 2; if (this->project_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->project_id().data(), static_cast<int>(this->project_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.PartitionId.project_id"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->project_id(), output); } // string namespace_id = 4; if (this->namespace_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->namespace_id().data(), static_cast<int>(this->namespace_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.PartitionId.namespace_id"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 4, this->namespace_id(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.PartitionId) } ::google::protobuf::uint8* PartitionId::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.PartitionId) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string project_id = 2; if (this->project_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->project_id().data(), static_cast<int>(this->project_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.PartitionId.project_id"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->project_id(), target); } // string namespace_id = 4; if (this->namespace_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->namespace_id().data(), static_cast<int>(this->namespace_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.PartitionId.namespace_id"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 4, this->namespace_id(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.PartitionId) return target; } size_t PartitionId::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.PartitionId) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string project_id = 2; if (this->project_id().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->project_id()); } // string namespace_id = 4; if (this->namespace_id().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->namespace_id()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void PartitionId::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.PartitionId) GOOGLE_DCHECK_NE(&from, this); const PartitionId* source = ::google::protobuf::DynamicCastToGenerated<PartitionId>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.PartitionId) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.PartitionId) MergeFrom(*source); } } void PartitionId::MergeFrom(const PartitionId& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.PartitionId) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.project_id().size() > 0) { project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_); } if (from.namespace_id().size() > 0) { namespace_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.namespace_id_); } } void PartitionId::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.PartitionId) if (&from == this) return; Clear(); MergeFrom(from); } void PartitionId::CopyFrom(const PartitionId& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.PartitionId) if (&from == this) return; Clear(); MergeFrom(from); } bool PartitionId::IsInitialized() const { return true; } void PartitionId::Swap(PartitionId* other) { if (other == this) return; InternalSwap(other); } void PartitionId::InternalSwap(PartitionId* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); namespace_id_.Swap(&other->namespace_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata PartitionId::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void KindExpression::InitAsDefaultInstance() { } class KindExpression::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int KindExpression::kNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 KindExpression::KindExpression() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.KindExpression) } KindExpression::KindExpression(const KindExpression& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.KindExpression) } void KindExpression::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_KindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } KindExpression::~KindExpression() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.KindExpression) SharedDtor(); } void KindExpression::SharedDtor() { name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void KindExpression::SetCachedSize(int size) const { _cached_size_.Set(size); } const KindExpression& KindExpression::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_KindExpression_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void KindExpression::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.KindExpression) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* KindExpression::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<KindExpression*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.KindExpression.name"); object = msg->mutable_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool KindExpression::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.KindExpression) 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) == (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, "google.privacy.dlp.v2.KindExpression.name")); } 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:google.privacy.dlp.v2.KindExpression) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.KindExpression) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void KindExpression::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.KindExpression) ::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, "google.privacy.dlp.v2.KindExpression.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->name(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.KindExpression) } ::google::protobuf::uint8* KindExpression::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.KindExpression) ::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, "google.privacy.dlp.v2.KindExpression.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->name(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.KindExpression) return target; } size_t KindExpression::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.KindExpression) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // 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 KindExpression::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.KindExpression) GOOGLE_DCHECK_NE(&from, this); const KindExpression* source = ::google::protobuf::DynamicCastToGenerated<KindExpression>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.KindExpression) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.KindExpression) MergeFrom(*source); } } void KindExpression::MergeFrom(const KindExpression& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.KindExpression) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.name().size() > 0) { name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.name_); } } void KindExpression::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.KindExpression) if (&from == this) return; Clear(); MergeFrom(from); } void KindExpression::CopyFrom(const KindExpression& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.KindExpression) if (&from == this) return; Clear(); MergeFrom(from); } bool KindExpression::IsInitialized() const { return true; } void KindExpression::Swap(KindExpression* other) { if (other == this) return; InternalSwap(other); } void KindExpression::InternalSwap(KindExpression* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); name_.Swap(&other->name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata KindExpression::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void DatastoreOptions::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_DatastoreOptions_default_instance_._instance.get_mutable()->partition_id_ = const_cast< ::google::privacy::dlp::v2::PartitionId*>( ::google::privacy::dlp::v2::PartitionId::internal_default_instance()); ::google::privacy::dlp::v2::_DatastoreOptions_default_instance_._instance.get_mutable()->kind_ = const_cast< ::google::privacy::dlp::v2::KindExpression*>( ::google::privacy::dlp::v2::KindExpression::internal_default_instance()); } class DatastoreOptions::HasBitSetters { public: static const ::google::privacy::dlp::v2::PartitionId& partition_id(const DatastoreOptions* msg); static const ::google::privacy::dlp::v2::KindExpression& kind(const DatastoreOptions* msg); }; const ::google::privacy::dlp::v2::PartitionId& DatastoreOptions::HasBitSetters::partition_id(const DatastoreOptions* msg) { return *msg->partition_id_; } const ::google::privacy::dlp::v2::KindExpression& DatastoreOptions::HasBitSetters::kind(const DatastoreOptions* msg) { return *msg->kind_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DatastoreOptions::kPartitionIdFieldNumber; const int DatastoreOptions::kKindFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DatastoreOptions::DatastoreOptions() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.DatastoreOptions) } DatastoreOptions::DatastoreOptions(const DatastoreOptions& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_partition_id()) { partition_id_ = new ::google::privacy::dlp::v2::PartitionId(*from.partition_id_); } else { partition_id_ = nullptr; } if (from.has_kind()) { kind_ = new ::google::privacy::dlp::v2::KindExpression(*from.kind_); } else { kind_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.DatastoreOptions) } void DatastoreOptions::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_DatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&partition_id_, 0, static_cast<size_t>( reinterpret_cast<char*>(&kind_) - reinterpret_cast<char*>(&partition_id_)) + sizeof(kind_)); } DatastoreOptions::~DatastoreOptions() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.DatastoreOptions) SharedDtor(); } void DatastoreOptions::SharedDtor() { if (this != internal_default_instance()) delete partition_id_; if (this != internal_default_instance()) delete kind_; } void DatastoreOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } const DatastoreOptions& DatastoreOptions::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_DatastoreOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void DatastoreOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.DatastoreOptions) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && partition_id_ != nullptr) { delete partition_id_; } partition_id_ = nullptr; if (GetArenaNoVirtual() == nullptr && kind_ != nullptr) { delete kind_; } kind_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* DatastoreOptions::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<DatastoreOptions*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.PartitionId partition_id = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::PartitionId::_InternalParse; object = msg->mutable_partition_id(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.KindExpression kind = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::KindExpression::_InternalParse; object = msg->mutable_kind(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DatastoreOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.DatastoreOptions) 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)) { // .google.privacy.dlp.v2.PartitionId partition_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_partition_id())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.KindExpression kind = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_kind())); } 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:google.privacy.dlp.v2.DatastoreOptions) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.DatastoreOptions) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void DatastoreOptions::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.DatastoreOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.PartitionId partition_id = 1; if (this->has_partition_id()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::partition_id(this), output); } // .google.privacy.dlp.v2.KindExpression kind = 2; if (this->has_kind()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::kind(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.DatastoreOptions) } ::google::protobuf::uint8* DatastoreOptions::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.DatastoreOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.PartitionId partition_id = 1; if (this->has_partition_id()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::partition_id(this), target); } // .google.privacy.dlp.v2.KindExpression kind = 2; if (this->has_kind()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::kind(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.DatastoreOptions) return target; } size_t DatastoreOptions::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.DatastoreOptions) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.privacy.dlp.v2.PartitionId partition_id = 1; if (this->has_partition_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *partition_id_); } // .google.privacy.dlp.v2.KindExpression kind = 2; if (this->has_kind()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *kind_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DatastoreOptions::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.DatastoreOptions) GOOGLE_DCHECK_NE(&from, this); const DatastoreOptions* source = ::google::protobuf::DynamicCastToGenerated<DatastoreOptions>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.DatastoreOptions) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.DatastoreOptions) MergeFrom(*source); } } void DatastoreOptions::MergeFrom(const DatastoreOptions& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.DatastoreOptions) 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_partition_id()) { mutable_partition_id()->::google::privacy::dlp::v2::PartitionId::MergeFrom(from.partition_id()); } if (from.has_kind()) { mutable_kind()->::google::privacy::dlp::v2::KindExpression::MergeFrom(from.kind()); } } void DatastoreOptions::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.DatastoreOptions) if (&from == this) return; Clear(); MergeFrom(from); } void DatastoreOptions::CopyFrom(const DatastoreOptions& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.DatastoreOptions) if (&from == this) return; Clear(); MergeFrom(from); } bool DatastoreOptions::IsInitialized() const { return true; } void DatastoreOptions::Swap(DatastoreOptions* other) { if (other == this) return; InternalSwap(other); } void DatastoreOptions::InternalSwap(DatastoreOptions* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(partition_id_, other->partition_id_); swap(kind_, other->kind_); } ::google::protobuf::Metadata DatastoreOptions::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CloudStorageRegexFileSet::InitAsDefaultInstance() { } class CloudStorageRegexFileSet::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CloudStorageRegexFileSet::kBucketNameFieldNumber; const int CloudStorageRegexFileSet::kIncludeRegexFieldNumber; const int CloudStorageRegexFileSet::kExcludeRegexFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CloudStorageRegexFileSet::CloudStorageRegexFileSet() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CloudStorageRegexFileSet) } CloudStorageRegexFileSet::CloudStorageRegexFileSet(const CloudStorageRegexFileSet& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), include_regex_(from.include_regex_), exclude_regex_(from.exclude_regex_) { _internal_metadata_.MergeFrom(from._internal_metadata_); bucket_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.bucket_name().size() > 0) { bucket_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.bucket_name_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CloudStorageRegexFileSet) } void CloudStorageRegexFileSet::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); bucket_name_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } CloudStorageRegexFileSet::~CloudStorageRegexFileSet() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CloudStorageRegexFileSet) SharedDtor(); } void CloudStorageRegexFileSet::SharedDtor() { bucket_name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void CloudStorageRegexFileSet::SetCachedSize(int size) const { _cached_size_.Set(size); } const CloudStorageRegexFileSet& CloudStorageRegexFileSet::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CloudStorageRegexFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CloudStorageRegexFileSet::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; include_regex_.Clear(); exclude_regex_.Clear(); bucket_name_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CloudStorageRegexFileSet::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CloudStorageRegexFileSet*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string bucket_name = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CloudStorageRegexFileSet.bucket_name"); object = msg->mutable_bucket_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // repeated string include_regex = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CloudStorageRegexFileSet.include_regex"); object = msg->add_include_regex(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // repeated string exclude_regex = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CloudStorageRegexFileSet.exclude_regex"); object = msg->add_exclude_regex(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CloudStorageRegexFileSet::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) 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 bucket_name = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_bucket_name())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->bucket_name().data(), static_cast<int>(this->bucket_name().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.bucket_name")); } else { goto handle_unusual; } break; } // repeated string include_regex = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_include_regex())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->include_regex(this->include_regex_size() - 1).data(), static_cast<int>(this->include_regex(this->include_regex_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.include_regex")); } else { goto handle_unusual; } break; } // repeated string exclude_regex = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_exclude_regex())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->exclude_regex(this->exclude_regex_size() - 1).data(), static_cast<int>(this->exclude_regex(this->exclude_regex_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.exclude_regex")); } 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:google.privacy.dlp.v2.CloudStorageRegexFileSet) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CloudStorageRegexFileSet) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CloudStorageRegexFileSet::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string bucket_name = 1; if (this->bucket_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->bucket_name().data(), static_cast<int>(this->bucket_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.bucket_name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->bucket_name(), output); } // repeated string include_regex = 2; for (int i = 0, n = this->include_regex_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->include_regex(i).data(), static_cast<int>(this->include_regex(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.include_regex"); ::google::protobuf::internal::WireFormatLite::WriteString( 2, this->include_regex(i), output); } // repeated string exclude_regex = 3; for (int i = 0, n = this->exclude_regex_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->exclude_regex(i).data(), static_cast<int>(this->exclude_regex(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.exclude_regex"); ::google::protobuf::internal::WireFormatLite::WriteString( 3, this->exclude_regex(i), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CloudStorageRegexFileSet) } ::google::protobuf::uint8* CloudStorageRegexFileSet::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string bucket_name = 1; if (this->bucket_name().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->bucket_name().data(), static_cast<int>(this->bucket_name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.bucket_name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->bucket_name(), target); } // repeated string include_regex = 2; for (int i = 0, n = this->include_regex_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->include_regex(i).data(), static_cast<int>(this->include_regex(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.include_regex"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(2, this->include_regex(i), target); } // repeated string exclude_regex = 3; for (int i = 0, n = this->exclude_regex_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->exclude_regex(i).data(), static_cast<int>(this->exclude_regex(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageRegexFileSet.exclude_regex"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(3, this->exclude_regex(i), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CloudStorageRegexFileSet) return target; } size_t CloudStorageRegexFileSet::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string include_regex = 2; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->include_regex_size()); for (int i = 0, n = this->include_regex_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->include_regex(i)); } // repeated string exclude_regex = 3; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->exclude_regex_size()); for (int i = 0, n = this->exclude_regex_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->exclude_regex(i)); } // string bucket_name = 1; if (this->bucket_name().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->bucket_name()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CloudStorageRegexFileSet::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) GOOGLE_DCHECK_NE(&from, this); const CloudStorageRegexFileSet* source = ::google::protobuf::DynamicCastToGenerated<CloudStorageRegexFileSet>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CloudStorageRegexFileSet) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CloudStorageRegexFileSet) MergeFrom(*source); } } void CloudStorageRegexFileSet::MergeFrom(const CloudStorageRegexFileSet& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; include_regex_.MergeFrom(from.include_regex_); exclude_regex_.MergeFrom(from.exclude_regex_); if (from.bucket_name().size() > 0) { bucket_name_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.bucket_name_); } } void CloudStorageRegexFileSet::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) if (&from == this) return; Clear(); MergeFrom(from); } void CloudStorageRegexFileSet::CopyFrom(const CloudStorageRegexFileSet& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CloudStorageRegexFileSet) if (&from == this) return; Clear(); MergeFrom(from); } bool CloudStorageRegexFileSet::IsInitialized() const { return true; } void CloudStorageRegexFileSet::Swap(CloudStorageRegexFileSet* other) { if (other == this) return; InternalSwap(other); } void CloudStorageRegexFileSet::InternalSwap(CloudStorageRegexFileSet* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); include_regex_.InternalSwap(CastToBase(&other->include_regex_)); exclude_regex_.InternalSwap(CastToBase(&other->exclude_regex_)); bucket_name_.Swap(&other->bucket_name_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata CloudStorageRegexFileSet::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CloudStorageOptions_FileSet::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_CloudStorageOptions_FileSet_default_instance_._instance.get_mutable()->regex_file_set_ = const_cast< ::google::privacy::dlp::v2::CloudStorageRegexFileSet*>( ::google::privacy::dlp::v2::CloudStorageRegexFileSet::internal_default_instance()); } class CloudStorageOptions_FileSet::HasBitSetters { public: static const ::google::privacy::dlp::v2::CloudStorageRegexFileSet& regex_file_set(const CloudStorageOptions_FileSet* msg); }; const ::google::privacy::dlp::v2::CloudStorageRegexFileSet& CloudStorageOptions_FileSet::HasBitSetters::regex_file_set(const CloudStorageOptions_FileSet* msg) { return *msg->regex_file_set_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CloudStorageOptions_FileSet::kUrlFieldNumber; const int CloudStorageOptions_FileSet::kRegexFileSetFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CloudStorageOptions_FileSet::CloudStorageOptions_FileSet() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CloudStorageOptions.FileSet) } CloudStorageOptions_FileSet::CloudStorageOptions_FileSet(const CloudStorageOptions_FileSet& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.url().size() > 0) { url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.url_); } if (from.has_regex_file_set()) { regex_file_set_ = new ::google::privacy::dlp::v2::CloudStorageRegexFileSet(*from.regex_file_set_); } else { regex_file_set_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CloudStorageOptions.FileSet) } void CloudStorageOptions_FileSet::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); regex_file_set_ = nullptr; } CloudStorageOptions_FileSet::~CloudStorageOptions_FileSet() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CloudStorageOptions.FileSet) SharedDtor(); } void CloudStorageOptions_FileSet::SharedDtor() { url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete regex_file_set_; } void CloudStorageOptions_FileSet::SetCachedSize(int size) const { _cached_size_.Set(size); } const CloudStorageOptions_FileSet& CloudStorageOptions_FileSet::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CloudStorageOptions_FileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CloudStorageOptions_FileSet::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == nullptr && regex_file_set_ != nullptr) { delete regex_file_set_; } regex_file_set_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CloudStorageOptions_FileSet::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CloudStorageOptions_FileSet*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string url = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CloudStorageOptions.FileSet.url"); object = msg->mutable_url(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // .google.privacy.dlp.v2.CloudStorageRegexFileSet regex_file_set = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CloudStorageRegexFileSet::_InternalParse; object = msg->mutable_regex_file_set(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CloudStorageOptions_FileSet::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) 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 url = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_url())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->url().data(), static_cast<int>(this->url().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CloudStorageOptions.FileSet.url")); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CloudStorageRegexFileSet regex_file_set = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_regex_file_set())); } 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:google.privacy.dlp.v2.CloudStorageOptions.FileSet) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CloudStorageOptions.FileSet) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CloudStorageOptions_FileSet::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string url = 1; if (this->url().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->url().data(), static_cast<int>(this->url().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageOptions.FileSet.url"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->url(), output); } // .google.privacy.dlp.v2.CloudStorageRegexFileSet regex_file_set = 2; if (this->has_regex_file_set()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::regex_file_set(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CloudStorageOptions.FileSet) } ::google::protobuf::uint8* CloudStorageOptions_FileSet::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string url = 1; if (this->url().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->url().data(), static_cast<int>(this->url().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageOptions.FileSet.url"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->url(), target); } // .google.privacy.dlp.v2.CloudStorageRegexFileSet regex_file_set = 2; if (this->has_regex_file_set()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::regex_file_set(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CloudStorageOptions.FileSet) return target; } size_t CloudStorageOptions_FileSet::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string url = 1; if (this->url().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->url()); } // .google.privacy.dlp.v2.CloudStorageRegexFileSet regex_file_set = 2; if (this->has_regex_file_set()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *regex_file_set_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CloudStorageOptions_FileSet::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) GOOGLE_DCHECK_NE(&from, this); const CloudStorageOptions_FileSet* source = ::google::protobuf::DynamicCastToGenerated<CloudStorageOptions_FileSet>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CloudStorageOptions.FileSet) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CloudStorageOptions.FileSet) MergeFrom(*source); } } void CloudStorageOptions_FileSet::MergeFrom(const CloudStorageOptions_FileSet& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.url().size() > 0) { url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.url_); } if (from.has_regex_file_set()) { mutable_regex_file_set()->::google::privacy::dlp::v2::CloudStorageRegexFileSet::MergeFrom(from.regex_file_set()); } } void CloudStorageOptions_FileSet::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) if (&from == this) return; Clear(); MergeFrom(from); } void CloudStorageOptions_FileSet::CopyFrom(const CloudStorageOptions_FileSet& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CloudStorageOptions.FileSet) if (&from == this) return; Clear(); MergeFrom(from); } bool CloudStorageOptions_FileSet::IsInitialized() const { return true; } void CloudStorageOptions_FileSet::Swap(CloudStorageOptions_FileSet* other) { if (other == this) return; InternalSwap(other); } void CloudStorageOptions_FileSet::InternalSwap(CloudStorageOptions_FileSet* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); url_.Swap(&other->url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(regex_file_set_, other->regex_file_set_); } ::google::protobuf::Metadata CloudStorageOptions_FileSet::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CloudStorageOptions::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_CloudStorageOptions_default_instance_._instance.get_mutable()->file_set_ = const_cast< ::google::privacy::dlp::v2::CloudStorageOptions_FileSet*>( ::google::privacy::dlp::v2::CloudStorageOptions_FileSet::internal_default_instance()); } class CloudStorageOptions::HasBitSetters { public: static const ::google::privacy::dlp::v2::CloudStorageOptions_FileSet& file_set(const CloudStorageOptions* msg); }; const ::google::privacy::dlp::v2::CloudStorageOptions_FileSet& CloudStorageOptions::HasBitSetters::file_set(const CloudStorageOptions* msg) { return *msg->file_set_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CloudStorageOptions::kFileSetFieldNumber; const int CloudStorageOptions::kBytesLimitPerFileFieldNumber; const int CloudStorageOptions::kBytesLimitPerFilePercentFieldNumber; const int CloudStorageOptions::kFileTypesFieldNumber; const int CloudStorageOptions::kSampleMethodFieldNumber; const int CloudStorageOptions::kFilesLimitPercentFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CloudStorageOptions::CloudStorageOptions() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CloudStorageOptions) } CloudStorageOptions::CloudStorageOptions(const CloudStorageOptions& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), file_types_(from.file_types_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_file_set()) { file_set_ = new ::google::privacy::dlp::v2::CloudStorageOptions_FileSet(*from.file_set_); } else { file_set_ = nullptr; } ::memcpy(&bytes_limit_per_file_, &from.bytes_limit_per_file_, static_cast<size_t>(reinterpret_cast<char*>(&bytes_limit_per_file_percent_) - reinterpret_cast<char*>(&bytes_limit_per_file_)) + sizeof(bytes_limit_per_file_percent_)); // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CloudStorageOptions) } void CloudStorageOptions::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&file_set_, 0, static_cast<size_t>( reinterpret_cast<char*>(&bytes_limit_per_file_percent_) - reinterpret_cast<char*>(&file_set_)) + sizeof(bytes_limit_per_file_percent_)); } CloudStorageOptions::~CloudStorageOptions() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CloudStorageOptions) SharedDtor(); } void CloudStorageOptions::SharedDtor() { if (this != internal_default_instance()) delete file_set_; } void CloudStorageOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } const CloudStorageOptions& CloudStorageOptions::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CloudStorageOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CloudStorageOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CloudStorageOptions) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; file_types_.Clear(); if (GetArenaNoVirtual() == nullptr && file_set_ != nullptr) { delete file_set_; } file_set_ = nullptr; ::memset(&bytes_limit_per_file_, 0, static_cast<size_t>( reinterpret_cast<char*>(&bytes_limit_per_file_percent_) - reinterpret_cast<char*>(&bytes_limit_per_file_)) + sizeof(bytes_limit_per_file_percent_)); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CloudStorageOptions::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CloudStorageOptions*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.CloudStorageOptions.FileSet file_set = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CloudStorageOptions_FileSet::_InternalParse; object = msg->mutable_file_set(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // int64 bytes_limit_per_file = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual; msg->set_bytes_limit_per_file(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // repeated .google.privacy.dlp.v2.FileType file_types = 5; case 5: { if (static_cast<::google::protobuf::uint8>(tag) == 42) { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::PackedEnumParser; object = msg->mutable_file_types(); if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; if (size) ptr = parser_till_end(ptr, newend, object, ctx); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr == newend); break; } else if (static_cast<::google::protobuf::uint8>(tag) != 40) goto handle_unusual; do { ::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr); msg->add_file_types(static_cast<::google::privacy::dlp::v2::FileType>(val)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 40 && (ptr += 1)); break; } // .google.privacy.dlp.v2.CloudStorageOptions.SampleMethod sample_method = 6; case 6: { if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual; ::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr); msg->set_sample_method(static_cast<::google::privacy::dlp::v2::CloudStorageOptions_SampleMethod>(val)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // int32 files_limit_percent = 7; case 7: { if (static_cast<::google::protobuf::uint8>(tag) != 56) goto handle_unusual; msg->set_files_limit_percent(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // int32 bytes_limit_per_file_percent = 8; case 8: { if (static_cast<::google::protobuf::uint8>(tag) != 64) goto handle_unusual; msg->set_bytes_limit_per_file_percent(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CloudStorageOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CloudStorageOptions) 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)) { // .google.privacy.dlp.v2.CloudStorageOptions.FileSet file_set = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_file_set())); } else { goto handle_unusual; } break; } // int64 bytes_limit_per_file = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &bytes_limit_per_file_))); } else { goto handle_unusual; } break; } // repeated .google.privacy.dlp.v2.FileType file_types = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) { ::google::protobuf::uint32 length; DO_(input->ReadVarint32(&length)); ::google::protobuf::io::CodedInputStream::Limit limit = input->PushLimit(static_cast<int>(length)); while (input->BytesUntilLimit() > 0) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_file_types(static_cast< ::google::privacy::dlp::v2::FileType >(value)); } input->PopLimit(limit); } else if (static_cast< ::google::protobuf::uint8>(tag) == (40 & 0xFF)) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); add_file_types(static_cast< ::google::privacy::dlp::v2::FileType >(value)); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CloudStorageOptions.SampleMethod sample_method = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == (48 & 0xFF)) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_sample_method(static_cast< ::google::privacy::dlp::v2::CloudStorageOptions_SampleMethod >(value)); } else { goto handle_unusual; } break; } // int32 files_limit_percent = 7; case 7: { if (static_cast< ::google::protobuf::uint8>(tag) == (56 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &files_limit_percent_))); } else { goto handle_unusual; } break; } // int32 bytes_limit_per_file_percent = 8; case 8: { if (static_cast< ::google::protobuf::uint8>(tag) == (64 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &bytes_limit_per_file_percent_))); } 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:google.privacy.dlp.v2.CloudStorageOptions) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CloudStorageOptions) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CloudStorageOptions::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CloudStorageOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CloudStorageOptions.FileSet file_set = 1; if (this->has_file_set()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::file_set(this), output); } // int64 bytes_limit_per_file = 4; if (this->bytes_limit_per_file() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(4, this->bytes_limit_per_file(), output); } // repeated .google.privacy.dlp.v2.FileType file_types = 5; if (this->file_types_size() > 0) { ::google::protobuf::internal::WireFormatLite::WriteTag( 5, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, output); output->WriteVarint32(_file_types_cached_byte_size_.load( std::memory_order_relaxed)); } for (int i = 0, n = this->file_types_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteEnumNoTag( this->file_types(i), output); } // .google.privacy.dlp.v2.CloudStorageOptions.SampleMethod sample_method = 6; if (this->sample_method() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 6, this->sample_method(), output); } // int32 files_limit_percent = 7; if (this->files_limit_percent() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(7, this->files_limit_percent(), output); } // int32 bytes_limit_per_file_percent = 8; if (this->bytes_limit_per_file_percent() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(8, this->bytes_limit_per_file_percent(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CloudStorageOptions) } ::google::protobuf::uint8* CloudStorageOptions::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CloudStorageOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.CloudStorageOptions.FileSet file_set = 1; if (this->has_file_set()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::file_set(this), target); } // int64 bytes_limit_per_file = 4; if (this->bytes_limit_per_file() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(4, this->bytes_limit_per_file(), target); } // repeated .google.privacy.dlp.v2.FileType file_types = 5; if (this->file_types_size() > 0) { target = ::google::protobuf::internal::WireFormatLite::WriteTagToArray( 5, ::google::protobuf::internal::WireFormatLite::WIRETYPE_LENGTH_DELIMITED, target); target = ::google::protobuf::io::CodedOutputStream::WriteVarint32ToArray( _file_types_cached_byte_size_.load(std::memory_order_relaxed), target); target = ::google::protobuf::internal::WireFormatLite::WriteEnumNoTagToArray( this->file_types_, target); } // .google.privacy.dlp.v2.CloudStorageOptions.SampleMethod sample_method = 6; if (this->sample_method() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 6, this->sample_method(), target); } // int32 files_limit_percent = 7; if (this->files_limit_percent() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(7, this->files_limit_percent(), target); } // int32 bytes_limit_per_file_percent = 8; if (this->bytes_limit_per_file_percent() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(8, this->bytes_limit_per_file_percent(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CloudStorageOptions) return target; } size_t CloudStorageOptions::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CloudStorageOptions) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.privacy.dlp.v2.FileType file_types = 5; { size_t data_size = 0; unsigned int count = static_cast<unsigned int>(this->file_types_size());for (unsigned int i = 0; i < count; i++) { data_size += ::google::protobuf::internal::WireFormatLite::EnumSize( this->file_types(static_cast<int>(i))); } 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); _file_types_cached_byte_size_.store(cached_size, std::memory_order_relaxed); total_size += data_size; } // .google.privacy.dlp.v2.CloudStorageOptions.FileSet file_set = 1; if (this->has_file_set()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *file_set_); } // int64 bytes_limit_per_file = 4; if (this->bytes_limit_per_file() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->bytes_limit_per_file()); } // .google.privacy.dlp.v2.CloudStorageOptions.SampleMethod sample_method = 6; if (this->sample_method() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->sample_method()); } // int32 files_limit_percent = 7; if (this->files_limit_percent() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->files_limit_percent()); } // int32 bytes_limit_per_file_percent = 8; if (this->bytes_limit_per_file_percent() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->bytes_limit_per_file_percent()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CloudStorageOptions::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CloudStorageOptions) GOOGLE_DCHECK_NE(&from, this); const CloudStorageOptions* source = ::google::protobuf::DynamicCastToGenerated<CloudStorageOptions>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CloudStorageOptions) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CloudStorageOptions) MergeFrom(*source); } } void CloudStorageOptions::MergeFrom(const CloudStorageOptions& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CloudStorageOptions) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; file_types_.MergeFrom(from.file_types_); if (from.has_file_set()) { mutable_file_set()->::google::privacy::dlp::v2::CloudStorageOptions_FileSet::MergeFrom(from.file_set()); } if (from.bytes_limit_per_file() != 0) { set_bytes_limit_per_file(from.bytes_limit_per_file()); } if (from.sample_method() != 0) { set_sample_method(from.sample_method()); } if (from.files_limit_percent() != 0) { set_files_limit_percent(from.files_limit_percent()); } if (from.bytes_limit_per_file_percent() != 0) { set_bytes_limit_per_file_percent(from.bytes_limit_per_file_percent()); } } void CloudStorageOptions::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CloudStorageOptions) if (&from == this) return; Clear(); MergeFrom(from); } void CloudStorageOptions::CopyFrom(const CloudStorageOptions& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CloudStorageOptions) if (&from == this) return; Clear(); MergeFrom(from); } bool CloudStorageOptions::IsInitialized() const { return true; } void CloudStorageOptions::Swap(CloudStorageOptions* other) { if (other == this) return; InternalSwap(other); } void CloudStorageOptions::InternalSwap(CloudStorageOptions* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); file_types_.InternalSwap(&other->file_types_); swap(file_set_, other->file_set_); swap(bytes_limit_per_file_, other->bytes_limit_per_file_); swap(sample_method_, other->sample_method_); swap(files_limit_percent_, other->files_limit_percent_); swap(bytes_limit_per_file_percent_, other->bytes_limit_per_file_percent_); } ::google::protobuf::Metadata CloudStorageOptions::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CloudStorageFileSet::InitAsDefaultInstance() { } class CloudStorageFileSet::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CloudStorageFileSet::kUrlFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CloudStorageFileSet::CloudStorageFileSet() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CloudStorageFileSet) } CloudStorageFileSet::CloudStorageFileSet(const CloudStorageFileSet& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.url().size() > 0) { url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.url_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CloudStorageFileSet) } void CloudStorageFileSet::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CloudStorageFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); url_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } CloudStorageFileSet::~CloudStorageFileSet() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CloudStorageFileSet) SharedDtor(); } void CloudStorageFileSet::SharedDtor() { url_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void CloudStorageFileSet::SetCachedSize(int size) const { _cached_size_.Set(size); } const CloudStorageFileSet& CloudStorageFileSet::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CloudStorageFileSet_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CloudStorageFileSet::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CloudStorageFileSet) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; url_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CloudStorageFileSet::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CloudStorageFileSet*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string url = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CloudStorageFileSet.url"); object = msg->mutable_url(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CloudStorageFileSet::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CloudStorageFileSet) 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 url = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_url())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->url().data(), static_cast<int>(this->url().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CloudStorageFileSet.url")); } 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:google.privacy.dlp.v2.CloudStorageFileSet) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CloudStorageFileSet) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CloudStorageFileSet::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CloudStorageFileSet) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string url = 1; if (this->url().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->url().data(), static_cast<int>(this->url().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageFileSet.url"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->url(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CloudStorageFileSet) } ::google::protobuf::uint8* CloudStorageFileSet::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CloudStorageFileSet) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string url = 1; if (this->url().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->url().data(), static_cast<int>(this->url().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStorageFileSet.url"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->url(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CloudStorageFileSet) return target; } size_t CloudStorageFileSet::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CloudStorageFileSet) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string url = 1; if (this->url().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->url()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CloudStorageFileSet::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CloudStorageFileSet) GOOGLE_DCHECK_NE(&from, this); const CloudStorageFileSet* source = ::google::protobuf::DynamicCastToGenerated<CloudStorageFileSet>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CloudStorageFileSet) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CloudStorageFileSet) MergeFrom(*source); } } void CloudStorageFileSet::MergeFrom(const CloudStorageFileSet& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CloudStorageFileSet) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.url().size() > 0) { url_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.url_); } } void CloudStorageFileSet::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CloudStorageFileSet) if (&from == this) return; Clear(); MergeFrom(from); } void CloudStorageFileSet::CopyFrom(const CloudStorageFileSet& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CloudStorageFileSet) if (&from == this) return; Clear(); MergeFrom(from); } bool CloudStorageFileSet::IsInitialized() const { return true; } void CloudStorageFileSet::Swap(CloudStorageFileSet* other) { if (other == this) return; InternalSwap(other); } void CloudStorageFileSet::InternalSwap(CloudStorageFileSet* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); url_.Swap(&other->url_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata CloudStorageFileSet::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void CloudStoragePath::InitAsDefaultInstance() { } class CloudStoragePath::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int CloudStoragePath::kPathFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 CloudStoragePath::CloudStoragePath() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.CloudStoragePath) } CloudStoragePath::CloudStoragePath(const CloudStoragePath& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); path_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.path().size() > 0) { path_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.path_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.CloudStoragePath) } void CloudStoragePath::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_CloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); path_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } CloudStoragePath::~CloudStoragePath() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.CloudStoragePath) SharedDtor(); } void CloudStoragePath::SharedDtor() { path_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void CloudStoragePath::SetCachedSize(int size) const { _cached_size_.Set(size); } const CloudStoragePath& CloudStoragePath::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_CloudStoragePath_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void CloudStoragePath::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.CloudStoragePath) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; path_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* CloudStoragePath::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<CloudStoragePath*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string path = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.CloudStoragePath.path"); object = msg->mutable_path(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool CloudStoragePath::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.CloudStoragePath) 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 path = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_path())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->path().data(), static_cast<int>(this->path().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.CloudStoragePath.path")); } 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:google.privacy.dlp.v2.CloudStoragePath) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.CloudStoragePath) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void CloudStoragePath::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.CloudStoragePath) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string path = 1; if (this->path().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->path().data(), static_cast<int>(this->path().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStoragePath.path"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->path(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.CloudStoragePath) } ::google::protobuf::uint8* CloudStoragePath::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.CloudStoragePath) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string path = 1; if (this->path().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->path().data(), static_cast<int>(this->path().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.CloudStoragePath.path"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->path(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.CloudStoragePath) return target; } size_t CloudStoragePath::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.CloudStoragePath) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string path = 1; if (this->path().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->path()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void CloudStoragePath::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.CloudStoragePath) GOOGLE_DCHECK_NE(&from, this); const CloudStoragePath* source = ::google::protobuf::DynamicCastToGenerated<CloudStoragePath>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.CloudStoragePath) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.CloudStoragePath) MergeFrom(*source); } } void CloudStoragePath::MergeFrom(const CloudStoragePath& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.CloudStoragePath) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.path().size() > 0) { path_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.path_); } } void CloudStoragePath::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.CloudStoragePath) if (&from == this) return; Clear(); MergeFrom(from); } void CloudStoragePath::CopyFrom(const CloudStoragePath& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.CloudStoragePath) if (&from == this) return; Clear(); MergeFrom(from); } bool CloudStoragePath::IsInitialized() const { return true; } void CloudStoragePath::Swap(CloudStoragePath* other) { if (other == this) return; InternalSwap(other); } void CloudStoragePath::InternalSwap(CloudStoragePath* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); path_.Swap(&other->path_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata CloudStoragePath::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void BigQueryOptions::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_BigQueryOptions_default_instance_._instance.get_mutable()->table_reference_ = const_cast< ::google::privacy::dlp::v2::BigQueryTable*>( ::google::privacy::dlp::v2::BigQueryTable::internal_default_instance()); } class BigQueryOptions::HasBitSetters { public: static const ::google::privacy::dlp::v2::BigQueryTable& table_reference(const BigQueryOptions* msg); }; const ::google::privacy::dlp::v2::BigQueryTable& BigQueryOptions::HasBitSetters::table_reference(const BigQueryOptions* msg) { return *msg->table_reference_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BigQueryOptions::kTableReferenceFieldNumber; const int BigQueryOptions::kIdentifyingFieldsFieldNumber; const int BigQueryOptions::kRowsLimitFieldNumber; const int BigQueryOptions::kRowsLimitPercentFieldNumber; const int BigQueryOptions::kSampleMethodFieldNumber; const int BigQueryOptions::kExcludedFieldsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BigQueryOptions::BigQueryOptions() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.BigQueryOptions) } BigQueryOptions::BigQueryOptions(const BigQueryOptions& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), identifying_fields_(from.identifying_fields_), excluded_fields_(from.excluded_fields_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_table_reference()) { table_reference_ = new ::google::privacy::dlp::v2::BigQueryTable(*from.table_reference_); } else { table_reference_ = nullptr; } ::memcpy(&rows_limit_, &from.rows_limit_, static_cast<size_t>(reinterpret_cast<char*>(&rows_limit_percent_) - reinterpret_cast<char*>(&rows_limit_)) + sizeof(rows_limit_percent_)); // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.BigQueryOptions) } void BigQueryOptions::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_BigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&table_reference_, 0, static_cast<size_t>( reinterpret_cast<char*>(&rows_limit_percent_) - reinterpret_cast<char*>(&table_reference_)) + sizeof(rows_limit_percent_)); } BigQueryOptions::~BigQueryOptions() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.BigQueryOptions) SharedDtor(); } void BigQueryOptions::SharedDtor() { if (this != internal_default_instance()) delete table_reference_; } void BigQueryOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } const BigQueryOptions& BigQueryOptions::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_BigQueryOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void BigQueryOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.BigQueryOptions) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; identifying_fields_.Clear(); excluded_fields_.Clear(); if (GetArenaNoVirtual() == nullptr && table_reference_ != nullptr) { delete table_reference_; } table_reference_ = nullptr; ::memset(&rows_limit_, 0, static_cast<size_t>( reinterpret_cast<char*>(&rows_limit_percent_) - reinterpret_cast<char*>(&rows_limit_)) + sizeof(rows_limit_percent_)); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* BigQueryOptions::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<BigQueryOptions*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::BigQueryTable::_InternalParse; object = msg->mutable_table_reference(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::FieldId::_InternalParse; object = msg->add_identifying_fields(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // int64 rows_limit = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 24) goto handle_unusual; msg->set_rows_limit(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // .google.privacy.dlp.v2.BigQueryOptions.SampleMethod sample_method = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual; ::google::protobuf::uint64 val = ::google::protobuf::internal::ReadVarint(&ptr); msg->set_sample_method(static_cast<::google::privacy::dlp::v2::BigQueryOptions_SampleMethod>(val)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // repeated .google.privacy.dlp.v2.FieldId excluded_fields = 5; case 5: { if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::FieldId::_InternalParse; object = msg->add_excluded_fields(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1)); break; } // int32 rows_limit_percent = 6; case 6: { if (static_cast<::google::protobuf::uint8>(tag) != 48) goto handle_unusual; msg->set_rows_limit_percent(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool BigQueryOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.BigQueryOptions) 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)) { // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_table_reference())); } else { goto handle_unusual; } break; } // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_identifying_fields())); } else { goto handle_unusual; } break; } // int64 rows_limit = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (24 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &rows_limit_))); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.BigQueryOptions.SampleMethod sample_method = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) { int value = 0; DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< int, ::google::protobuf::internal::WireFormatLite::TYPE_ENUM>( input, &value))); set_sample_method(static_cast< ::google::privacy::dlp::v2::BigQueryOptions_SampleMethod >(value)); } else { goto handle_unusual; } break; } // repeated .google.privacy.dlp.v2.FieldId excluded_fields = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_excluded_fields())); } else { goto handle_unusual; } break; } // int32 rows_limit_percent = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == (48 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int32, ::google::protobuf::internal::WireFormatLite::TYPE_INT32>( input, &rows_limit_percent_))); } 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:google.privacy.dlp.v2.BigQueryOptions) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.BigQueryOptions) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void BigQueryOptions::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.BigQueryOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; if (this->has_table_reference()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::table_reference(this), output); } // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->identifying_fields_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->identifying_fields(static_cast<int>(i)), output); } // int64 rows_limit = 3; if (this->rows_limit() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(3, this->rows_limit(), output); } // .google.privacy.dlp.v2.BigQueryOptions.SampleMethod sample_method = 4; if (this->sample_method() != 0) { ::google::protobuf::internal::WireFormatLite::WriteEnum( 4, this->sample_method(), output); } // repeated .google.privacy.dlp.v2.FieldId excluded_fields = 5; for (unsigned int i = 0, n = static_cast<unsigned int>(this->excluded_fields_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 5, this->excluded_fields(static_cast<int>(i)), output); } // int32 rows_limit_percent = 6; if (this->rows_limit_percent() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt32(6, this->rows_limit_percent(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.BigQueryOptions) } ::google::protobuf::uint8* BigQueryOptions::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.BigQueryOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; if (this->has_table_reference()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::table_reference(this), target); } // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->identifying_fields_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->identifying_fields(static_cast<int>(i)), target); } // int64 rows_limit = 3; if (this->rows_limit() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(3, this->rows_limit(), target); } // .google.privacy.dlp.v2.BigQueryOptions.SampleMethod sample_method = 4; if (this->sample_method() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteEnumToArray( 4, this->sample_method(), target); } // repeated .google.privacy.dlp.v2.FieldId excluded_fields = 5; for (unsigned int i = 0, n = static_cast<unsigned int>(this->excluded_fields_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 5, this->excluded_fields(static_cast<int>(i)), target); } // int32 rows_limit_percent = 6; if (this->rows_limit_percent() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt32ToArray(6, this->rows_limit_percent(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.BigQueryOptions) return target; } size_t BigQueryOptions::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.BigQueryOptions) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 2; { unsigned int count = static_cast<unsigned int>(this->identifying_fields_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->identifying_fields(static_cast<int>(i))); } } // repeated .google.privacy.dlp.v2.FieldId excluded_fields = 5; { unsigned int count = static_cast<unsigned int>(this->excluded_fields_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->excluded_fields(static_cast<int>(i))); } } // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; if (this->has_table_reference()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *table_reference_); } // int64 rows_limit = 3; if (this->rows_limit() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->rows_limit()); } // .google.privacy.dlp.v2.BigQueryOptions.SampleMethod sample_method = 4; if (this->sample_method() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::EnumSize(this->sample_method()); } // int32 rows_limit_percent = 6; if (this->rows_limit_percent() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int32Size( this->rows_limit_percent()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BigQueryOptions::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.BigQueryOptions) GOOGLE_DCHECK_NE(&from, this); const BigQueryOptions* source = ::google::protobuf::DynamicCastToGenerated<BigQueryOptions>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.BigQueryOptions) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.BigQueryOptions) MergeFrom(*source); } } void BigQueryOptions::MergeFrom(const BigQueryOptions& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.BigQueryOptions) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; identifying_fields_.MergeFrom(from.identifying_fields_); excluded_fields_.MergeFrom(from.excluded_fields_); if (from.has_table_reference()) { mutable_table_reference()->::google::privacy::dlp::v2::BigQueryTable::MergeFrom(from.table_reference()); } if (from.rows_limit() != 0) { set_rows_limit(from.rows_limit()); } if (from.sample_method() != 0) { set_sample_method(from.sample_method()); } if (from.rows_limit_percent() != 0) { set_rows_limit_percent(from.rows_limit_percent()); } } void BigQueryOptions::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.BigQueryOptions) if (&from == this) return; Clear(); MergeFrom(from); } void BigQueryOptions::CopyFrom(const BigQueryOptions& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.BigQueryOptions) if (&from == this) return; Clear(); MergeFrom(from); } bool BigQueryOptions::IsInitialized() const { return true; } void BigQueryOptions::Swap(BigQueryOptions* other) { if (other == this) return; InternalSwap(other); } void BigQueryOptions::InternalSwap(BigQueryOptions* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&identifying_fields_)->InternalSwap(CastToBase(&other->identifying_fields_)); CastToBase(&excluded_fields_)->InternalSwap(CastToBase(&other->excluded_fields_)); swap(table_reference_, other->table_reference_); swap(rows_limit_, other->rows_limit_); swap(sample_method_, other->sample_method_); swap(rows_limit_percent_, other->rows_limit_percent_); } ::google::protobuf::Metadata BigQueryOptions::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void StorageConfig_TimespanConfig::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_StorageConfig_TimespanConfig_default_instance_._instance.get_mutable()->start_time_ = const_cast< ::google::protobuf::Timestamp*>( ::google::protobuf::Timestamp::internal_default_instance()); ::google::privacy::dlp::v2::_StorageConfig_TimespanConfig_default_instance_._instance.get_mutable()->end_time_ = const_cast< ::google::protobuf::Timestamp*>( ::google::protobuf::Timestamp::internal_default_instance()); ::google::privacy::dlp::v2::_StorageConfig_TimespanConfig_default_instance_._instance.get_mutable()->timestamp_field_ = const_cast< ::google::privacy::dlp::v2::FieldId*>( ::google::privacy::dlp::v2::FieldId::internal_default_instance()); } class StorageConfig_TimespanConfig::HasBitSetters { public: static const ::google::protobuf::Timestamp& start_time(const StorageConfig_TimespanConfig* msg); static const ::google::protobuf::Timestamp& end_time(const StorageConfig_TimespanConfig* msg); static const ::google::privacy::dlp::v2::FieldId& timestamp_field(const StorageConfig_TimespanConfig* msg); }; const ::google::protobuf::Timestamp& StorageConfig_TimespanConfig::HasBitSetters::start_time(const StorageConfig_TimespanConfig* msg) { return *msg->start_time_; } const ::google::protobuf::Timestamp& StorageConfig_TimespanConfig::HasBitSetters::end_time(const StorageConfig_TimespanConfig* msg) { return *msg->end_time_; } const ::google::privacy::dlp::v2::FieldId& StorageConfig_TimespanConfig::HasBitSetters::timestamp_field(const StorageConfig_TimespanConfig* msg) { return *msg->timestamp_field_; } void StorageConfig_TimespanConfig::clear_start_time() { if (GetArenaNoVirtual() == nullptr && start_time_ != nullptr) { delete start_time_; } start_time_ = nullptr; } void StorageConfig_TimespanConfig::clear_end_time() { if (GetArenaNoVirtual() == nullptr && end_time_ != nullptr) { delete end_time_; } end_time_ = nullptr; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int StorageConfig_TimespanConfig::kStartTimeFieldNumber; const int StorageConfig_TimespanConfig::kEndTimeFieldNumber; const int StorageConfig_TimespanConfig::kTimestampFieldFieldNumber; const int StorageConfig_TimespanConfig::kEnableAutoPopulationOfTimespanConfigFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 StorageConfig_TimespanConfig::StorageConfig_TimespanConfig() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.StorageConfig.TimespanConfig) } StorageConfig_TimespanConfig::StorageConfig_TimespanConfig(const StorageConfig_TimespanConfig& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_start_time()) { start_time_ = new ::google::protobuf::Timestamp(*from.start_time_); } else { start_time_ = nullptr; } if (from.has_end_time()) { end_time_ = new ::google::protobuf::Timestamp(*from.end_time_); } else { end_time_ = nullptr; } if (from.has_timestamp_field()) { timestamp_field_ = new ::google::privacy::dlp::v2::FieldId(*from.timestamp_field_); } else { timestamp_field_ = nullptr; } enable_auto_population_of_timespan_config_ = from.enable_auto_population_of_timespan_config_; // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.StorageConfig.TimespanConfig) } void StorageConfig_TimespanConfig::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_StorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&start_time_, 0, static_cast<size_t>( reinterpret_cast<char*>(&enable_auto_population_of_timespan_config_) - reinterpret_cast<char*>(&start_time_)) + sizeof(enable_auto_population_of_timespan_config_)); } StorageConfig_TimespanConfig::~StorageConfig_TimespanConfig() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.StorageConfig.TimespanConfig) SharedDtor(); } void StorageConfig_TimespanConfig::SharedDtor() { if (this != internal_default_instance()) delete start_time_; if (this != internal_default_instance()) delete end_time_; if (this != internal_default_instance()) delete timestamp_field_; } void StorageConfig_TimespanConfig::SetCachedSize(int size) const { _cached_size_.Set(size); } const StorageConfig_TimespanConfig& StorageConfig_TimespanConfig::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_StorageConfig_TimespanConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void StorageConfig_TimespanConfig::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && start_time_ != nullptr) { delete start_time_; } start_time_ = nullptr; if (GetArenaNoVirtual() == nullptr && end_time_ != nullptr) { delete end_time_; } end_time_ = nullptr; if (GetArenaNoVirtual() == nullptr && timestamp_field_ != nullptr) { delete timestamp_field_; } timestamp_field_ = nullptr; enable_auto_population_of_timespan_config_ = false; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* StorageConfig_TimespanConfig::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<StorageConfig_TimespanConfig*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.protobuf.Timestamp start_time = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::Timestamp::_InternalParse; object = msg->mutable_start_time(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.protobuf.Timestamp end_time = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::Timestamp::_InternalParse; object = msg->mutable_end_time(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.FieldId timestamp_field = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::FieldId::_InternalParse; object = msg->mutable_timestamp_field(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // bool enable_auto_population_of_timespan_config = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 32) goto handle_unusual; msg->set_enable_auto_population_of_timespan_config(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool StorageConfig_TimespanConfig::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) 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)) { // .google.protobuf.Timestamp start_time = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_start_time())); } else { goto handle_unusual; } break; } // .google.protobuf.Timestamp end_time = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_end_time())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.FieldId timestamp_field = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_timestamp_field())); } else { goto handle_unusual; } break; } // bool enable_auto_population_of_timespan_config = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (32 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< bool, ::google::protobuf::internal::WireFormatLite::TYPE_BOOL>( input, &enable_auto_population_of_timespan_config_))); } 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:google.privacy.dlp.v2.StorageConfig.TimespanConfig) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.StorageConfig.TimespanConfig) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void StorageConfig_TimespanConfig::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.protobuf.Timestamp start_time = 1; if (this->has_start_time()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::start_time(this), output); } // .google.protobuf.Timestamp end_time = 2; if (this->has_end_time()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::end_time(this), output); } // .google.privacy.dlp.v2.FieldId timestamp_field = 3; if (this->has_timestamp_field()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, HasBitSetters::timestamp_field(this), output); } // bool enable_auto_population_of_timespan_config = 4; if (this->enable_auto_population_of_timespan_config() != 0) { ::google::protobuf::internal::WireFormatLite::WriteBool(4, this->enable_auto_population_of_timespan_config(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.StorageConfig.TimespanConfig) } ::google::protobuf::uint8* StorageConfig_TimespanConfig::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.protobuf.Timestamp start_time = 1; if (this->has_start_time()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::start_time(this), target); } // .google.protobuf.Timestamp end_time = 2; if (this->has_end_time()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::end_time(this), target); } // .google.privacy.dlp.v2.FieldId timestamp_field = 3; if (this->has_timestamp_field()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, HasBitSetters::timestamp_field(this), target); } // bool enable_auto_population_of_timespan_config = 4; if (this->enable_auto_population_of_timespan_config() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteBoolToArray(4, this->enable_auto_population_of_timespan_config(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.StorageConfig.TimespanConfig) return target; } size_t StorageConfig_TimespanConfig::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.protobuf.Timestamp start_time = 1; if (this->has_start_time()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *start_time_); } // .google.protobuf.Timestamp end_time = 2; if (this->has_end_time()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *end_time_); } // .google.privacy.dlp.v2.FieldId timestamp_field = 3; if (this->has_timestamp_field()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *timestamp_field_); } // bool enable_auto_population_of_timespan_config = 4; if (this->enable_auto_population_of_timespan_config() != 0) { total_size += 1 + 1; } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void StorageConfig_TimespanConfig::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) GOOGLE_DCHECK_NE(&from, this); const StorageConfig_TimespanConfig* source = ::google::protobuf::DynamicCastToGenerated<StorageConfig_TimespanConfig>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.StorageConfig.TimespanConfig) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.StorageConfig.TimespanConfig) MergeFrom(*source); } } void StorageConfig_TimespanConfig::MergeFrom(const StorageConfig_TimespanConfig& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) 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_start_time()) { mutable_start_time()->::google::protobuf::Timestamp::MergeFrom(from.start_time()); } if (from.has_end_time()) { mutable_end_time()->::google::protobuf::Timestamp::MergeFrom(from.end_time()); } if (from.has_timestamp_field()) { mutable_timestamp_field()->::google::privacy::dlp::v2::FieldId::MergeFrom(from.timestamp_field()); } if (from.enable_auto_population_of_timespan_config() != 0) { set_enable_auto_population_of_timespan_config(from.enable_auto_population_of_timespan_config()); } } void StorageConfig_TimespanConfig::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) if (&from == this) return; Clear(); MergeFrom(from); } void StorageConfig_TimespanConfig::CopyFrom(const StorageConfig_TimespanConfig& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.StorageConfig.TimespanConfig) if (&from == this) return; Clear(); MergeFrom(from); } bool StorageConfig_TimespanConfig::IsInitialized() const { return true; } void StorageConfig_TimespanConfig::Swap(StorageConfig_TimespanConfig* other) { if (other == this) return; InternalSwap(other); } void StorageConfig_TimespanConfig::InternalSwap(StorageConfig_TimespanConfig* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(start_time_, other->start_time_); swap(end_time_, other->end_time_); swap(timestamp_field_, other->timestamp_field_); swap(enable_auto_population_of_timespan_config_, other->enable_auto_population_of_timespan_config_); } ::google::protobuf::Metadata StorageConfig_TimespanConfig::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void StorageConfig::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_StorageConfig_default_instance_.datastore_options_ = const_cast< ::google::privacy::dlp::v2::DatastoreOptions*>( ::google::privacy::dlp::v2::DatastoreOptions::internal_default_instance()); ::google::privacy::dlp::v2::_StorageConfig_default_instance_.cloud_storage_options_ = const_cast< ::google::privacy::dlp::v2::CloudStorageOptions*>( ::google::privacy::dlp::v2::CloudStorageOptions::internal_default_instance()); ::google::privacy::dlp::v2::_StorageConfig_default_instance_.big_query_options_ = const_cast< ::google::privacy::dlp::v2::BigQueryOptions*>( ::google::privacy::dlp::v2::BigQueryOptions::internal_default_instance()); ::google::privacy::dlp::v2::_StorageConfig_default_instance_.hybrid_options_ = const_cast< ::google::privacy::dlp::v2::HybridOptions*>( ::google::privacy::dlp::v2::HybridOptions::internal_default_instance()); ::google::privacy::dlp::v2::_StorageConfig_default_instance_._instance.get_mutable()->timespan_config_ = const_cast< ::google::privacy::dlp::v2::StorageConfig_TimespanConfig*>( ::google::privacy::dlp::v2::StorageConfig_TimespanConfig::internal_default_instance()); } class StorageConfig::HasBitSetters { public: static const ::google::privacy::dlp::v2::DatastoreOptions& datastore_options(const StorageConfig* msg); static const ::google::privacy::dlp::v2::CloudStorageOptions& cloud_storage_options(const StorageConfig* msg); static const ::google::privacy::dlp::v2::BigQueryOptions& big_query_options(const StorageConfig* msg); static const ::google::privacy::dlp::v2::HybridOptions& hybrid_options(const StorageConfig* msg); static const ::google::privacy::dlp::v2::StorageConfig_TimespanConfig& timespan_config(const StorageConfig* msg); }; const ::google::privacy::dlp::v2::DatastoreOptions& StorageConfig::HasBitSetters::datastore_options(const StorageConfig* msg) { return *msg->type_.datastore_options_; } const ::google::privacy::dlp::v2::CloudStorageOptions& StorageConfig::HasBitSetters::cloud_storage_options(const StorageConfig* msg) { return *msg->type_.cloud_storage_options_; } const ::google::privacy::dlp::v2::BigQueryOptions& StorageConfig::HasBitSetters::big_query_options(const StorageConfig* msg) { return *msg->type_.big_query_options_; } const ::google::privacy::dlp::v2::HybridOptions& StorageConfig::HasBitSetters::hybrid_options(const StorageConfig* msg) { return *msg->type_.hybrid_options_; } const ::google::privacy::dlp::v2::StorageConfig_TimespanConfig& StorageConfig::HasBitSetters::timespan_config(const StorageConfig* msg) { return *msg->timespan_config_; } void StorageConfig::set_allocated_datastore_options(::google::privacy::dlp::v2::DatastoreOptions* datastore_options) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (datastore_options) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { datastore_options = ::google::protobuf::internal::GetOwnedMessage( message_arena, datastore_options, submessage_arena); } set_has_datastore_options(); type_.datastore_options_ = datastore_options; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.StorageConfig.datastore_options) } void StorageConfig::set_allocated_cloud_storage_options(::google::privacy::dlp::v2::CloudStorageOptions* cloud_storage_options) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (cloud_storage_options) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { cloud_storage_options = ::google::protobuf::internal::GetOwnedMessage( message_arena, cloud_storage_options, submessage_arena); } set_has_cloud_storage_options(); type_.cloud_storage_options_ = cloud_storage_options; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.StorageConfig.cloud_storage_options) } void StorageConfig::set_allocated_big_query_options(::google::privacy::dlp::v2::BigQueryOptions* big_query_options) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (big_query_options) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { big_query_options = ::google::protobuf::internal::GetOwnedMessage( message_arena, big_query_options, submessage_arena); } set_has_big_query_options(); type_.big_query_options_ = big_query_options; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.StorageConfig.big_query_options) } void StorageConfig::set_allocated_hybrid_options(::google::privacy::dlp::v2::HybridOptions* hybrid_options) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (hybrid_options) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { hybrid_options = ::google::protobuf::internal::GetOwnedMessage( message_arena, hybrid_options, submessage_arena); } set_has_hybrid_options(); type_.hybrid_options_ = hybrid_options; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.StorageConfig.hybrid_options) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int StorageConfig::kDatastoreOptionsFieldNumber; const int StorageConfig::kCloudStorageOptionsFieldNumber; const int StorageConfig::kBigQueryOptionsFieldNumber; const int StorageConfig::kHybridOptionsFieldNumber; const int StorageConfig::kTimespanConfigFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 StorageConfig::StorageConfig() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.StorageConfig) } StorageConfig::StorageConfig(const StorageConfig& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_timespan_config()) { timespan_config_ = new ::google::privacy::dlp::v2::StorageConfig_TimespanConfig(*from.timespan_config_); } else { timespan_config_ = nullptr; } clear_has_type(); switch (from.type_case()) { case kDatastoreOptions: { mutable_datastore_options()->::google::privacy::dlp::v2::DatastoreOptions::MergeFrom(from.datastore_options()); break; } case kCloudStorageOptions: { mutable_cloud_storage_options()->::google::privacy::dlp::v2::CloudStorageOptions::MergeFrom(from.cloud_storage_options()); break; } case kBigQueryOptions: { mutable_big_query_options()->::google::privacy::dlp::v2::BigQueryOptions::MergeFrom(from.big_query_options()); break; } case kHybridOptions: { mutable_hybrid_options()->::google::privacy::dlp::v2::HybridOptions::MergeFrom(from.hybrid_options()); break; } case TYPE_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.StorageConfig) } void StorageConfig::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_StorageConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); timespan_config_ = nullptr; clear_has_type(); } StorageConfig::~StorageConfig() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.StorageConfig) SharedDtor(); } void StorageConfig::SharedDtor() { if (this != internal_default_instance()) delete timespan_config_; if (has_type()) { clear_type(); } } void StorageConfig::SetCachedSize(int size) const { _cached_size_.Set(size); } const StorageConfig& StorageConfig::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_StorageConfig_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void StorageConfig::clear_type() { // @@protoc_insertion_point(one_of_clear_start:google.privacy.dlp.v2.StorageConfig) switch (type_case()) { case kDatastoreOptions: { delete type_.datastore_options_; break; } case kCloudStorageOptions: { delete type_.cloud_storage_options_; break; } case kBigQueryOptions: { delete type_.big_query_options_; break; } case kHybridOptions: { delete type_.hybrid_options_; break; } case TYPE_NOT_SET: { break; } } _oneof_case_[0] = TYPE_NOT_SET; } void StorageConfig::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.StorageConfig) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && timespan_config_ != nullptr) { delete timespan_config_; } timespan_config_ = nullptr; clear_type(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* StorageConfig::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<StorageConfig*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.DatastoreOptions datastore_options = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::DatastoreOptions::_InternalParse; object = msg->mutable_datastore_options(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.CloudStorageOptions cloud_storage_options = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::CloudStorageOptions::_InternalParse; object = msg->mutable_cloud_storage_options(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.BigQueryOptions big_query_options = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::BigQueryOptions::_InternalParse; object = msg->mutable_big_query_options(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.StorageConfig.TimespanConfig timespan_config = 6; case 6: { if (static_cast<::google::protobuf::uint8>(tag) != 50) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::StorageConfig_TimespanConfig::_InternalParse; object = msg->mutable_timespan_config(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.HybridOptions hybrid_options = 9; case 9: { if (static_cast<::google::protobuf::uint8>(tag) != 74) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::HybridOptions::_InternalParse; object = msg->mutable_hybrid_options(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool StorageConfig::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.StorageConfig) 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)) { // .google.privacy.dlp.v2.DatastoreOptions datastore_options = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_datastore_options())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.CloudStorageOptions cloud_storage_options = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_cloud_storage_options())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.BigQueryOptions big_query_options = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_big_query_options())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.StorageConfig.TimespanConfig timespan_config = 6; case 6: { if (static_cast< ::google::protobuf::uint8>(tag) == (50 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_timespan_config())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.HybridOptions hybrid_options = 9; case 9: { if (static_cast< ::google::protobuf::uint8>(tag) == (74 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_hybrid_options())); } 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:google.privacy.dlp.v2.StorageConfig) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.StorageConfig) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void StorageConfig::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.StorageConfig) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.DatastoreOptions datastore_options = 2; if (has_datastore_options()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::datastore_options(this), output); } // .google.privacy.dlp.v2.CloudStorageOptions cloud_storage_options = 3; if (has_cloud_storage_options()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, HasBitSetters::cloud_storage_options(this), output); } // .google.privacy.dlp.v2.BigQueryOptions big_query_options = 4; if (has_big_query_options()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, HasBitSetters::big_query_options(this), output); } // .google.privacy.dlp.v2.StorageConfig.TimespanConfig timespan_config = 6; if (this->has_timespan_config()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 6, HasBitSetters::timespan_config(this), output); } // .google.privacy.dlp.v2.HybridOptions hybrid_options = 9; if (has_hybrid_options()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 9, HasBitSetters::hybrid_options(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.StorageConfig) } ::google::protobuf::uint8* StorageConfig::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.StorageConfig) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.DatastoreOptions datastore_options = 2; if (has_datastore_options()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::datastore_options(this), target); } // .google.privacy.dlp.v2.CloudStorageOptions cloud_storage_options = 3; if (has_cloud_storage_options()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, HasBitSetters::cloud_storage_options(this), target); } // .google.privacy.dlp.v2.BigQueryOptions big_query_options = 4; if (has_big_query_options()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, HasBitSetters::big_query_options(this), target); } // .google.privacy.dlp.v2.StorageConfig.TimespanConfig timespan_config = 6; if (this->has_timespan_config()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 6, HasBitSetters::timespan_config(this), target); } // .google.privacy.dlp.v2.HybridOptions hybrid_options = 9; if (has_hybrid_options()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 9, HasBitSetters::hybrid_options(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.StorageConfig) return target; } size_t StorageConfig::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.StorageConfig) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.privacy.dlp.v2.StorageConfig.TimespanConfig timespan_config = 6; if (this->has_timespan_config()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *timespan_config_); } switch (type_case()) { // .google.privacy.dlp.v2.DatastoreOptions datastore_options = 2; case kDatastoreOptions: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.datastore_options_); break; } // .google.privacy.dlp.v2.CloudStorageOptions cloud_storage_options = 3; case kCloudStorageOptions: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.cloud_storage_options_); break; } // .google.privacy.dlp.v2.BigQueryOptions big_query_options = 4; case kBigQueryOptions: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.big_query_options_); break; } // .google.privacy.dlp.v2.HybridOptions hybrid_options = 9; case kHybridOptions: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.hybrid_options_); break; } case TYPE_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void StorageConfig::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.StorageConfig) GOOGLE_DCHECK_NE(&from, this); const StorageConfig* source = ::google::protobuf::DynamicCastToGenerated<StorageConfig>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.StorageConfig) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.StorageConfig) MergeFrom(*source); } } void StorageConfig::MergeFrom(const StorageConfig& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.StorageConfig) 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_timespan_config()) { mutable_timespan_config()->::google::privacy::dlp::v2::StorageConfig_TimespanConfig::MergeFrom(from.timespan_config()); } switch (from.type_case()) { case kDatastoreOptions: { mutable_datastore_options()->::google::privacy::dlp::v2::DatastoreOptions::MergeFrom(from.datastore_options()); break; } case kCloudStorageOptions: { mutable_cloud_storage_options()->::google::privacy::dlp::v2::CloudStorageOptions::MergeFrom(from.cloud_storage_options()); break; } case kBigQueryOptions: { mutable_big_query_options()->::google::privacy::dlp::v2::BigQueryOptions::MergeFrom(from.big_query_options()); break; } case kHybridOptions: { mutable_hybrid_options()->::google::privacy::dlp::v2::HybridOptions::MergeFrom(from.hybrid_options()); break; } case TYPE_NOT_SET: { break; } } } void StorageConfig::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.StorageConfig) if (&from == this) return; Clear(); MergeFrom(from); } void StorageConfig::CopyFrom(const StorageConfig& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.StorageConfig) if (&from == this) return; Clear(); MergeFrom(from); } bool StorageConfig::IsInitialized() const { return true; } void StorageConfig::Swap(StorageConfig* other) { if (other == this) return; InternalSwap(other); } void StorageConfig::InternalSwap(StorageConfig* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(timespan_config_, other->timespan_config_); swap(type_, other->type_); swap(_oneof_case_[0], other->_oneof_case_[0]); } ::google::protobuf::Metadata StorageConfig::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== HybridOptions_LabelsEntry_DoNotUse::HybridOptions_LabelsEntry_DoNotUse() {} HybridOptions_LabelsEntry_DoNotUse::HybridOptions_LabelsEntry_DoNotUse(::google::protobuf::Arena* arena) : SuperType(arena) {} void HybridOptions_LabelsEntry_DoNotUse::MergeFrom(const HybridOptions_LabelsEntry_DoNotUse& other) { MergeFromInternal(other); } ::google::protobuf::Metadata HybridOptions_LabelsEntry_DoNotUse::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[23]; } void HybridOptions_LabelsEntry_DoNotUse::MergeFrom( const ::google::protobuf::Message& other) { ::google::protobuf::Message::MergeFrom(other); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool HybridOptions_LabelsEntry_DoNotUse::_ParseMap(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { using MF = ::google::protobuf::internal::MapField< HybridOptions_LabelsEntry_DoNotUse, EntryKeyType, EntryValueType, kEntryKeyFieldType, kEntryValueFieldType, kEntryDefaultEnumValue>; auto mf = static_cast<MF*>(object); Parser<MF, ::google::protobuf::Map<EntryKeyType, EntryValueType>> parser(mf); #define DO_(x) if (!(x)) return false DO_(parser.ParseMap(begin, end)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.value")); #undef DO_ return true; } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER // =================================================================== void HybridOptions::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_HybridOptions_default_instance_._instance.get_mutable()->table_options_ = const_cast< ::google::privacy::dlp::v2::TableOptions*>( ::google::privacy::dlp::v2::TableOptions::internal_default_instance()); } class HybridOptions::HasBitSetters { public: static const ::google::privacy::dlp::v2::TableOptions& table_options(const HybridOptions* msg); }; const ::google::privacy::dlp::v2::TableOptions& HybridOptions::HasBitSetters::table_options(const HybridOptions* msg) { return *msg->table_options_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int HybridOptions::kDescriptionFieldNumber; const int HybridOptions::kRequiredFindingLabelKeysFieldNumber; const int HybridOptions::kLabelsFieldNumber; const int HybridOptions::kTableOptionsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 HybridOptions::HybridOptions() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.HybridOptions) } HybridOptions::HybridOptions(const HybridOptions& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), required_finding_label_keys_(from.required_finding_label_keys_) { _internal_metadata_.MergeFrom(from._internal_metadata_); labels_.MergeFrom(from.labels_); description_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.description().size() > 0) { description_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.description_); } if (from.has_table_options()) { table_options_ = new ::google::privacy::dlp::v2::TableOptions(*from.table_options_); } else { table_options_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.HybridOptions) } void HybridOptions::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_HybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); description_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); table_options_ = nullptr; } HybridOptions::~HybridOptions() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.HybridOptions) SharedDtor(); } void HybridOptions::SharedDtor() { description_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (this != internal_default_instance()) delete table_options_; } void HybridOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } const HybridOptions& HybridOptions::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_HybridOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void HybridOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.HybridOptions) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; required_finding_label_keys_.Clear(); labels_.Clear(); description_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (GetArenaNoVirtual() == nullptr && table_options_ != nullptr) { delete table_options_; } table_options_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* HybridOptions::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<HybridOptions*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string description = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.HybridOptions.description"); object = msg->mutable_description(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // repeated string required_finding_label_keys = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.HybridOptions.required_finding_label_keys"); object = msg->add_required_finding_label_keys(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } // map<string, string> labels = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::protobuf::internal::SlowMapEntryParser; auto parse_map = ::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse::_ParseMap; ctx->extra_parse_data().payload.clear(); ctx->extra_parse_data().parse_map = parse_map; object = &msg->labels_; if (size > end - ptr) goto len_delim_till_end; auto newend = ptr + size; GOOGLE_PROTOBUF_PARSER_ASSERT(parse_map(ptr, newend, object, ctx)); ptr = newend; if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 26 && (ptr += 1)); break; } // .google.privacy.dlp.v2.TableOptions table_options = 4; case 4: { if (static_cast<::google::protobuf::uint8>(tag) != 34) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::TableOptions::_InternalParse; object = msg->mutable_table_options(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool HybridOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.HybridOptions) 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 description = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_description())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->description().data(), static_cast<int>(this->description().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.HybridOptions.description")); } else { goto handle_unusual; } break; } // repeated string required_finding_label_keys = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_required_finding_label_keys())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->required_finding_label_keys(this->required_finding_label_keys_size() - 1).data(), static_cast<int>(this->required_finding_label_keys(this->required_finding_label_keys_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.HybridOptions.required_finding_label_keys")); } else { goto handle_unusual; } break; } // map<string, string> labels = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { HybridOptions_LabelsEntry_DoNotUse::Parser< ::google::protobuf::internal::MapField< HybridOptions_LabelsEntry_DoNotUse, ::std::string, ::std::string, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, ::google::protobuf::internal::WireFormatLite::TYPE_STRING, 0 >, ::google::protobuf::Map< ::std::string, ::std::string > > parser(&labels_); DO_(::google::protobuf::internal::WireFormatLite::ReadMessageNoVirtual( input, &parser)); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.key().data(), static_cast<int>(parser.key().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.key")); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( parser.value().data(), static_cast<int>(parser.value().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.value")); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.TableOptions table_options = 4; case 4: { if (static_cast< ::google::protobuf::uint8>(tag) == (34 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_table_options())); } 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:google.privacy.dlp.v2.HybridOptions) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.HybridOptions) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void HybridOptions::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.HybridOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string description = 1; if (this->description().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->description().data(), static_cast<int>(this->description().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.description"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->description(), output); } // repeated string required_finding_label_keys = 2; for (int i = 0, n = this->required_finding_label_keys_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->required_finding_label_keys(i).data(), static_cast<int>(this->required_finding_label_keys(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.required_finding_label_keys"); ::google::protobuf::internal::WireFormatLite::WriteString( 2, this->required_finding_label_keys(i), output); } // map<string, string> labels = 3; if (!this->labels().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.value"); } }; if (output->IsSerializationDeterministic() && this->labels().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->labels().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->labels().begin(); it != this->labels().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<HybridOptions_LabelsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(labels_.NewEntryWrapper(items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(3, *entry, output); Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)])); } } else { ::std::unique_ptr<HybridOptions_LabelsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->labels().begin(); it != this->labels().end(); ++it) { entry.reset(labels_.NewEntryWrapper(it->first, it->second)); ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray(3, *entry, output); Utf8Check::Check(&(*it)); } } } // .google.privacy.dlp.v2.TableOptions table_options = 4; if (this->has_table_options()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 4, HasBitSetters::table_options(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.HybridOptions) } ::google::protobuf::uint8* HybridOptions::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.HybridOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string description = 1; if (this->description().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->description().data(), static_cast<int>(this->description().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.description"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->description(), target); } // repeated string required_finding_label_keys = 2; for (int i = 0, n = this->required_finding_label_keys_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->required_finding_label_keys(i).data(), static_cast<int>(this->required_finding_label_keys(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.required_finding_label_keys"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(2, this->required_finding_label_keys(i), target); } // map<string, string> labels = 3; if (!this->labels().empty()) { typedef ::google::protobuf::Map< ::std::string, ::std::string >::const_pointer ConstPtr; typedef ConstPtr SortItem; typedef ::google::protobuf::internal::CompareByDerefFirst<SortItem> Less; struct Utf8Check { static void Check(ConstPtr p) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->first.data(), static_cast<int>(p->first.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.key"); ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( p->second.data(), static_cast<int>(p->second.length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.HybridOptions.LabelsEntry.value"); } }; if (false && this->labels().size() > 1) { ::std::unique_ptr<SortItem[]> items( new SortItem[this->labels().size()]); typedef ::google::protobuf::Map< ::std::string, ::std::string >::size_type size_type; size_type n = 0; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->labels().begin(); it != this->labels().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<HybridOptions_LabelsEntry_DoNotUse> entry; for (size_type i = 0; i < n; i++) { entry.reset(labels_.NewEntryWrapper(items[static_cast<ptrdiff_t>(i)]->first, items[static_cast<ptrdiff_t>(i)]->second)); target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(3, *entry, target); Utf8Check::Check(&(*items[static_cast<ptrdiff_t>(i)])); } } else { ::std::unique_ptr<HybridOptions_LabelsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->labels().begin(); it != this->labels().end(); ++it) { entry.reset(labels_.NewEntryWrapper(it->first, it->second)); target = ::google::protobuf::internal::WireFormatLite::InternalWriteMessageNoVirtualToArray(3, *entry, target); Utf8Check::Check(&(*it)); } } } // .google.privacy.dlp.v2.TableOptions table_options = 4; if (this->has_table_options()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 4, HasBitSetters::table_options(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.HybridOptions) return target; } size_t HybridOptions::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.HybridOptions) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string required_finding_label_keys = 2; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->required_finding_label_keys_size()); for (int i = 0, n = this->required_finding_label_keys_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->required_finding_label_keys(i)); } // map<string, string> labels = 3; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->labels_size()); { ::std::unique_ptr<HybridOptions_LabelsEntry_DoNotUse> entry; for (::google::protobuf::Map< ::std::string, ::std::string >::const_iterator it = this->labels().begin(); it != this->labels().end(); ++it) { entry.reset(labels_.NewEntryWrapper(it->first, it->second)); total_size += ::google::protobuf::internal::WireFormatLite:: MessageSizeNoVirtual(*entry); } } // string description = 1; if (this->description().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->description()); } // .google.privacy.dlp.v2.TableOptions table_options = 4; if (this->has_table_options()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *table_options_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void HybridOptions::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.HybridOptions) GOOGLE_DCHECK_NE(&from, this); const HybridOptions* source = ::google::protobuf::DynamicCastToGenerated<HybridOptions>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.HybridOptions) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.HybridOptions) MergeFrom(*source); } } void HybridOptions::MergeFrom(const HybridOptions& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.HybridOptions) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; required_finding_label_keys_.MergeFrom(from.required_finding_label_keys_); labels_.MergeFrom(from.labels_); if (from.description().size() > 0) { description_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.description_); } if (from.has_table_options()) { mutable_table_options()->::google::privacy::dlp::v2::TableOptions::MergeFrom(from.table_options()); } } void HybridOptions::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.HybridOptions) if (&from == this) return; Clear(); MergeFrom(from); } void HybridOptions::CopyFrom(const HybridOptions& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.HybridOptions) if (&from == this) return; Clear(); MergeFrom(from); } bool HybridOptions::IsInitialized() const { return true; } void HybridOptions::Swap(HybridOptions* other) { if (other == this) return; InternalSwap(other); } void HybridOptions::InternalSwap(HybridOptions* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); required_finding_label_keys_.InternalSwap(CastToBase(&other->required_finding_label_keys_)); labels_.Swap(&other->labels_); description_.Swap(&other->description_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(table_options_, other->table_options_); } ::google::protobuf::Metadata HybridOptions::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void BigQueryKey::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_BigQueryKey_default_instance_._instance.get_mutable()->table_reference_ = const_cast< ::google::privacy::dlp::v2::BigQueryTable*>( ::google::privacy::dlp::v2::BigQueryTable::internal_default_instance()); } class BigQueryKey::HasBitSetters { public: static const ::google::privacy::dlp::v2::BigQueryTable& table_reference(const BigQueryKey* msg); }; const ::google::privacy::dlp::v2::BigQueryTable& BigQueryKey::HasBitSetters::table_reference(const BigQueryKey* msg) { return *msg->table_reference_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BigQueryKey::kTableReferenceFieldNumber; const int BigQueryKey::kRowNumberFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BigQueryKey::BigQueryKey() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.BigQueryKey) } BigQueryKey::BigQueryKey(const BigQueryKey& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_table_reference()) { table_reference_ = new ::google::privacy::dlp::v2::BigQueryTable(*from.table_reference_); } else { table_reference_ = nullptr; } row_number_ = from.row_number_; // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.BigQueryKey) } void BigQueryKey::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_BigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&table_reference_, 0, static_cast<size_t>( reinterpret_cast<char*>(&row_number_) - reinterpret_cast<char*>(&table_reference_)) + sizeof(row_number_)); } BigQueryKey::~BigQueryKey() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.BigQueryKey) SharedDtor(); } void BigQueryKey::SharedDtor() { if (this != internal_default_instance()) delete table_reference_; } void BigQueryKey::SetCachedSize(int size) const { _cached_size_.Set(size); } const BigQueryKey& BigQueryKey::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_BigQueryKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void BigQueryKey::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.BigQueryKey) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && table_reference_ != nullptr) { delete table_reference_; } table_reference_ = nullptr; row_number_ = PROTOBUF_LONGLONG(0); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* BigQueryKey::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<BigQueryKey*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::BigQueryTable::_InternalParse; object = msg->mutable_table_reference(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // int64 row_number = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; msg->set_row_number(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool BigQueryKey::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.BigQueryKey) 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)) { // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_table_reference())); } else { goto handle_unusual; } break; } // int64 row_number = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) { DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &row_number_))); } 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:google.privacy.dlp.v2.BigQueryKey) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.BigQueryKey) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void BigQueryKey::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.BigQueryKey) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; if (this->has_table_reference()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::table_reference(this), output); } // int64 row_number = 2; if (this->row_number() != 0) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->row_number(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.BigQueryKey) } ::google::protobuf::uint8* BigQueryKey::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.BigQueryKey) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; if (this->has_table_reference()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::table_reference(this), target); } // int64 row_number = 2; if (this->row_number() != 0) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->row_number(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.BigQueryKey) return target; } size_t BigQueryKey::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.BigQueryKey) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table_reference = 1; if (this->has_table_reference()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *table_reference_); } // int64 row_number = 2; if (this->row_number() != 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->row_number()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BigQueryKey::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.BigQueryKey) GOOGLE_DCHECK_NE(&from, this); const BigQueryKey* source = ::google::protobuf::DynamicCastToGenerated<BigQueryKey>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.BigQueryKey) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.BigQueryKey) MergeFrom(*source); } } void BigQueryKey::MergeFrom(const BigQueryKey& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.BigQueryKey) 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_table_reference()) { mutable_table_reference()->::google::privacy::dlp::v2::BigQueryTable::MergeFrom(from.table_reference()); } if (from.row_number() != 0) { set_row_number(from.row_number()); } } void BigQueryKey::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.BigQueryKey) if (&from == this) return; Clear(); MergeFrom(from); } void BigQueryKey::CopyFrom(const BigQueryKey& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.BigQueryKey) if (&from == this) return; Clear(); MergeFrom(from); } bool BigQueryKey::IsInitialized() const { return true; } void BigQueryKey::Swap(BigQueryKey* other) { if (other == this) return; InternalSwap(other); } void BigQueryKey::InternalSwap(BigQueryKey* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(table_reference_, other->table_reference_); swap(row_number_, other->row_number_); } ::google::protobuf::Metadata BigQueryKey::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void DatastoreKey::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_DatastoreKey_default_instance_._instance.get_mutable()->entity_key_ = const_cast< ::google::privacy::dlp::v2::Key*>( ::google::privacy::dlp::v2::Key::internal_default_instance()); } class DatastoreKey::HasBitSetters { public: static const ::google::privacy::dlp::v2::Key& entity_key(const DatastoreKey* msg); }; const ::google::privacy::dlp::v2::Key& DatastoreKey::HasBitSetters::entity_key(const DatastoreKey* msg) { return *msg->entity_key_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int DatastoreKey::kEntityKeyFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 DatastoreKey::DatastoreKey() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.DatastoreKey) } DatastoreKey::DatastoreKey(const DatastoreKey& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_entity_key()) { entity_key_ = new ::google::privacy::dlp::v2::Key(*from.entity_key_); } else { entity_key_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.DatastoreKey) } void DatastoreKey::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_DatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); entity_key_ = nullptr; } DatastoreKey::~DatastoreKey() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.DatastoreKey) SharedDtor(); } void DatastoreKey::SharedDtor() { if (this != internal_default_instance()) delete entity_key_; } void DatastoreKey::SetCachedSize(int size) const { _cached_size_.Set(size); } const DatastoreKey& DatastoreKey::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_DatastoreKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void DatastoreKey::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.DatastoreKey) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && entity_key_ != nullptr) { delete entity_key_; } entity_key_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* DatastoreKey::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<DatastoreKey*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.Key entity_key = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::Key::_InternalParse; object = msg->mutable_entity_key(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool DatastoreKey::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.DatastoreKey) 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)) { // .google.privacy.dlp.v2.Key entity_key = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_entity_key())); } 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:google.privacy.dlp.v2.DatastoreKey) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.DatastoreKey) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void DatastoreKey::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.DatastoreKey) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.Key entity_key = 1; if (this->has_entity_key()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::entity_key(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.DatastoreKey) } ::google::protobuf::uint8* DatastoreKey::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.DatastoreKey) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.Key entity_key = 1; if (this->has_entity_key()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::entity_key(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.DatastoreKey) return target; } size_t DatastoreKey::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.DatastoreKey) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.privacy.dlp.v2.Key entity_key = 1; if (this->has_entity_key()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *entity_key_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void DatastoreKey::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.DatastoreKey) GOOGLE_DCHECK_NE(&from, this); const DatastoreKey* source = ::google::protobuf::DynamicCastToGenerated<DatastoreKey>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.DatastoreKey) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.DatastoreKey) MergeFrom(*source); } } void DatastoreKey::MergeFrom(const DatastoreKey& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.DatastoreKey) 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_entity_key()) { mutable_entity_key()->::google::privacy::dlp::v2::Key::MergeFrom(from.entity_key()); } } void DatastoreKey::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.DatastoreKey) if (&from == this) return; Clear(); MergeFrom(from); } void DatastoreKey::CopyFrom(const DatastoreKey& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.DatastoreKey) if (&from == this) return; Clear(); MergeFrom(from); } bool DatastoreKey::IsInitialized() const { return true; } void DatastoreKey::Swap(DatastoreKey* other) { if (other == this) return; InternalSwap(other); } void DatastoreKey::InternalSwap(DatastoreKey* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(entity_key_, other->entity_key_); } ::google::protobuf::Metadata DatastoreKey::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void Key_PathElement::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_Key_PathElement_default_instance_.id_ = PROTOBUF_LONGLONG(0); ::google::privacy::dlp::v2::_Key_PathElement_default_instance_.name_.UnsafeSetDefault( &::google::protobuf::internal::GetEmptyStringAlreadyInited()); } class Key_PathElement::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Key_PathElement::kKindFieldNumber; const int Key_PathElement::kIdFieldNumber; const int Key_PathElement::kNameFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Key_PathElement::Key_PathElement() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.Key.PathElement) } Key_PathElement::Key_PathElement(const Key_PathElement& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); kind_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.kind().size() > 0) { kind_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.kind_); } clear_has_id_type(); switch (from.id_type_case()) { case kId: { set_id(from.id()); break; } case kName: { set_name(from.name()); break; } case ID_TYPE_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.Key.PathElement) } void Key_PathElement::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_Key_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); kind_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_has_id_type(); } Key_PathElement::~Key_PathElement() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.Key.PathElement) SharedDtor(); } void Key_PathElement::SharedDtor() { kind_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (has_id_type()) { clear_id_type(); } } void Key_PathElement::SetCachedSize(int size) const { _cached_size_.Set(size); } const Key_PathElement& Key_PathElement::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_Key_PathElement_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void Key_PathElement::clear_id_type() { // @@protoc_insertion_point(one_of_clear_start:google.privacy.dlp.v2.Key.PathElement) switch (id_type_case()) { case kId: { // No need to clear break; } case kName: { id_type_.name_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); break; } case ID_TYPE_NOT_SET: { break; } } _oneof_case_[0] = ID_TYPE_NOT_SET; } void Key_PathElement::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.Key.PathElement) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; kind_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); clear_id_type(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* Key_PathElement::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<Key_PathElement*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string kind = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.Key.PathElement.kind"); object = msg->mutable_kind(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // int64 id = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 16) goto handle_unusual; msg->set_id(::google::protobuf::internal::ReadVarint(&ptr)); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); break; } // string name = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.Key.PathElement.name"); object = msg->mutable_name(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Key_PathElement::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.Key.PathElement) 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 kind = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_kind())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->kind().data(), static_cast<int>(this->kind().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.Key.PathElement.kind")); } else { goto handle_unusual; } break; } // int64 id = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (16 & 0xFF)) { clear_id_type(); DO_((::google::protobuf::internal::WireFormatLite::ReadPrimitive< ::google::protobuf::int64, ::google::protobuf::internal::WireFormatLite::TYPE_INT64>( input, &id_type_.id_))); set_has_id(); } else { goto handle_unusual; } break; } // string name = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 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, "google.privacy.dlp.v2.Key.PathElement.name")); } 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:google.privacy.dlp.v2.Key.PathElement) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.Key.PathElement) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Key_PathElement::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.Key.PathElement) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string kind = 1; if (this->kind().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->kind().data(), static_cast<int>(this->kind().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.Key.PathElement.kind"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->kind(), output); } // int64 id = 2; if (has_id()) { ::google::protobuf::internal::WireFormatLite::WriteInt64(2, this->id(), output); } // string name = 3; if (has_name()) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.Key.PathElement.name"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->name(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.Key.PathElement) } ::google::protobuf::uint8* Key_PathElement::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.Key.PathElement) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string kind = 1; if (this->kind().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->kind().data(), static_cast<int>(this->kind().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.Key.PathElement.kind"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->kind(), target); } // int64 id = 2; if (has_id()) { target = ::google::protobuf::internal::WireFormatLite::WriteInt64ToArray(2, this->id(), target); } // string name = 3; if (has_name()) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->name().data(), static_cast<int>(this->name().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.Key.PathElement.name"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->name(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.Key.PathElement) return target; } size_t Key_PathElement::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.Key.PathElement) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string kind = 1; if (this->kind().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->kind()); } switch (id_type_case()) { // int64 id = 2; case kId: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::Int64Size( this->id()); break; } // string name = 3; case kName: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->name()); break; } case ID_TYPE_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void Key_PathElement::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.Key.PathElement) GOOGLE_DCHECK_NE(&from, this); const Key_PathElement* source = ::google::protobuf::DynamicCastToGenerated<Key_PathElement>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.Key.PathElement) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.Key.PathElement) MergeFrom(*source); } } void Key_PathElement::MergeFrom(const Key_PathElement& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.Key.PathElement) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.kind().size() > 0) { kind_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.kind_); } switch (from.id_type_case()) { case kId: { set_id(from.id()); break; } case kName: { set_name(from.name()); break; } case ID_TYPE_NOT_SET: { break; } } } void Key_PathElement::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.Key.PathElement) if (&from == this) return; Clear(); MergeFrom(from); } void Key_PathElement::CopyFrom(const Key_PathElement& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.Key.PathElement) if (&from == this) return; Clear(); MergeFrom(from); } bool Key_PathElement::IsInitialized() const { return true; } void Key_PathElement::Swap(Key_PathElement* other) { if (other == this) return; InternalSwap(other); } void Key_PathElement::InternalSwap(Key_PathElement* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); kind_.Swap(&other->kind_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); swap(id_type_, other->id_type_); swap(_oneof_case_[0], other->_oneof_case_[0]); } ::google::protobuf::Metadata Key_PathElement::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void Key::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_Key_default_instance_._instance.get_mutable()->partition_id_ = const_cast< ::google::privacy::dlp::v2::PartitionId*>( ::google::privacy::dlp::v2::PartitionId::internal_default_instance()); } class Key::HasBitSetters { public: static const ::google::privacy::dlp::v2::PartitionId& partition_id(const Key* msg); }; const ::google::privacy::dlp::v2::PartitionId& Key::HasBitSetters::partition_id(const Key* msg) { return *msg->partition_id_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int Key::kPartitionIdFieldNumber; const int Key::kPathFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 Key::Key() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.Key) } Key::Key(const Key& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), path_(from.path_) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_partition_id()) { partition_id_ = new ::google::privacy::dlp::v2::PartitionId(*from.partition_id_); } else { partition_id_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.Key) } void Key::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_Key_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); partition_id_ = nullptr; } Key::~Key() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.Key) SharedDtor(); } void Key::SharedDtor() { if (this != internal_default_instance()) delete partition_id_; } void Key::SetCachedSize(int size) const { _cached_size_.Set(size); } const Key& Key::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_Key_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void Key::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.Key) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; path_.Clear(); if (GetArenaNoVirtual() == nullptr && partition_id_ != nullptr) { delete partition_id_; } partition_id_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* Key::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<Key*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.PartitionId partition_id = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::PartitionId::_InternalParse; object = msg->mutable_partition_id(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // repeated .google.privacy.dlp.v2.Key.PathElement path = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::Key_PathElement::_InternalParse; object = msg->add_path(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 18 && (ptr += 1)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool Key::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.Key) 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)) { // .google.privacy.dlp.v2.PartitionId partition_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_partition_id())); } else { goto handle_unusual; } break; } // repeated .google.privacy.dlp.v2.Key.PathElement path = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_path())); } 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:google.privacy.dlp.v2.Key) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.Key) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void Key::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.Key) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.PartitionId partition_id = 1; if (this->has_partition_id()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::partition_id(this), output); } // repeated .google.privacy.dlp.v2.Key.PathElement path = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->path_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, this->path(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.Key) } ::google::protobuf::uint8* Key::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.Key) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.PartitionId partition_id = 1; if (this->has_partition_id()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::partition_id(this), target); } // repeated .google.privacy.dlp.v2.Key.PathElement path = 2; for (unsigned int i = 0, n = static_cast<unsigned int>(this->path_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, this->path(static_cast<int>(i)), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.Key) return target; } size_t Key::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.Key) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.privacy.dlp.v2.Key.PathElement path = 2; { unsigned int count = static_cast<unsigned int>(this->path_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->path(static_cast<int>(i))); } } // .google.privacy.dlp.v2.PartitionId partition_id = 1; if (this->has_partition_id()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *partition_id_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void Key::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.Key) GOOGLE_DCHECK_NE(&from, this); const Key* source = ::google::protobuf::DynamicCastToGenerated<Key>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.Key) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.Key) MergeFrom(*source); } } void Key::MergeFrom(const Key& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.Key) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; path_.MergeFrom(from.path_); if (from.has_partition_id()) { mutable_partition_id()->::google::privacy::dlp::v2::PartitionId::MergeFrom(from.partition_id()); } } void Key::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.Key) if (&from == this) return; Clear(); MergeFrom(from); } void Key::CopyFrom(const Key& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.Key) if (&from == this) return; Clear(); MergeFrom(from); } bool Key::IsInitialized() const { return true; } void Key::Swap(Key* other) { if (other == this) return; InternalSwap(other); } void Key::InternalSwap(Key* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&path_)->InternalSwap(CastToBase(&other->path_)); swap(partition_id_, other->partition_id_); } ::google::protobuf::Metadata Key::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void RecordKey::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_RecordKey_default_instance_.datastore_key_ = const_cast< ::google::privacy::dlp::v2::DatastoreKey*>( ::google::privacy::dlp::v2::DatastoreKey::internal_default_instance()); ::google::privacy::dlp::v2::_RecordKey_default_instance_.big_query_key_ = const_cast< ::google::privacy::dlp::v2::BigQueryKey*>( ::google::privacy::dlp::v2::BigQueryKey::internal_default_instance()); } class RecordKey::HasBitSetters { public: static const ::google::privacy::dlp::v2::DatastoreKey& datastore_key(const RecordKey* msg); static const ::google::privacy::dlp::v2::BigQueryKey& big_query_key(const RecordKey* msg); }; const ::google::privacy::dlp::v2::DatastoreKey& RecordKey::HasBitSetters::datastore_key(const RecordKey* msg) { return *msg->type_.datastore_key_; } const ::google::privacy::dlp::v2::BigQueryKey& RecordKey::HasBitSetters::big_query_key(const RecordKey* msg) { return *msg->type_.big_query_key_; } void RecordKey::set_allocated_datastore_key(::google::privacy::dlp::v2::DatastoreKey* datastore_key) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (datastore_key) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { datastore_key = ::google::protobuf::internal::GetOwnedMessage( message_arena, datastore_key, submessage_arena); } set_has_datastore_key(); type_.datastore_key_ = datastore_key; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.RecordKey.datastore_key) } void RecordKey::set_allocated_big_query_key(::google::privacy::dlp::v2::BigQueryKey* big_query_key) { ::google::protobuf::Arena* message_arena = GetArenaNoVirtual(); clear_type(); if (big_query_key) { ::google::protobuf::Arena* submessage_arena = nullptr; if (message_arena != submessage_arena) { big_query_key = ::google::protobuf::internal::GetOwnedMessage( message_arena, big_query_key, submessage_arena); } set_has_big_query_key(); type_.big_query_key_ = big_query_key; } // @@protoc_insertion_point(field_set_allocated:google.privacy.dlp.v2.RecordKey.big_query_key) } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int RecordKey::kDatastoreKeyFieldNumber; const int RecordKey::kBigQueryKeyFieldNumber; const int RecordKey::kIdValuesFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 RecordKey::RecordKey() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.RecordKey) } RecordKey::RecordKey(const RecordKey& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), id_values_(from.id_values_) { _internal_metadata_.MergeFrom(from._internal_metadata_); clear_has_type(); switch (from.type_case()) { case kDatastoreKey: { mutable_datastore_key()->::google::privacy::dlp::v2::DatastoreKey::MergeFrom(from.datastore_key()); break; } case kBigQueryKey: { mutable_big_query_key()->::google::privacy::dlp::v2::BigQueryKey::MergeFrom(from.big_query_key()); break; } case TYPE_NOT_SET: { break; } } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.RecordKey) } void RecordKey::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_RecordKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); clear_has_type(); } RecordKey::~RecordKey() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.RecordKey) SharedDtor(); } void RecordKey::SharedDtor() { if (has_type()) { clear_type(); } } void RecordKey::SetCachedSize(int size) const { _cached_size_.Set(size); } const RecordKey& RecordKey::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_RecordKey_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void RecordKey::clear_type() { // @@protoc_insertion_point(one_of_clear_start:google.privacy.dlp.v2.RecordKey) switch (type_case()) { case kDatastoreKey: { delete type_.datastore_key_; break; } case kBigQueryKey: { delete type_.big_query_key_; break; } case TYPE_NOT_SET: { break; } } _oneof_case_[0] = TYPE_NOT_SET; } void RecordKey::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.RecordKey) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; id_values_.Clear(); clear_type(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* RecordKey::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<RecordKey*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.DatastoreKey datastore_key = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::DatastoreKey::_InternalParse; object = msg->mutable_datastore_key(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.BigQueryKey big_query_key = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::BigQueryKey::_InternalParse; object = msg->mutable_big_query_key(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // repeated string id_values = 5; case 5: { if (static_cast<::google::protobuf::uint8>(tag) != 42) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.RecordKey.id_values"); object = msg->add_id_values(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 42 && (ptr += 1)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool RecordKey::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.RecordKey) 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)) { // .google.privacy.dlp.v2.DatastoreKey datastore_key = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_datastore_key())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.BigQueryKey big_query_key = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_big_query_key())); } else { goto handle_unusual; } break; } // repeated string id_values = 5; case 5: { if (static_cast< ::google::protobuf::uint8>(tag) == (42 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->add_id_values())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->id_values(this->id_values_size() - 1).data(), static_cast<int>(this->id_values(this->id_values_size() - 1).length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.RecordKey.id_values")); } 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:google.privacy.dlp.v2.RecordKey) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.RecordKey) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void RecordKey::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.RecordKey) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.DatastoreKey datastore_key = 2; if (has_datastore_key()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::datastore_key(this), output); } // .google.privacy.dlp.v2.BigQueryKey big_query_key = 3; if (has_big_query_key()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 3, HasBitSetters::big_query_key(this), output); } // repeated string id_values = 5; for (int i = 0, n = this->id_values_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->id_values(i).data(), static_cast<int>(this->id_values(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.RecordKey.id_values"); ::google::protobuf::internal::WireFormatLite::WriteString( 5, this->id_values(i), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.RecordKey) } ::google::protobuf::uint8* RecordKey::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.RecordKey) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.DatastoreKey datastore_key = 2; if (has_datastore_key()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::datastore_key(this), target); } // .google.privacy.dlp.v2.BigQueryKey big_query_key = 3; if (has_big_query_key()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 3, HasBitSetters::big_query_key(this), target); } // repeated string id_values = 5; for (int i = 0, n = this->id_values_size(); i < n; i++) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->id_values(i).data(), static_cast<int>(this->id_values(i).length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.RecordKey.id_values"); target = ::google::protobuf::internal::WireFormatLite:: WriteStringToArray(5, this->id_values(i), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.RecordKey) return target; } size_t RecordKey::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.RecordKey) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated string id_values = 5; total_size += 1 * ::google::protobuf::internal::FromIntSize(this->id_values_size()); for (int i = 0, n = this->id_values_size(); i < n; i++) { total_size += ::google::protobuf::internal::WireFormatLite::StringSize( this->id_values(i)); } switch (type_case()) { // .google.privacy.dlp.v2.DatastoreKey datastore_key = 2; case kDatastoreKey: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.datastore_key_); break; } // .google.privacy.dlp.v2.BigQueryKey big_query_key = 3; case kBigQueryKey: { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *type_.big_query_key_); break; } case TYPE_NOT_SET: { break; } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void RecordKey::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.RecordKey) GOOGLE_DCHECK_NE(&from, this); const RecordKey* source = ::google::protobuf::DynamicCastToGenerated<RecordKey>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.RecordKey) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.RecordKey) MergeFrom(*source); } } void RecordKey::MergeFrom(const RecordKey& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.RecordKey) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; id_values_.MergeFrom(from.id_values_); switch (from.type_case()) { case kDatastoreKey: { mutable_datastore_key()->::google::privacy::dlp::v2::DatastoreKey::MergeFrom(from.datastore_key()); break; } case kBigQueryKey: { mutable_big_query_key()->::google::privacy::dlp::v2::BigQueryKey::MergeFrom(from.big_query_key()); break; } case TYPE_NOT_SET: { break; } } } void RecordKey::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.RecordKey) if (&from == this) return; Clear(); MergeFrom(from); } void RecordKey::CopyFrom(const RecordKey& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.RecordKey) if (&from == this) return; Clear(); MergeFrom(from); } bool RecordKey::IsInitialized() const { return true; } void RecordKey::Swap(RecordKey* other) { if (other == this) return; InternalSwap(other); } void RecordKey::InternalSwap(RecordKey* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); id_values_.InternalSwap(CastToBase(&other->id_values_)); swap(type_, other->type_); swap(_oneof_case_[0], other->_oneof_case_[0]); } ::google::protobuf::Metadata RecordKey::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void BigQueryTable::InitAsDefaultInstance() { } class BigQueryTable::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BigQueryTable::kProjectIdFieldNumber; const int BigQueryTable::kDatasetIdFieldNumber; const int BigQueryTable::kTableIdFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BigQueryTable::BigQueryTable() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.BigQueryTable) } BigQueryTable::BigQueryTable(const BigQueryTable& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.project_id().size() > 0) { project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_); } dataset_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.dataset_id().size() > 0) { dataset_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.dataset_id_); } table_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); if (from.table_id().size() > 0) { table_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.table_id_); } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.BigQueryTable) } void BigQueryTable::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); project_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dataset_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); table_id_.UnsafeSetDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } BigQueryTable::~BigQueryTable() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.BigQueryTable) SharedDtor(); } void BigQueryTable::SharedDtor() { project_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dataset_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); table_id_.DestroyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); } void BigQueryTable::SetCachedSize(int size) const { _cached_size_.Set(size); } const BigQueryTable& BigQueryTable::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_BigQueryTable_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void BigQueryTable::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.BigQueryTable) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; project_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); dataset_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); table_id_.ClearToEmptyNoArena(&::google::protobuf::internal::GetEmptyStringAlreadyInited()); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* BigQueryTable::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<BigQueryTable*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // string project_id = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.BigQueryTable.project_id"); object = msg->mutable_project_id(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string dataset_id = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.BigQueryTable.dataset_id"); object = msg->mutable_dataset_id(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } // string table_id = 3; case 3: { if (static_cast<::google::protobuf::uint8>(tag) != 26) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); ctx->extra_parse_data().SetFieldName("google.privacy.dlp.v2.BigQueryTable.table_id"); object = msg->mutable_table_id(); if (size > end - ptr + ::google::protobuf::internal::ParseContext::kSlopBytes) { parser_till_end = ::google::protobuf::internal::GreedyStringParserUTF8; goto string_till_end; } GOOGLE_PROTOBUF_PARSER_ASSERT(::google::protobuf::internal::StringCheckUTF8(ptr, size, ctx)); ::google::protobuf::internal::InlineGreedyStringParser(object, ptr, size, ctx); ptr += size; break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; string_till_end: static_cast<::std::string*>(object)->clear(); static_cast<::std::string*>(object)->reserve(size); goto len_delim_till_end; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool BigQueryTable::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.BigQueryTable) 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 project_id = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_project_id())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->project_id().data(), static_cast<int>(this->project_id().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.BigQueryTable.project_id")); } else { goto handle_unusual; } break; } // string dataset_id = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_dataset_id())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dataset_id().data(), static_cast<int>(this->dataset_id().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.BigQueryTable.dataset_id")); } else { goto handle_unusual; } break; } // string table_id = 3; case 3: { if (static_cast< ::google::protobuf::uint8>(tag) == (26 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadString( input, this->mutable_table_id())); DO_(::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->table_id().data(), static_cast<int>(this->table_id().length()), ::google::protobuf::internal::WireFormatLite::PARSE, "google.privacy.dlp.v2.BigQueryTable.table_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:google.privacy.dlp.v2.BigQueryTable) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.BigQueryTable) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void BigQueryTable::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.BigQueryTable) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string project_id = 1; if (this->project_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->project_id().data(), static_cast<int>(this->project_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.BigQueryTable.project_id"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 1, this->project_id(), output); } // string dataset_id = 2; if (this->dataset_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dataset_id().data(), static_cast<int>(this->dataset_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.BigQueryTable.dataset_id"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 2, this->dataset_id(), output); } // string table_id = 3; if (this->table_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->table_id().data(), static_cast<int>(this->table_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.BigQueryTable.table_id"); ::google::protobuf::internal::WireFormatLite::WriteStringMaybeAliased( 3, this->table_id(), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.BigQueryTable) } ::google::protobuf::uint8* BigQueryTable::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.BigQueryTable) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // string project_id = 1; if (this->project_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->project_id().data(), static_cast<int>(this->project_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.BigQueryTable.project_id"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 1, this->project_id(), target); } // string dataset_id = 2; if (this->dataset_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->dataset_id().data(), static_cast<int>(this->dataset_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.BigQueryTable.dataset_id"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 2, this->dataset_id(), target); } // string table_id = 3; if (this->table_id().size() > 0) { ::google::protobuf::internal::WireFormatLite::VerifyUtf8String( this->table_id().data(), static_cast<int>(this->table_id().length()), ::google::protobuf::internal::WireFormatLite::SERIALIZE, "google.privacy.dlp.v2.BigQueryTable.table_id"); target = ::google::protobuf::internal::WireFormatLite::WriteStringToArray( 3, this->table_id(), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.BigQueryTable) return target; } size_t BigQueryTable::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.BigQueryTable) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // string project_id = 1; if (this->project_id().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->project_id()); } // string dataset_id = 2; if (this->dataset_id().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->dataset_id()); } // string table_id = 3; if (this->table_id().size() > 0) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::StringSize( this->table_id()); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BigQueryTable::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.BigQueryTable) GOOGLE_DCHECK_NE(&from, this); const BigQueryTable* source = ::google::protobuf::DynamicCastToGenerated<BigQueryTable>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.BigQueryTable) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.BigQueryTable) MergeFrom(*source); } } void BigQueryTable::MergeFrom(const BigQueryTable& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.BigQueryTable) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; if (from.project_id().size() > 0) { project_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.project_id_); } if (from.dataset_id().size() > 0) { dataset_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.dataset_id_); } if (from.table_id().size() > 0) { table_id_.AssignWithDefault(&::google::protobuf::internal::GetEmptyStringAlreadyInited(), from.table_id_); } } void BigQueryTable::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.BigQueryTable) if (&from == this) return; Clear(); MergeFrom(from); } void BigQueryTable::CopyFrom(const BigQueryTable& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.BigQueryTable) if (&from == this) return; Clear(); MergeFrom(from); } bool BigQueryTable::IsInitialized() const { return true; } void BigQueryTable::Swap(BigQueryTable* other) { if (other == this) return; InternalSwap(other); } void BigQueryTable::InternalSwap(BigQueryTable* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); project_id_.Swap(&other->project_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); dataset_id_.Swap(&other->dataset_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); table_id_.Swap(&other->table_id_, &::google::protobuf::internal::GetEmptyStringAlreadyInited(), GetArenaNoVirtual()); } ::google::protobuf::Metadata BigQueryTable::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void BigQueryField::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_BigQueryField_default_instance_._instance.get_mutable()->table_ = const_cast< ::google::privacy::dlp::v2::BigQueryTable*>( ::google::privacy::dlp::v2::BigQueryTable::internal_default_instance()); ::google::privacy::dlp::v2::_BigQueryField_default_instance_._instance.get_mutable()->field_ = const_cast< ::google::privacy::dlp::v2::FieldId*>( ::google::privacy::dlp::v2::FieldId::internal_default_instance()); } class BigQueryField::HasBitSetters { public: static const ::google::privacy::dlp::v2::BigQueryTable& table(const BigQueryField* msg); static const ::google::privacy::dlp::v2::FieldId& field(const BigQueryField* msg); }; const ::google::privacy::dlp::v2::BigQueryTable& BigQueryField::HasBitSetters::table(const BigQueryField* msg) { return *msg->table_; } const ::google::privacy::dlp::v2::FieldId& BigQueryField::HasBitSetters::field(const BigQueryField* msg) { return *msg->field_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int BigQueryField::kTableFieldNumber; const int BigQueryField::kFieldFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 BigQueryField::BigQueryField() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.BigQueryField) } BigQueryField::BigQueryField(const BigQueryField& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_table()) { table_ = new ::google::privacy::dlp::v2::BigQueryTable(*from.table_); } else { table_ = nullptr; } if (from.has_field()) { field_ = new ::google::privacy::dlp::v2::FieldId(*from.field_); } else { field_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.BigQueryField) } void BigQueryField::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_BigQueryField_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); ::memset(&table_, 0, static_cast<size_t>( reinterpret_cast<char*>(&field_) - reinterpret_cast<char*>(&table_)) + sizeof(field_)); } BigQueryField::~BigQueryField() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.BigQueryField) SharedDtor(); } void BigQueryField::SharedDtor() { if (this != internal_default_instance()) delete table_; if (this != internal_default_instance()) delete field_; } void BigQueryField::SetCachedSize(int size) const { _cached_size_.Set(size); } const BigQueryField& BigQueryField::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_BigQueryField_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void BigQueryField::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.BigQueryField) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && table_ != nullptr) { delete table_; } table_ = nullptr; if (GetArenaNoVirtual() == nullptr && field_ != nullptr) { delete field_; } field_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* BigQueryField::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<BigQueryField*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.BigQueryTable table = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::BigQueryTable::_InternalParse; object = msg->mutable_table(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } // .google.privacy.dlp.v2.FieldId field = 2; case 2: { if (static_cast<::google::protobuf::uint8>(tag) != 18) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::FieldId::_InternalParse; object = msg->mutable_field(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool BigQueryField::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.BigQueryField) 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)) { // .google.privacy.dlp.v2.BigQueryTable table = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_table())); } else { goto handle_unusual; } break; } // .google.privacy.dlp.v2.FieldId field = 2; case 2: { if (static_cast< ::google::protobuf::uint8>(tag) == (18 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_field())); } 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:google.privacy.dlp.v2.BigQueryField) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.BigQueryField) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void BigQueryField::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.BigQueryField) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table = 1; if (this->has_table()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::table(this), output); } // .google.privacy.dlp.v2.FieldId field = 2; if (this->has_field()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 2, HasBitSetters::field(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.BigQueryField) } ::google::protobuf::uint8* BigQueryField::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.BigQueryField) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table = 1; if (this->has_table()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::table(this), target); } // .google.privacy.dlp.v2.FieldId field = 2; if (this->has_field()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 2, HasBitSetters::field(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.BigQueryField) return target; } size_t BigQueryField::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.BigQueryField) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.privacy.dlp.v2.BigQueryTable table = 1; if (this->has_table()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *table_); } // .google.privacy.dlp.v2.FieldId field = 2; if (this->has_field()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *field_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void BigQueryField::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.BigQueryField) GOOGLE_DCHECK_NE(&from, this); const BigQueryField* source = ::google::protobuf::DynamicCastToGenerated<BigQueryField>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.BigQueryField) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.BigQueryField) MergeFrom(*source); } } void BigQueryField::MergeFrom(const BigQueryField& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.BigQueryField) 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_table()) { mutable_table()->::google::privacy::dlp::v2::BigQueryTable::MergeFrom(from.table()); } if (from.has_field()) { mutable_field()->::google::privacy::dlp::v2::FieldId::MergeFrom(from.field()); } } void BigQueryField::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.BigQueryField) if (&from == this) return; Clear(); MergeFrom(from); } void BigQueryField::CopyFrom(const BigQueryField& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.BigQueryField) if (&from == this) return; Clear(); MergeFrom(from); } bool BigQueryField::IsInitialized() const { return true; } void BigQueryField::Swap(BigQueryField* other) { if (other == this) return; InternalSwap(other); } void BigQueryField::InternalSwap(BigQueryField* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(table_, other->table_); swap(field_, other->field_); } ::google::protobuf::Metadata BigQueryField::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void EntityId::InitAsDefaultInstance() { ::google::privacy::dlp::v2::_EntityId_default_instance_._instance.get_mutable()->field_ = const_cast< ::google::privacy::dlp::v2::FieldId*>( ::google::privacy::dlp::v2::FieldId::internal_default_instance()); } class EntityId::HasBitSetters { public: static const ::google::privacy::dlp::v2::FieldId& field(const EntityId* msg); }; const ::google::privacy::dlp::v2::FieldId& EntityId::HasBitSetters::field(const EntityId* msg) { return *msg->field_; } #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int EntityId::kFieldFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 EntityId::EntityId() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.EntityId) } EntityId::EntityId(const EntityId& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr) { _internal_metadata_.MergeFrom(from._internal_metadata_); if (from.has_field()) { field_ = new ::google::privacy::dlp::v2::FieldId(*from.field_); } else { field_ = nullptr; } // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.EntityId) } void EntityId::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_EntityId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); field_ = nullptr; } EntityId::~EntityId() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.EntityId) SharedDtor(); } void EntityId::SharedDtor() { if (this != internal_default_instance()) delete field_; } void EntityId::SetCachedSize(int size) const { _cached_size_.Set(size); } const EntityId& EntityId::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_EntityId_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void EntityId::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.EntityId) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; if (GetArenaNoVirtual() == nullptr && field_ != nullptr) { delete field_; } field_ = nullptr; _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* EntityId::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<EntityId*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // .google.privacy.dlp.v2.FieldId field = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::FieldId::_InternalParse; object = msg->mutable_field(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool EntityId::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.EntityId) 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)) { // .google.privacy.dlp.v2.FieldId field = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, mutable_field())); } 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:google.privacy.dlp.v2.EntityId) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.EntityId) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void EntityId::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.EntityId) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.FieldId field = 1; if (this->has_field()) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, HasBitSetters::field(this), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.EntityId) } ::google::protobuf::uint8* EntityId::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.EntityId) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // .google.privacy.dlp.v2.FieldId field = 1; if (this->has_field()) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, HasBitSetters::field(this), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.EntityId) return target; } size_t EntityId::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.EntityId) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // .google.privacy.dlp.v2.FieldId field = 1; if (this->has_field()) { total_size += 1 + ::google::protobuf::internal::WireFormatLite::MessageSize( *field_); } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void EntityId::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.EntityId) GOOGLE_DCHECK_NE(&from, this); const EntityId* source = ::google::protobuf::DynamicCastToGenerated<EntityId>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.EntityId) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.EntityId) MergeFrom(*source); } } void EntityId::MergeFrom(const EntityId& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.EntityId) 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_field()) { mutable_field()->::google::privacy::dlp::v2::FieldId::MergeFrom(from.field()); } } void EntityId::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.EntityId) if (&from == this) return; Clear(); MergeFrom(from); } void EntityId::CopyFrom(const EntityId& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.EntityId) if (&from == this) return; Clear(); MergeFrom(from); } bool EntityId::IsInitialized() const { return true; } void EntityId::Swap(EntityId* other) { if (other == this) return; InternalSwap(other); } void EntityId::InternalSwap(EntityId* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); swap(field_, other->field_); } ::google::protobuf::Metadata EntityId::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // =================================================================== void TableOptions::InitAsDefaultInstance() { } class TableOptions::HasBitSetters { public: }; #if !defined(_MSC_VER) || _MSC_VER >= 1900 const int TableOptions::kIdentifyingFieldsFieldNumber; #endif // !defined(_MSC_VER) || _MSC_VER >= 1900 TableOptions::TableOptions() : ::google::protobuf::Message(), _internal_metadata_(nullptr) { SharedCtor(); // @@protoc_insertion_point(constructor:google.privacy.dlp.v2.TableOptions) } TableOptions::TableOptions(const TableOptions& from) : ::google::protobuf::Message(), _internal_metadata_(nullptr), identifying_fields_(from.identifying_fields_) { _internal_metadata_.MergeFrom(from._internal_metadata_); // @@protoc_insertion_point(copy_constructor:google.privacy.dlp.v2.TableOptions) } void TableOptions::SharedCtor() { ::google::protobuf::internal::InitSCC( &scc_info_TableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); } TableOptions::~TableOptions() { // @@protoc_insertion_point(destructor:google.privacy.dlp.v2.TableOptions) SharedDtor(); } void TableOptions::SharedDtor() { } void TableOptions::SetCachedSize(int size) const { _cached_size_.Set(size); } const TableOptions& TableOptions::default_instance() { ::google::protobuf::internal::InitSCC(&::scc_info_TableOptions_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto.base); return *internal_default_instance(); } void TableOptions::Clear() { // @@protoc_insertion_point(message_clear_start:google.privacy.dlp.v2.TableOptions) ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; identifying_fields_.Clear(); _internal_metadata_.Clear(); } #if GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER const char* TableOptions::_InternalParse(const char* begin, const char* end, void* object, ::google::protobuf::internal::ParseContext* ctx) { auto msg = static_cast<TableOptions*>(object); ::google::protobuf::int32 size; (void)size; int depth; (void)depth; ::google::protobuf::uint32 tag; ::google::protobuf::internal::ParseFunc parser_till_end; (void)parser_till_end; auto ptr = begin; while (ptr < end) { ptr = ::google::protobuf::io::Parse32(ptr, &tag); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); switch (tag >> 3) { // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 1; case 1: { if (static_cast<::google::protobuf::uint8>(tag) != 10) goto handle_unusual; do { ptr = ::google::protobuf::io::ReadSize(ptr, &size); GOOGLE_PROTOBUF_PARSER_ASSERT(ptr); parser_till_end = ::google::privacy::dlp::v2::FieldId::_InternalParse; object = msg->add_identifying_fields(); if (size > end - ptr) goto len_delim_till_end; ptr += size; GOOGLE_PROTOBUF_PARSER_ASSERT(ctx->ParseExactRange( {parser_till_end, object}, ptr - size, ptr)); if (ptr >= end) break; } while ((::google::protobuf::io::UnalignedLoad<::google::protobuf::uint64>(ptr) & 255) == 10 && (ptr += 1)); break; } default: { handle_unusual: if ((tag & 7) == 4 || tag == 0) { ctx->EndGroup(tag); return ptr; } auto res = UnknownFieldParse(tag, {_InternalParse, msg}, ptr, end, msg->_internal_metadata_.mutable_unknown_fields(), ctx); ptr = res.first; GOOGLE_PROTOBUF_PARSER_ASSERT(ptr != nullptr); if (res.second) return ptr; } } // switch } // while return ptr; len_delim_till_end: return ctx->StoreAndTailCall(ptr, end, {_InternalParse, msg}, {parser_till_end, object}, size); } #else // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER bool TableOptions::MergePartialFromCodedStream( ::google::protobuf::io::CodedInputStream* input) { #define DO_(EXPRESSION) if (!PROTOBUF_PREDICT_TRUE(EXPRESSION)) goto failure ::google::protobuf::uint32 tag; // @@protoc_insertion_point(parse_start:google.privacy.dlp.v2.TableOptions) 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 .google.privacy.dlp.v2.FieldId identifying_fields = 1; case 1: { if (static_cast< ::google::protobuf::uint8>(tag) == (10 & 0xFF)) { DO_(::google::protobuf::internal::WireFormatLite::ReadMessage( input, add_identifying_fields())); } 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:google.privacy.dlp.v2.TableOptions) return true; failure: // @@protoc_insertion_point(parse_failure:google.privacy.dlp.v2.TableOptions) return false; #undef DO_ } #endif // GOOGLE_PROTOBUF_ENABLE_EXPERIMENTAL_PARSER void TableOptions::SerializeWithCachedSizes( ::google::protobuf::io::CodedOutputStream* output) const { // @@protoc_insertion_point(serialize_start:google.privacy.dlp.v2.TableOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->identifying_fields_size()); i < n; i++) { ::google::protobuf::internal::WireFormatLite::WriteMessageMaybeToArray( 1, this->identifying_fields(static_cast<int>(i)), output); } if (_internal_metadata_.have_unknown_fields()) { ::google::protobuf::internal::WireFormat::SerializeUnknownFields( _internal_metadata_.unknown_fields(), output); } // @@protoc_insertion_point(serialize_end:google.privacy.dlp.v2.TableOptions) } ::google::protobuf::uint8* TableOptions::InternalSerializeWithCachedSizesToArray( ::google::protobuf::uint8* target) const { // @@protoc_insertion_point(serialize_to_array_start:google.privacy.dlp.v2.TableOptions) ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 1; for (unsigned int i = 0, n = static_cast<unsigned int>(this->identifying_fields_size()); i < n; i++) { target = ::google::protobuf::internal::WireFormatLite:: InternalWriteMessageToArray( 1, this->identifying_fields(static_cast<int>(i)), target); } if (_internal_metadata_.have_unknown_fields()) { target = ::google::protobuf::internal::WireFormat::SerializeUnknownFieldsToArray( _internal_metadata_.unknown_fields(), target); } // @@protoc_insertion_point(serialize_to_array_end:google.privacy.dlp.v2.TableOptions) return target; } size_t TableOptions::ByteSizeLong() const { // @@protoc_insertion_point(message_byte_size_start:google.privacy.dlp.v2.TableOptions) size_t total_size = 0; if (_internal_metadata_.have_unknown_fields()) { total_size += ::google::protobuf::internal::WireFormat::ComputeUnknownFieldsSize( _internal_metadata_.unknown_fields()); } ::google::protobuf::uint32 cached_has_bits = 0; // Prevent compiler warnings about cached_has_bits being unused (void) cached_has_bits; // repeated .google.privacy.dlp.v2.FieldId identifying_fields = 1; { unsigned int count = static_cast<unsigned int>(this->identifying_fields_size()); total_size += 1UL * count; for (unsigned int i = 0; i < count; i++) { total_size += ::google::protobuf::internal::WireFormatLite::MessageSize( this->identifying_fields(static_cast<int>(i))); } } int cached_size = ::google::protobuf::internal::ToCachedSize(total_size); SetCachedSize(cached_size); return total_size; } void TableOptions::MergeFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_merge_from_start:google.privacy.dlp.v2.TableOptions) GOOGLE_DCHECK_NE(&from, this); const TableOptions* source = ::google::protobuf::DynamicCastToGenerated<TableOptions>( &from); if (source == nullptr) { // @@protoc_insertion_point(generalized_merge_from_cast_fail:google.privacy.dlp.v2.TableOptions) ::google::protobuf::internal::ReflectionOps::Merge(from, this); } else { // @@protoc_insertion_point(generalized_merge_from_cast_success:google.privacy.dlp.v2.TableOptions) MergeFrom(*source); } } void TableOptions::MergeFrom(const TableOptions& from) { // @@protoc_insertion_point(class_specific_merge_from_start:google.privacy.dlp.v2.TableOptions) GOOGLE_DCHECK_NE(&from, this); _internal_metadata_.MergeFrom(from._internal_metadata_); ::google::protobuf::uint32 cached_has_bits = 0; (void) cached_has_bits; identifying_fields_.MergeFrom(from.identifying_fields_); } void TableOptions::CopyFrom(const ::google::protobuf::Message& from) { // @@protoc_insertion_point(generalized_copy_from_start:google.privacy.dlp.v2.TableOptions) if (&from == this) return; Clear(); MergeFrom(from); } void TableOptions::CopyFrom(const TableOptions& from) { // @@protoc_insertion_point(class_specific_copy_from_start:google.privacy.dlp.v2.TableOptions) if (&from == this) return; Clear(); MergeFrom(from); } bool TableOptions::IsInitialized() const { return true; } void TableOptions::Swap(TableOptions* other) { if (other == this) return; InternalSwap(other); } void TableOptions::InternalSwap(TableOptions* other) { using std::swap; _internal_metadata_.Swap(&other->_internal_metadata_); CastToBase(&identifying_fields_)->InternalSwap(CastToBase(&other->identifying_fields_)); } ::google::protobuf::Metadata TableOptions::GetMetadata() const { ::google::protobuf::internal::AssignDescriptors(&::assign_descriptors_table_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto); return ::file_level_metadata_google_2fprivacy_2fdlp_2fv2_2fstorage_2eproto[kIndexInFileMessages]; } // @@protoc_insertion_point(namespace_scope) } // namespace v2 } // namespace dlp } // namespace privacy } // namespace google namespace google { namespace protobuf { template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::InfoType* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::InfoType >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::InfoType >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::StoredType* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::StoredType >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::StoredType >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_Dictionary_WordList >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_Dictionary* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_Dictionary >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_Dictionary >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_Regex* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_Regex >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_Regex >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_SurrogateType* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_SurrogateType >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_SurrogateType >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_Proximity >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_LikelihoodAdjustment >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule_HotwordRule >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType_DetectionRule* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType_DetectionRule >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CustomInfoType* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CustomInfoType >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CustomInfoType >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::FieldId* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::FieldId >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::FieldId >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::PartitionId* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::PartitionId >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::PartitionId >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::KindExpression* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::KindExpression >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::KindExpression >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::DatastoreOptions* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::DatastoreOptions >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::DatastoreOptions >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CloudStorageRegexFileSet* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CloudStorageRegexFileSet >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CloudStorageRegexFileSet >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CloudStorageOptions_FileSet* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CloudStorageOptions_FileSet >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CloudStorageOptions_FileSet >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CloudStorageOptions* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CloudStorageOptions >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CloudStorageOptions >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CloudStorageFileSet* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CloudStorageFileSet >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CloudStorageFileSet >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::CloudStoragePath* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::CloudStoragePath >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::CloudStoragePath >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::BigQueryOptions* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::BigQueryOptions >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::BigQueryOptions >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::StorageConfig_TimespanConfig* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::StorageConfig_TimespanConfig >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::StorageConfig_TimespanConfig >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::StorageConfig* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::StorageConfig >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::StorageConfig >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::HybridOptions_LabelsEntry_DoNotUse >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::HybridOptions* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::HybridOptions >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::HybridOptions >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::BigQueryKey* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::BigQueryKey >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::BigQueryKey >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::DatastoreKey* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::DatastoreKey >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::DatastoreKey >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::Key_PathElement* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::Key_PathElement >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::Key_PathElement >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::Key* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::Key >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::Key >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::RecordKey* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::RecordKey >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::RecordKey >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::BigQueryTable* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::BigQueryTable >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::BigQueryTable >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::BigQueryField* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::BigQueryField >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::BigQueryField >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::EntityId* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::EntityId >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::EntityId >(arena); } template<> PROTOBUF_NOINLINE ::google::privacy::dlp::v2::TableOptions* Arena::CreateMaybeMessage< ::google::privacy::dlp::v2::TableOptions >(Arena* arena) { return Arena::CreateInternal< ::google::privacy::dlp::v2::TableOptions >(arena); } } // namespace protobuf } // namespace google // @@protoc_insertion_point(global_scope) #include <google/protobuf/port_undef.inc>
41.474262
232
0.716328
kashiish
0046c638e7ee0b932ba46c03c86d96be44efd1f2
1,642
cc
C++
packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_CoherentInelastic_SingleXtal_kernel.cc
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
5
2017-01-16T03:59:47.000Z
2020-06-23T02:54:19.000Z
packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_CoherentInelastic_SingleXtal_kernel.cc
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
293
2015-10-29T17:45:52.000Z
2022-01-07T16:31:09.000Z
packages/mccomponents/mccomponentsbpmodule/wrap_Phonon_CoherentInelastic_SingleXtal_kernel.cc
mcvine/mcvine
42232534b0c6af729628009bed165cd7d833789d
[ "BSD-3-Clause" ]
1
2019-05-25T00:53:31.000Z
2019-05-25T00:53:31.000Z
// -*- C++ -*- // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // // Jiao Lin // California Institute of Technology // (C) 2007-2010 All Rights Reserved // // {LicenseText} // // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // #include <sstream> #include <boost/python.hpp> #include "mccomponents/math/rootfinding.h" #include "mccomponents/kernels/sample/phonon/TargetCone.h" #include "mccomponents/kernels/sample/phonon/AbstractDispersion_3D.h" #include "mccomponents/kernels/sample/phonon/AbstractDebyeWallerFactor.h" #include "mccomponents/kernels/sample/phonon/CoherentInelastic_SingleXtal.h" #include "mccomponents/boostpython_binding/wrap_kernel.h" namespace wrap_mccomponents { void wrap_Phonon_CoherentInelastic_SingleXtal_kernel() { using namespace boost::python; using namespace mccomponents::boostpython_binding; typedef mccomponents::kernels::phonon::CoherentInelastic_SingleXtal w_t; kernel_wrapper<w_t>::wrap ( "Phonon_CoherentInelastic_SingleXtal_kernel", init< const w_t::dispersion_t &, const w_t::atoms_t &, w_t::float_t, // uc vol w_t::dwcalculator_t & , w_t::float_t, // temperature w_t::float_t, // deltaV_Jacobi const w_t::rootsfinder_t &, const w_t::target_region_t &, w_t::float_t // epsilon > () [with_custodian_and_ward<1,2, with_custodian_and_ward<1,3, with_custodian_and_ward<1,5, with_custodian_and_ward<1,8, with_custodian_and_ward<1,9> > > > > () ] ) ; } } // version // $Id$ // End of file
25.65625
81
0.626066
mcvine
004ccf2cd8b1955dfcdc018a74343e217ce5c42c
3,603
cpp
C++
Raven.CppClient/AbstractIndexCreationTaskBase.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-04-24T02:34:53.000Z
2019-08-01T08:22:26.000Z
Raven.CppClient/AbstractIndexCreationTaskBase.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
2
2019-03-21T09:00:02.000Z
2021-02-28T23:49:26.000Z
Raven.CppClient/AbstractIndexCreationTaskBase.cpp
mlawsonca/ravendb-cpp-client
c3a3d4960c8b810156547f62fa7aeb14a121bf74
[ "MIT" ]
3
2019-03-04T11:58:54.000Z
2021-03-01T00:25:49.000Z
#include "stdafx.h" #include "AbstractIndexCreationTaskBase.h" #include "GetCppClassName.h" #include "MaintenanceOperationExecutor.h" #include "PutIndexesOperation.h" namespace ravendb::client::documents::indexes { void AbstractIndexCreationTaskBase::throw_index_name_was_set() { throw std::runtime_error("The index name was already set"); } void AbstractIndexCreationTaskBase::throw_index_name_was_not_set() { throw std::runtime_error("Index name was not set." "Did you forget to call set_index_name() or set_default_index_name() ?"); } void AbstractIndexCreationTaskBase::set_index_name(std::string index_name) { if(_index_name) { throw_index_name_was_set(); } _index_name = std::move(index_name); } void AbstractIndexCreationTaskBase::set_default_index_name(std::type_index type) { if (_index_name) { throw_index_name_was_set(); } auto&& index_name = impl::utils::GetCppClassName::get_simple_class_name(type); for(auto& c : index_name) { if(c == '_') c = '/'; } _index_name = std::move(index_name); } AbstractIndexCreationTaskBase::~AbstractIndexCreationTaskBase() = default; const std::optional<std::unordered_map<std::string, std::string>>& AbstractIndexCreationTaskBase::get_additional_sources() const { return additional_sources; } void AbstractIndexCreationTaskBase::set_additional_sources( std::optional<std::unordered_map<std::string, std::string>> additional_sources_param) { additional_sources = std::move(additional_sources_param); } bool AbstractIndexCreationTaskBase::is_map_reduce() const { return false; } std::string AbstractIndexCreationTaskBase::get_index_name() const { if(!_index_name) { throw_index_name_was_not_set(); } return *_index_name; } std::shared_ptr<conventions::DocumentConventions> AbstractIndexCreationTaskBase::get_conventions() const { return conventions; } void AbstractIndexCreationTaskBase::set_conventions( std::shared_ptr<conventions::DocumentConventions> conventions_param) { conventions = conventions_param; } std::optional<IndexPriority> AbstractIndexCreationTaskBase::get_priority() const { return priority; } void AbstractIndexCreationTaskBase::set_priority(std::optional<IndexPriority> priority_param) { priority = priority_param; } std::optional<IndexLockMode> AbstractIndexCreationTaskBase::get_lock_mode() const { return lock_mode; } void AbstractIndexCreationTaskBase::set_lock_mode(std::optional<IndexLockMode> lock_mode_param) { lock_mode = lock_mode_param; } void AbstractIndexCreationTaskBase::execute(std::shared_ptr<IDocumentStore> store, std::shared_ptr<conventions::DocumentConventions> conventions_param, std::optional<std::string> database) { struct OldConventionsRestore { AbstractIndexCreationTaskBase* outer_this; std::shared_ptr<conventions::DocumentConventions> old_conventions; ~OldConventionsRestore(){ outer_this->set_conventions(old_conventions); } } old_conventions_restore{this, get_conventions()}; if (conventions_param) { set_conventions(conventions_param); } else if(get_conventions()) {} else { set_conventions(store->get_conventions()); } auto index_definition = create_index_definition(); index_definition.name = get_index_name(); if(lock_mode) { index_definition.lock_mode = *lock_mode; } if(priority) { index_definition.priority = *priority; } store->maintenance() ->for_database(database ? *database : store->get_database()) ->send(operations::indexes::PutIndexesOperation({ index_definition })); } }
25.020833
105
0.760755
mlawsonca
0052cc864933fa4d30c8c6eb289a0e6ea557df34
17
cpp
C++
Tests/QtAutogen/UicNoGui/NoQt/main.cpp
eWert-Online/esy-cmake
c0de72da9a1bc4d9b4fbe3766bafcbaca442cc2c
[ "MIT" ]
107
2021-08-28T20:08:42.000Z
2022-03-22T08:02:16.000Z
Tests/QtAutogen/UicNoGui/NoQt/main.cpp
eWert-Online/esy-cmake
c0de72da9a1bc4d9b4fbe3766bafcbaca442cc2c
[ "MIT" ]
null
null
null
Tests/QtAutogen/UicNoGui/NoQt/main.cpp
eWert-Online/esy-cmake
c0de72da9a1bc4d9b4fbe3766bafcbaca442cc2c
[ "MIT" ]
16
2021-08-30T06:57:36.000Z
2022-03-22T08:05:52.000Z
void noQt() { }
3.4
11
0.470588
eWert-Online
0053ad050e024fdd08b7d00d56a57979e6458421
951
cpp
C++
Graph Algorithms/Havel Hakimi/main.cpp
Swizop/Algorithms
d3f4ec0040a92680649e22b8b90982ddb9293d07
[ "MIT" ]
null
null
null
Graph Algorithms/Havel Hakimi/main.cpp
Swizop/Algorithms
d3f4ec0040a92680649e22b8b90982ddb9293d07
[ "MIT" ]
null
null
null
Graph Algorithms/Havel Hakimi/main.cpp
Swizop/Algorithms
d3f4ec0040a92680649e22b8b90982ddb9293d07
[ "MIT" ]
null
null
null
#include <iostream> #include <fstream> #include <vector> #include <algorithm> using namespace std; ifstream f("havel.in"); int main() { int i, x, n, j; f >> n; vector<int> degrees; for(i = 1; i <= n; i++) { f >> x; degrees.push_back(x); } while(true) { sort(degrees.begin(), degrees.end()); i = degrees.size() - 1; if(degrees[i] == 0) // every node has degree 0 so the graph can be made { cout << "Yes."; break; } j = i - 1; while(j >= 0 && degrees[i] > 0) { degrees[j]--; degrees[i]--; if(degrees[j] < 0) { cout << "No!"; return 0; } j--; } if(j == -1 && degrees[i] > 0) { cout << "No!"; break; } degrees.pop_back(); } return 0; }
19.02
83
0.383807
Swizop
0058f608ad695add4d0c926a9eb7e3ad3a78a0d6
5,080
cpp
C++
CPP/Targets/SupportWFLib/symbian/NavTaskGuiHandler.cpp
wayfinder/Wayfinder-S60-Navigator
14d1b729b2cea52f726874687e78f17492949585
[ "BSD-3-Clause" ]
6
2015-12-01T01:12:33.000Z
2021-07-24T09:02:34.000Z
CPP/Targets/SupportWFLib/symbian/NavTaskGuiHandler.cpp
wayfinder/Wayfinder-S60-Navigator
14d1b729b2cea52f726874687e78f17492949585
[ "BSD-3-Clause" ]
null
null
null
CPP/Targets/SupportWFLib/symbian/NavTaskGuiHandler.cpp
wayfinder/Wayfinder-S60-Navigator
14d1b729b2cea52f726874687e78f17492949585
[ "BSD-3-Clause" ]
2
2017-02-02T19:31:29.000Z
2018-12-17T21:00:45.000Z
/* Copyright (c) 1999 - 2010, Vodafone Group Services Ltd All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the Vodafone Group Services Ltd nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "arch.h" /* #include <badesca.h> */ //#include "GuiFileOperation.h" #include "NavTaskGuiHandler.h" #include "GuiProt/ServerEnums.h" #include "GuiProt/GuiProtEnums.h" #include "GuiProt/GuiProtMess.h" #include "GuiProt/GuiProtFileMess.h" #include "nav2util.h" #include "WFTextUtil.h" using namespace isab; char * CNavTaskGuiCommandHandler::aBaseName(const char *full) { HBufC* tmp = WFTextUtil::AllocLC(full); TInt i = tmp->LocateReverse('/'); CleanupStack::PopAndDestroy(tmp); char *filename = NULL; if (KErrNotFound == i) { filename = strdup_new(full); } else { filename = strdup_new((const char*)&full[i]); } return filename; } void CNavTaskGuiCommandHandler::SendCommandL(uint16 command) { class GuiFileOperationCommand *op = new GuiFileOperationCommand(0, command); SendFileOperationL(op); } void CNavTaskGuiCommandHandler::HandleGuiFileOperation(GuiProtFileMess* message) { /* Handle file operation messages. */ GuiFileOperation* op = message->getFileOperation(); switch (op->typeId()) { case OPERATION_SELECT: /* Show user a selection dialogue. */ HandleGuiFileOperationSelect(static_cast<GuiFileOperationSelect*>(op)); break; case OPERATION_SELECT_REPLY: /* Should never get here. */ break; case OPERATION_CONFIRM: /* Show user a confirmation dialogue. */ HandleGuiFileOperationConfirm(static_cast<GuiFileOperationConfirm*>(op)); break; case OPERATION_CONFIRM_REPLY: /* Should never get here. */ break; case OPERATION_COMMAND: break; } } void CNavTaskGuiCommandHandler::EditOk(class CEditFileNameOperation* edit) { char *filename = WFTextUtil::newTDesDupL(*edit->iEditField); delete edit->iEditField; /* Takes ownership of allocated entries. */ GuiFileOperationSelectReply* rep = new GuiFileOperationSelectReply( 0, edit->iSelected, edit->iCommand, edit->iFileLocation, filename); SendFileOperationL(rep); delete edit; } void CNavTaskGuiCommandHandler::EditCancel(class CEditFileNameOperation* edit) { char *filename = WFTextUtil::newTDesDupL(*edit->iEditField); delete edit->iEditField; /* Takes ownership of allocated entries. */ GuiFileOperationSelectReply* rep = new GuiFileOperationSelectReply( 0, edit->iSelected, command_cancel, edit->iFileLocation, filename); SendFileOperationL(rep); delete edit; } void CNavTaskGuiCommandHandler::ConfirmOk(class CConfirmCommandOperation* confirm) { delete confirm->iAdditionalInfo; /* Takes ownership of allocated entries. */ GuiFileOperationConfirmReply* rep = new GuiFileOperationConfirmReply( 0, confirm->iCommand, confirm->iFileLocation); SendFileOperationL(rep); delete confirm; } void CNavTaskGuiCommandHandler::ConfirmCancel(class CConfirmCommandOperation* confirm) { delete confirm->iAdditionalInfo; /* Takes ownership of allocated entries. */ GuiFileOperationConfirmReply* rep = new GuiFileOperationConfirmReply( 0, command_confirm_no, confirm->iFileLocation); SendFileOperationL(rep); delete confirm; }
31.358025
207
0.691929
wayfinder
0059dd34aff2b4d2706c023af6cbe8af14f4b01e
12,257
cpp
C++
src/tablestore/core/error.cpp
TimeExceed/aliyun-tablestore-cpp-sdk
f8d2fdf500badf70073dff4e21a5d2d7aa7d3853
[ "BSD-3-Clause" ]
2
2020-02-24T06:51:55.000Z
2020-04-24T14:40:10.000Z
src/tablestore/core/error.cpp
TimeExceed/aliyun-tablestore-cpp-sdk
f8d2fdf500badf70073dff4e21a5d2d7aa7d3853
[ "BSD-3-Clause" ]
null
null
null
src/tablestore/core/error.cpp
TimeExceed/aliyun-tablestore-cpp-sdk
f8d2fdf500badf70073dff4e21a5d2d7aa7d3853
[ "BSD-3-Clause" ]
1
2020-02-24T06:51:57.000Z
2020-02-24T06:51:57.000Z
/* BSD 3-Clause License Copyright (c) 2017, Alibaba Cloud All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "tablestore/core/error.hpp" #include "tablestore/util/mempiece.hpp" #include "tablestore/util/prettyprint.hpp" using namespace std; using namespace aliyun::tablestore::util; namespace aliyun { namespace tablestore { namespace core { const string OTSError::kErrorCode_CouldntResolveHost("OTSCouldntResolveHost"); const string OTSError::kErrorCode_CouldntConnect("OTSCouldntConnect"); const string OTSError::kErrorCode_WriteRequestFail("OTSWriteRequestFail"); const string OTSError::kErrorCode_CorruptedResponse("OTSCorruptedResponse"); const string OTSError::kErrorCode_NoAvailableConnection("OTSNoAvailableConnection"); const string OTSError::kErrorCode_SslHandshakeFail("OTSSslHandshakeFail"); const string OTSError::kErrorCode_OTSOutOfColumnCountLimit("OTSOutOfColumnCountLimit"); const string OTSError::kErrorCode_OTSObjectNotExist("OTSObjectNotExist"); const string OTSError::kErrorCode_OTSServerBusy("OTSServerBusy"); const string OTSError::kErrorCode_OTSCapacityUnitExhausted("OTSCapacityUnitExhausted"); const string OTSError::kErrorCode_OTSTooFrequentReservedThroughputAdjustment( "OTSTooFrequentReservedThroughputAdjustment"); const string OTSError::kErrorCode_OTSInternalServerError("OTSInternalServerError"); const string OTSError::kErrorCode_OTSQuotaExhausted("OTSQuotaExhausted"); const string OTSError::kErrorCode_OTSRequestBodyTooLarge("OTSRequestBodyTooLarge"); const string OTSError::kErrorCode_OTSTimeout("OTSTimeout"); const string OTSError::kErrorCode_OTSObjectAlreadyExist("OTSObjectAlreadyExist"); const string OTSError::kErrorCode_OTSTableNotReady("OTSTableNotReady"); const string OTSError::kErrorCode_OTSConditionCheckFail("OTSConditionCheckFail"); const string OTSError::kErrorCode_OTSOutOfRowSizeLimit("OTSOutOfRowSizeLimit"); const string OTSError::kErrorCode_OTSInvalidPK("OTSInvalidPK"); const string OTSError::kErrorCode_OTSRequestTimeout("OTSRequestTimeout"); const string OTSError::kErrorCode_OTSMethodNotAllowed("OTSMethodNotAllowed"); const string OTSError::kErrorCode_OTSAuthFailed("OTSAuthFailed"); const string OTSError::kErrorCode_OTSServerUnavailable("OTSServerUnavailable"); const string OTSError::kErrorCode_OTSParameterInvalid("OTSParameterInvalid"); const string OTSError::kErrorCode_OTSRowOperationConflict("OTSRowOperationConflict"); const string OTSError::kErrorCode_OTSPartitionUnavailable("OTSPartitionUnavailable"); OTSError::OTSError(Predefined def) { switch(def) { case kPredefined_CouldntResoveHost: init(kHttpStatus_CouldntResolveHost, kErrorCode_CouldntResolveHost); break; case kPredefined_CouldntConnect: init(kHttpStatus_CouldntConnect, kErrorCode_CouldntConnect); break; case kPredefined_OperationTimeout: init(kHttpStatus_OperationTimeout, kErrorCode_OTSRequestTimeout); break; case kPredefined_WriteRequestFail: init(kHttpStatus_WriteRequestFail, kErrorCode_WriteRequestFail); break; case kPredefined_CorruptedResponse: init(kHttpStatus_CorruptedResponse, kErrorCode_CorruptedResponse); break; case kPredefined_NoConnectionAvailable: init(kHttpStatus_NoAvailableConnection, kErrorCode_NoAvailableConnection); break; case kPredefined_OTSOutOfColumnCountLimit: init(400, kErrorCode_OTSOutOfColumnCountLimit); break; case kPredefined_OTSObjectNotExist: init(404, kErrorCode_OTSObjectNotExist); break; case kPredefined_OTSServerBusy: init(503, kErrorCode_OTSServerBusy); break; case kPredefined_OTSCapacityUnitExhausted: init(403, kErrorCode_OTSCapacityUnitExhausted); break; case kPredefined_OTSTooFrequentReservedThroughputAdjustment: init(403, kErrorCode_OTSTooFrequentReservedThroughputAdjustment); break; case kPredefined_OTSInternalServerError: init(500, kErrorCode_OTSInternalServerError); break; case kPredefined_OTSQuotaExhausted: init(403, kErrorCode_OTSQuotaExhausted); break; case kPredefined_OTSRequestBodyTooLarge: init(413, kErrorCode_OTSRequestBodyTooLarge); break; case kPredefined_OTSTimeout: init(503, kErrorCode_OTSTimeout); break; case kPredefined_OTSObjectAlreadyExist: init(409, kErrorCode_OTSObjectAlreadyExist); break; case kPredefined_OTSTableNotReady: init(404, kErrorCode_OTSTableNotReady); break; case kPredefined_OTSConditionCheckFail: init(403, kErrorCode_OTSConditionCheckFail); break; case kPredefined_OTSOutOfRowSizeLimit: init(400, kErrorCode_OTSOutOfRowSizeLimit); break; case kPredefined_OTSInvalidPK: init(400, kErrorCode_OTSInvalidPK); break; case kPredefined_OTSMethodNotAllowed: init(405, kErrorCode_OTSMethodNotAllowed); break; case kPredefined_OTSAuthFailed: init(403, kErrorCode_OTSAuthFailed); break; case kPredefined_OTSServerUnavailable: init(503, kErrorCode_OTSServerUnavailable); break; case kPredefined_OTSParameterInvalid: init(400, kErrorCode_OTSParameterInvalid); break; case kPredefined_OTSRowOperationConflict: init(409, kErrorCode_OTSRowOperationConflict); break; case kPredefined_OTSPartitionUnavailable: init(503, kErrorCode_OTSPartitionUnavailable); break; case kPredefined_SslHandshakeFail: init(kHttpStatus_SslHandshakeFail, kErrorCode_SslHandshakeFail); break; } } void OTSError::init(int64_t hs, const string& ec) { mHttpStatus = hs; mErrorCode = ec; } void OTSError::prettyPrint(string& out) const { out.append("{\"HttpStatus\": "); pp::prettyPrint(out, mHttpStatus); out.append(", \"ErrorCode\": \""); out.append(mErrorCode); out.append("\", \"Message\": \""); out.append(mMessage); if (!mRequestId.empty()) { out.append("\", \"RequestId\": \""); out.append(mRequestId); } if (!mTraceId.empty()) { out.append("\", \"TraceId\": \""); out.append(mTraceId); } out.append("\"}"); } void OTSError::setHttpStatusFromErrorCode(const string& _ec) { MemPiece ec = MemPiece::from(_ec); if (ec == MemPiece::from(kErrorCode_CouldntResolveHost)) { mHttpStatus = kHttpStatus_CouldntResolveHost; } else if (ec == MemPiece::from(kErrorCode_CouldntConnect)) { mHttpStatus = kHttpStatus_CouldntConnect; } else if (ec == MemPiece::from(kErrorCode_OTSRequestTimeout)) { mHttpStatus = kHttpStatus_OperationTimeout; } else if (ec == MemPiece::from(kErrorCode_WriteRequestFail)) { mHttpStatus = kHttpStatus_WriteRequestFail; } else if (ec == MemPiece::from(kErrorCode_CorruptedResponse)) { mHttpStatus = kHttpStatus_CorruptedResponse; } else if (ec == MemPiece::from(kErrorCode_NoAvailableConnection)) { mHttpStatus = kHttpStatus_NoAvailableConnection; } else if (ec == MemPiece::from(kErrorCode_OTSOutOfColumnCountLimit)) { mHttpStatus = 400; } else if (ec == MemPiece::from(kErrorCode_OTSObjectNotExist)) { mHttpStatus = 404; } else if (ec == MemPiece::from(kErrorCode_OTSServerBusy)) { mHttpStatus = 503; } else if (ec == MemPiece::from(kErrorCode_OTSCapacityUnitExhausted)) { mHttpStatus = 403; } else if (ec == MemPiece::from(kErrorCode_OTSTooFrequentReservedThroughputAdjustment)) { mHttpStatus = 403; } else if (ec == MemPiece::from(kErrorCode_OTSInternalServerError)) { mHttpStatus = 500; } else if (ec == MemPiece::from(kErrorCode_OTSQuotaExhausted)) { mHttpStatus = 403; } else if (ec == MemPiece::from(kErrorCode_OTSRequestBodyTooLarge)) { mHttpStatus = 413; } else if (ec == MemPiece::from(kErrorCode_OTSTimeout)) { mHttpStatus = 503; } else if (ec == MemPiece::from(kErrorCode_OTSObjectAlreadyExist)) { mHttpStatus = 409; } else if (ec == MemPiece::from(kErrorCode_OTSTableNotReady)) { mHttpStatus = 404; } else if (ec == MemPiece::from(kErrorCode_OTSConditionCheckFail)) { mHttpStatus = 403; } else if (ec == MemPiece::from(kErrorCode_OTSOutOfRowSizeLimit)) { mHttpStatus = 400; } else if (ec == MemPiece::from(kErrorCode_OTSInvalidPK)) { mHttpStatus = 400; } else if (ec == MemPiece::from(kErrorCode_OTSMethodNotAllowed)) { mHttpStatus = 405; } else if (ec == MemPiece::from(kErrorCode_OTSAuthFailed)) { mHttpStatus = 403; } else if (ec == MemPiece::from(kErrorCode_OTSServerUnavailable)) { mHttpStatus = 503; } else if (ec == MemPiece::from(kErrorCode_OTSParameterInvalid)) { mHttpStatus = 400; } else if (ec == MemPiece::from(kErrorCode_OTSRowOperationConflict)) { mHttpStatus = 409; } else if (ec == MemPiece::from(kErrorCode_OTSPartitionUnavailable)) { mHttpStatus = 503; } else if (ec == MemPiece::from(kErrorCode_SslHandshakeFail)) { mHttpStatus = kHttpStatus_SslHandshakeFail; } else { mHttpStatus = 400; } } bool isCurlError(const OTSError& err) { return err.httpStatus() > 0 && err.httpStatus() <= 99; } bool isTemporary(const OTSError& err) { if (err.httpStatus() >= 500 && err.httpStatus() <= 599) { return true; } if (err.httpStatus() >= 400 && err.httpStatus() <= 499) { MemPiece code = MemPiece::from(err.errorCode()); MemPiece msg = MemPiece::from(err.message()); if (code == MemPiece::from("OTSQuotaExhausted") && msg == MemPiece::from("Too frequent table operations.")) { return true; } else if (code == MemPiece::from("OTSRowOperationConflict")) { return true; } else if (code == MemPiece::from("OTSTableNotReady")) { return true; } else if (code == MemPiece::from("OTSTooFrequentReservedThroughputAdjustment")) { return true; } else if (code == MemPiece::from("OTSCapacityUnitExhausted")) { return true; } else if (code == MemPiece::from("OTSRequestTimeout")) { return true; } } if (isCurlError(err)) { switch(err.httpStatus()) { case OTSError::kHttpStatus_CouldntResolveHost: case OTSError::kHttpStatus_CouldntConnect: case OTSError::kHttpStatus_OperationTimeout: case OTSError::kHttpStatus_WriteRequestFail: case OTSError::kHttpStatus_CorruptedResponse: case OTSError::kHttpStatus_NoAvailableConnection: return true; default: break; } } return false; } } // namespace core } // namespace tablestore } // namespace aliyun
41.549153
117
0.725381
TimeExceed
005b04f990045526bc490b386efddb77e7654851
1,462
hpp
C++
include/pyplot_cpp/plt/pyplot.hpp
CalebCintary/pyplot_cpp
de33c3e921229e5efd72a7fc4fdb17212edc9aa9
[ "MIT" ]
1
2022-03-29T10:52:21.000Z
2022-03-29T10:52:21.000Z
include/pyplot_cpp/plt/pyplot.hpp
CalebCintary/pyplot_cpp
de33c3e921229e5efd72a7fc4fdb17212edc9aa9
[ "MIT" ]
1
2022-03-20T12:17:11.000Z
2022-03-20T17:50:12.000Z
include/pyplot_cpp/plt/pyplot.hpp
CalebCintary/pyplot_cpp
de33c3e921229e5efd72a7fc4fdb17212edc9aa9
[ "MIT" ]
1
2022-03-29T19:40:59.000Z
2022-03-29T19:40:59.000Z
// // Created by calebcintary on 3/15/22. // // NOTE: Might be connection point between Dynamic Script and Embedded Interpreter // #ifndef PYPLOT_CPP_PYPLOT_HPP #define PYPLOT_CPP_PYPLOT_HPP #include <string> #include <sstream> #include <vector> #include <map> #include "Property.hpp" #include "pyplot_cpp/converter/converter.hpp" #define PYPLOT_PropertyArray const std::map<std::string, Property>& namespace pyplot_cpp { namespace plt { // ----- < Show able objects > ----- std::string plot(const std::string& x, const std::string& y, PYPLOT_PropertyArray args = {}); std::string plot(const std::vector<double>& x, std::vector<double>& y, PYPLOT_PropertyArray args = {}); std::string bar(const std::string& x, const std::string& y, PYPLOT_PropertyArray args = {}); std::string hist(const std::string& x, PYPLOT_PropertyArray args = {}); std::string scatter(const std::string& x, const std::string& y, PYPLOT_PropertyArray args = {}); // ----- < Different functions > ----- std::string import(); std::string xlabel(const std::string& xlabel); std::string ylabel(const std::string& ylabel); std::string title(const std::string& title); std::string tight_layout(); std::string show(); std::string savefig(const std::string& path); std::string legend(std::string legend_array); } } #endif //PYPLOT_CPP_PYPLOT_HPP
24.779661
111
0.650479
CalebCintary
005fefc45018788cdb3563f200504bb51ab56667
686
cpp
C++
src/593B.cpp
viing937/codeforces
d694eb6967cd56af02963c3a662066048cb78d07
[ "MIT" ]
2
2016-08-19T09:47:03.000Z
2016-10-01T10:15:03.000Z
src/593B.cpp
viing937/codeforces
d694eb6967cd56af02963c3a662066048cb78d07
[ "MIT" ]
null
null
null
src/593B.cpp
viing937/codeforces
d694eb6967cd56af02963c3a662066048cb78d07
[ "MIT" ]
1
2015-07-01T23:57:32.000Z
2015-07-01T23:57:32.000Z
#include <iostream> #include <cstdio> #include <vector> #include <map> #include <algorithm> using namespace std; int main() { int n; scanf("%d", &n); int x1, x2; scanf("%d%d", &x1, &x2); vector< pair<long long, long long> > arr; for ( int i = 0; i < n; ++i ) { int k, b; scanf("%d%d", &k, &b); arr.push_back(make_pair((long long)k*x1+b, (long long)k*x2+b)); } sort(arr.begin(), arr.end()); for ( int i = 0; i < n-1; ++i ) { if ( arr[i].first < arr[i+1].first && arr[i].second > arr[i+1].second ) { printf("YES\n"); return 0; } } printf("NO\n"); return 0; }
20.787879
79
0.472303
viing937
00611f8b4fb0a8cb06bebf72cff0fb151704ec8a
4,449
cpp
C++
privatedns/src/v20201028/model/TldQuota.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
1
2022-01-27T09:27:34.000Z
2022-01-27T09:27:34.000Z
privatedns/src/v20201028/model/TldQuota.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
privatedns/src/v20201028/model/TldQuota.cpp
suluner/tencentcloud-sdk-cpp
a56c73cc3f488c4d1e10755704107bb15c5e000d
[ "Apache-2.0" ]
null
null
null
/* * Copyright (c) 2017-2019 THL A29 Limited, a Tencent company. 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 <tencentcloud/privatedns/v20201028/model/TldQuota.h> using TencentCloud::CoreInternalOutcome; using namespace TencentCloud::Privatedns::V20201028::Model; using namespace std; TldQuota::TldQuota() : m_totalHasBeenSet(false), m_usedHasBeenSet(false), m_stockHasBeenSet(false), m_quotaHasBeenSet(false) { } CoreInternalOutcome TldQuota::Deserialize(const rapidjson::Value &value) { string requestId = ""; if (value.HasMember("Total") && !value["Total"].IsNull()) { if (!value["Total"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `TldQuota.Total` IsInt64=false incorrectly").SetRequestId(requestId)); } m_total = value["Total"].GetInt64(); m_totalHasBeenSet = true; } if (value.HasMember("Used") && !value["Used"].IsNull()) { if (!value["Used"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `TldQuota.Used` IsInt64=false incorrectly").SetRequestId(requestId)); } m_used = value["Used"].GetInt64(); m_usedHasBeenSet = true; } if (value.HasMember("Stock") && !value["Stock"].IsNull()) { if (!value["Stock"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `TldQuota.Stock` IsInt64=false incorrectly").SetRequestId(requestId)); } m_stock = value["Stock"].GetInt64(); m_stockHasBeenSet = true; } if (value.HasMember("Quota") && !value["Quota"].IsNull()) { if (!value["Quota"].IsInt64()) { return CoreInternalOutcome(Core::Error("response `TldQuota.Quota` IsInt64=false incorrectly").SetRequestId(requestId)); } m_quota = value["Quota"].GetInt64(); m_quotaHasBeenSet = true; } return CoreInternalOutcome(true); } void TldQuota::ToJsonObject(rapidjson::Value &value, rapidjson::Document::AllocatorType& allocator) const { if (m_totalHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Total"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_total, allocator); } if (m_usedHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Used"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_used, allocator); } if (m_stockHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Stock"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_stock, allocator); } if (m_quotaHasBeenSet) { rapidjson::Value iKey(rapidjson::kStringType); string key = "Quota"; iKey.SetString(key.c_str(), allocator); value.AddMember(iKey, m_quota, allocator); } } int64_t TldQuota::GetTotal() const { return m_total; } void TldQuota::SetTotal(const int64_t& _total) { m_total = _total; m_totalHasBeenSet = true; } bool TldQuota::TotalHasBeenSet() const { return m_totalHasBeenSet; } int64_t TldQuota::GetUsed() const { return m_used; } void TldQuota::SetUsed(const int64_t& _used) { m_used = _used; m_usedHasBeenSet = true; } bool TldQuota::UsedHasBeenSet() const { return m_usedHasBeenSet; } int64_t TldQuota::GetStock() const { return m_stock; } void TldQuota::SetStock(const int64_t& _stock) { m_stock = _stock; m_stockHasBeenSet = true; } bool TldQuota::StockHasBeenSet() const { return m_stockHasBeenSet; } int64_t TldQuota::GetQuota() const { return m_quota; } void TldQuota::SetQuota(const int64_t& _quota) { m_quota = _quota; m_quotaHasBeenSet = true; } bool TldQuota::QuotaHasBeenSet() const { return m_quotaHasBeenSet; }
24.445055
131
0.657901
suluner
00624f992da46ccb401186131cc5d4d2df6f1944
556
cpp
C++
Game/ZeldaDS/arm9/source/gslib/Hw/CpuClock.cpp
amaiorano/ZeldaDS
78b093796a17ca0aaef4ff8b53a41fe59adc072e
[ "MIT" ]
2
2018-02-18T19:11:39.000Z
2020-08-16T18:16:35.000Z
Game/ZeldaDS/arm9/source/gslib/Hw/CpuClock.cpp
amaiorano/ZeldaDS
78b093796a17ca0aaef4ff8b53a41fe59adc072e
[ "MIT" ]
null
null
null
Game/ZeldaDS/arm9/source/gslib/Hw/CpuClock.cpp
amaiorano/ZeldaDS
78b093796a17ca0aaef4ff8b53a41fe59adc072e
[ "MIT" ]
null
null
null
#include "CpuClock.h" #include <nds/timers.h> namespace CpuClock { namespace { CpuTickType gLastFrameElapsedTicks = 0; const uint32 gTimerChannel = 0; } void Update() { gLastFrameElapsedTicks = cpuEndTiming(); cpuStartTiming(gTimerChannel); // Restart timer for this frame } CpuTickType GetLastFrameElapsedTicks() { return gLastFrameElapsedTicks; } CpuTickType GetCurrFrameElapsedTicks() { //@TODO: Add cpuGetElapsed() that does the following... return ( (TIMER_DATA(gTimerChannel) | (TIMER_DATA(gTimerChannel+1)<<16) )); } }
19.172414
77
0.730216
amaiorano
0064c2a0436cffecfcc6c0c09b31b80c8bc15810
1,885
cpp
C++
2021/day20/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2021/day20/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
2021/day20/main.cpp
bielskij/AOC-2019
e98d660412037b3fdac4a6b49adcb9230f518c99
[ "MIT" ]
null
null
null
#include "common/types.h" #include "utils/file.h" #include "utils/utils.h" #define DEBUG_LEVEL 5 #include "common/debug.h" int main(int argc, char *argv[]) { std::string algorithm; std::vector<std::string> image; { bool parseAlgorithm = true; for (const auto &line : File::readAllLines(argv[1])) { if (line.empty()) { parseAlgorithm = false; } else { if (parseAlgorithm) { algorithm = line; } else { image.push_back(line); } } } } { std::vector<std::string> srcImage = image; std::vector<std::string> result; int padding = 0; int xMod[] = { -1, 0, 1, -1, 0, 1, -1, 0, 1 }; int yMod[] = { -1, -1, -1, 0, 0, 0, 1, 1, 1 }; for (int i = 0; i < 50; i++) { result.clear(); if (padding != 3) { padding = 3; } else { padding = -1; } for (int row = 0; row < srcImage.size() + padding * 2; row++) { std::string outRow; for (int col = 0; col < srcImage[0].length() + padding * 2; col++) { int padRow = row - padding; int padCol = col - padding; int index = 0; for (int idx = 0; idx < 9; idx++) { int cx = padCol + xMod[8 - idx]; int cy = padRow + yMod[8 - idx]; if ( (cy >= 0) && (cy < srcImage.size()) && (cx >= 0) && (cx < srcImage[0].length()) ) { index |= (((srcImage[cy][cx] == '#') ? 1 : 0) << idx); } } outRow.push_back(algorithm[index]); } result.push_back(outRow); } if ((i == 1) || (i == 49)) { int litNum = 0; for (const auto &r : result) { for (auto c : r) { if (c == '#') { litNum++; } } } PRINTF(("PART_%c: %d", i == 1 ? 'A' : 'B', litNum)); } srcImage = result; } #if 0 for (const auto &r : result) { for (auto c : r) { printf("%c", c); } printf("\n"); } printf("\n"); #endif } return 0; }
17.616822
72
0.481698
bielskij
006579b4fa6323be66e30c61ffd782770a19917a
608
cpp
C++
VideoPaletteExtraction/VideoPaletteExtraction/SystemParameter.cpp
Zhengjun-Du/GeometricPaletteBasedVideoRecoloring
d48f4fa942910b7e855eded4f1a2801db22050e4
[ "MIT" ]
10
2021-10-02T10:22:33.000Z
2022-02-16T07:11:22.000Z
VideoPaletteExtraction/VideoPaletteExtraction/SystemParameter.cpp
Zhengjun-Du/GeometricPaletteBasedVideoRecoloring
d48f4fa942910b7e855eded4f1a2801db22050e4
[ "MIT" ]
null
null
null
VideoPaletteExtraction/VideoPaletteExtraction/SystemParameter.cpp
Zhengjun-Du/GeometricPaletteBasedVideoRecoloring
d48f4fa942910b7e855eded4f1a2801db22050e4
[ "MIT" ]
5
2021-10-02T14:00:50.000Z
2022-02-08T06:25:06.000Z
#include "SystemParameter.h" int SysParameter::frmCnt = 0; int SysParameter::sampFrmCnt = 0; int SysParameter::sampFrmPixCnt = 0; double SysParameter::frmRefineRlossWt = 0; double SysParameter::frmRefineClossWt = 0; double SysParameter::blockAlpha = 0; double SysParameter::blockBeta = 0; double SysParameter::blockRlossWt = 0; double SysParameter::blockClossWt = 0; double SysParameter::blockSlossWt = 0; double SysParameter::blockTh = 0; double SysParameter::simplifyRlossWt = 0; double SysParameter::simplifyClossWt = 0; double SysParameter::simplifySlossWt = 0; double SysParameter::simplifyTh = 0;
28.952381
42
0.784539
Zhengjun-Du
0066bc0e3588ff1af61067c4f710fa505c4bb122
4,475
cpp
C++
src/examples/example3.cpp
mohistH/nanogui_from_dalerank
ae4b5e04b2d8e2e85ab63b737fd13f8882243526
[ "MIT" ]
2
2021-01-05T08:50:59.000Z
2021-08-17T09:09:55.000Z
src/examples/example3.cpp
mohistH/nanogui_from_dalerank
ae4b5e04b2d8e2e85ab63b737fd13f8882243526
[ "MIT" ]
null
null
null
src/examples/example3.cpp
mohistH/nanogui_from_dalerank
ae4b5e04b2d8e2e85ab63b737fd13f8882243526
[ "MIT" ]
1
2021-08-17T09:09:57.000Z
2021-08-17T09:09:57.000Z
/* src/example3.cpp -- C++ version of an example application that shows how to use nanogui in an application with an already created and managed glfw context. NanoGUI was developed by Wenzel Jakob <wenzel.jakob@epfl.ch>. The widget drawing code is based on the NanoVG demo application by Mikko Mononen. All rights reserved. Use of this source code is governed by a BSD-style license that can be found in the LICENSE.txt file. */ // GLFW // #if defined(NANOGUI_GLAD) #if defined(NANOGUI_SHARED) && !defined(GLAD_GLAPI_EXPORT) #define GLAD_GLAPI_EXPORT #endif #include <glad/glad.h> #else #if defined(__APPLE__) #define GLFW_INCLUDE_GLCOREARB #else #define GL_GLEXT_PROTOTYPES #endif #endif #include <nanogui/screen.h> #include <nanogui/window.h> #include <nanogui/layout.h> #include <nanogui/label.h> #include <nanogui/checkbox.h> #include <nanogui/dial.h> #include <nanogui/button.h> #include <nanogui/toolbutton.h> #include <nanogui/popupbutton.h> #include <nanogui/combobox.h> #include <nanogui/progressbar.h> #include <nanogui/entypo.h> #include <nanogui/meter.h> #include <nanogui/messagedialog.h> #include <nanogui/textbox.h> #include <nanogui/slider.h> #include <nanogui/imagepanel.h> #include <nanogui/imageview.h> #include <nanogui/vscrollpanel.h> #include <nanogui/colorwheel.h> #include <nanogui/colorpicker.h> #include <nanogui/table.h> #include <nanogui/graph.h> #include <nanogui/ledmatrix.h> #include <nanogui/tabwidget.h> #include <nanogui/switchbox.h> #include <nanogui/spinner.h> #include <nanogui/dropdownbox.h> #include <nanogui/editworkspace.h> #include <nanogui/editproperties.h> #include <nanogui/scrollbar.h> #include <nanogui/windowmenu.h> #include <nanogui/perfchart.h> #include <nanogui/common.h> #include <nanogui/listbox.h> #include <nanogui/themebuilder.h> #include <nanogui/tolerancebar.h> #include <nanogui/treeview.h> #include <nanogui/treeviewitem.h> #include <nanogui/picflow.h> #include <nanogui/textarea.h> #include <nanogui/searchbox.h> #include <nanogui/editproperties.h> #include <nanogui/formhelper.h> #include <iostream> using namespace nanogui; enum test_enum { Item1 = 0, Item2, Item3 }; bool bvar = true; int ivar = 12345678; double dvar = 3.1415926; float fvar = (float)dvar; std::string strval = "A string"; test_enum enumval = Item2; Color colval(0.5f, 0.5f, 0.7f, 1.f); int main(int /* argc */, char ** /* argv */) { nanogui::init(); Vector2i size{ 1600, 900 }; auto window = nanogui::sample::create_window(size.x(), size.y(), "Example Nanogui", true, false, true); nanogui::sample::create_context(); { // Create a nanogui screen and pass the glfw pointer to initialize Screen nscreen(size, "NanoGUI Test", false); nanogui::sample::setup_window_params(window, &nscreen); // Create nanogui gui bool enabled = true; FormHelper *gui = new FormHelper(&nscreen); ref<Window> nanoguiWindow = gui->addWindow({ 10, 10 }, "Form helper example"); gui->addGroup("Basic types"); gui->addVariable("bool", bvar)->setTooltip("Test tooltip."); gui->addVariable("string", strval); gui->addGroup("Validating fields"); gui->addVariable("int", ivar)->setSpinnable(true); gui->addVariable("float", fvar)->setTooltip("Test."); gui->addVariable("double", dvar)->setSpinnable(true); gui->addGroup("Complex types"); gui->addVariable("Enumeration", enumval, enabled)->setItems({ "Item 1", "Item 2", "Item 3" }); gui->addVariable("Color", colval) ->setFinalCallback([](const Color &c) { std::cout << "ColorPicker Final Callback: [" << c.r() << ", " << c.g() << ", " << c.b() << ", " << c.w() << "]" << std::endl; }); gui->addGroup("Other widgets"); gui->addButton("A button", []() { std::cout << "Button pressed." << std::endl; })->setTooltip("Testing a much longer tooltip, that will wrap around to new lines multiple times.");; nscreen.setVisible(true); nscreen.performLayout(); nscreen.drawAll(); nanogui::sample::run([&] { nanogui::sample::clear_frame(nscreen.background()); nscreen.drawAll(); nanogui::sample::present_frame(window); /* Wait for mouse/keyboard or empty refresh events */ nanogui::sample::wait_events(); }); nanogui::sample::poll_events(); } nanogui::sample::destroy_window(window); nanogui::shutdown(); return 0; }
28.503185
184
0.679777
mohistH
006a814318fbd236ff070c9008cd1307032ee45f
925
cpp
C++
message/pong.cpp
kagamikarasu/shaula
cbda881578669cbf407845e46a9a9f988a155aba
[ "MIT" ]
null
null
null
message/pong.cpp
kagamikarasu/shaula
cbda881578669cbf407845e46a9a9f988a155aba
[ "MIT" ]
13
2021-08-09T10:25:28.000Z
2021-08-12T07:39:05.000Z
message/pong.cpp
kagamikarasu/shaula
cbda881578669cbf407845e46a9a9f988a155aba
[ "MIT" ]
null
null
null
// // Pong.cpp // // Copyright (c) 2021 Yuya Takeda (@kagamikarasu) // // MIT LICENSE // See the following LICENSE file // https://github.com/kagamikarasu/shaula/ // #include "pong.h" Pong::Pong(const std::vector<unsigned char> &bytes) { setCommand(CommandDef.PONG); setNonce(bytes); } void Pong::setNonce(const std::vector<unsigned char> &bytes) { nonce_ = bytes; } std::vector<unsigned char> Pong::getMessage() { std::vector<unsigned char> payload; payload.insert(payload.end(), nonce_.begin(), nonce_.end()); Message::setPayload(payload); return Message::getMessage(); } void Pong::send( boost::asio::ip::tcp::socket &socket, const boost::asio::yield_context &yield, LastSend& last_send, const std::vector<unsigned char> &bytes) { auto v = std::make_unique<Pong>(bytes); v->sendMessage(socket, yield); last_send.setHeader(v->getHeader()); }
22.02381
64
0.656216
kagamikarasu
00747ce507529b2e7d651ff78e9dfd8888a8270d
17,305
cpp
C++
Sources/Elastos/Frameworks/Droid/WebView/Chromium/src/elastos/droid/webview/chromium/native/content/browser/ResourceExtractor.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
7
2017-07-13T10:34:54.000Z
2021-04-16T05:40:35.000Z
Sources/Elastos/Frameworks/Droid/WebView/Chromium/src/elastos/droid/webview/chromium/native/content/browser/ResourceExtractor.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
null
null
null
Sources/Elastos/Frameworks/Droid/WebView/Chromium/src/elastos/droid/webview/chromium/native/content/browser/ResourceExtractor.cpp
jingcao80/Elastos
d0f39852356bdaf3a1234743b86364493a0441bc
[ "Apache-2.0" ]
9
2017-07-13T12:33:20.000Z
2021-06-19T02:46:48.000Z
//========================================================================= // Copyright (C) 2012 The Elastos Open Source Project // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //========================================================================= #include "Elastos.CoreLibrary.Utility.h" #include "Elastos.Droid.Content.h" #include "Elastos.Droid.Preference.h" #include "elastos/droid/webkit/webview/chromium/native/content/browser/ResourceExtractor.h" #include "elastos/droid/webkit/webview/chromium/native/ui/base/LocalizationUtils.h" #include "elastos/droid/webkit/webview/chromium/native/base/PathUtils.h" #include <elastos/core/StringUtils.h> #include "elastos/core/StringBuilder.h" #include "elastos/core/CoreUtils.h" #include <elastos/utility/logging/Slogger.h> #include <elastos/utility/logging/Logger.h> using Elastos::Droid::Content::Res::IResources; using Elastos::Droid::Content::ISharedPreferences; using Elastos::Droid::Content::ISharedPreferencesEditor; using Elastos::Droid::Preference::CPreferenceManagerHelper; using Elastos::Droid::Preference::IPreferenceManagerHelper; using Elastos::Droid::Webkit::Webview::Chromium::Ui::Base::LocalizationUtils; using Elastos::Droid::Webkit::Webview::Chromium::Base::PathUtils; using Elastos::Core::StringBuilder; using Elastos::Core::StringUtils; using Elastos::Core::CoreUtils; using Elastos::IO::EIID_IFilenameFilter; using Elastos::IO::CFile; using Elastos::IO::IInputStream; using Elastos::IO::IOutputStream; using Elastos::IO::IFlushable; using Elastos::IO::CFileOutputStream; using Elastos::Utility::ISet; using Elastos::Utility::IIterator; using Elastos::Utility::CHashSet; using Elastos::Utility::Regex::IPattern; using Elastos::Utility::Regex::IPatternHelper; using Elastos::Utility::Regex::IMatcher; using Elastos::Utility::Regex::CPatternHelper; using Elastos::Utility::Logging::Slogger; using Elastos::Utility::Logging::Logger; namespace Elastos { namespace Droid { namespace Webkit { namespace Webview { namespace Chromium { namespace Content { namespace Browser { //===================================================================== // ResourceExtractor::InnerFilenameFilter //===================================================================== ResourceExtractor::InnerFilenameFilter::InnerFilenameFilter( /* [in] */ const String& timestamp) : TIMESTAMP_PREFIX(timestamp) { } CAR_INTERFACE_IMPL(ResourceExtractor::InnerFilenameFilter, Object, IFilenameFilter); ECode ResourceExtractor::InnerFilenameFilter::Accept( /* [in] */ IFile* dir, /* [in] */ const String& name, /* [out] */ Boolean* result) { VALIDATE_NOT_NULL(result); *result = name.StartWith(TIMESTAMP_PREFIX); return NOERROR; } //===================================================================== // ResourceExtractor::ExtractTask //===================================================================== const Int32 ResourceExtractor::ExtractTask::BUFFER_SIZE; ResourceExtractor::ExtractTask::ExtractTask( /* [in] */ ResourceExtractor* owner) : mOwner(owner) { } ECode ResourceExtractor::ExtractTask::DoInBackground( /* [in] */ ArrayOf<IInterface*>* params, /* [out] */ IInterface** result) { VALIDATE_NOT_NULL(result); AutoPtr<IFile> outputDir = mOwner->GetOutputDir(); Boolean bExists, bMkdirs; if (!(outputDir->Exists(&bExists), bExists) && !(outputDir->Mkdirs(&bMkdirs), bMkdirs)) { Slogger::E(LOGTAG, "Unable to create pak resources directory!"); *result = NULL; return NOERROR; } String timestampFile = CheckPakTimestamp(outputDir); if (timestampFile != NULL) { mOwner->DeleteFiles(); } AutoPtr<IPreferenceManagerHelper> helper; CPreferenceManagerHelper::AcquireSingleton((IPreferenceManagerHelper**)&helper); AutoPtr<ISharedPreferences> prefs; helper->GetDefaultSharedPreferences(mOwner->mContext, (ISharedPreferences**)&prefs); // HashSet<String> filenames = (HashSet<String>) prefs.getStringSet( // PAK_FILENAMES, new HashSet<String>()); AutoPtr<ISet> defValue; CHashSet::New((ISet**)&defValue); AutoPtr<ISet> filenames; prefs->GetStringSet(PAK_FILENAMES, defValue, (ISet**)&filenames); String currentLocale = LocalizationUtils::GetDefaultLocale(); AutoPtr<ArrayOf<String> > array; StringUtils::Split(currentLocale, "-", 2, (ArrayOf<String>**)&array); String currentLanguage = (*array)[0]; String value; prefs->GetString(LAST_LANGUAGE, String(""), &value); Int32 filenamesSize; filenames->GetSize(&filenamesSize); if (value.Equals(currentLanguage) && filenamesSize >= sMandatoryPaks->GetLength()) { Boolean filesPresent = TRUE; AutoPtr<IIterator> keyIter; filenames->GetIterator((IIterator**)&keyIter); Boolean isflag = FALSE; while ((keyIter->HasNext(&isflag), isflag)) { AutoPtr<IInterface> obj; keyIter->GetNext((IInterface**)&obj); ICharSequence* cs = ICharSequence::Probe(obj); String file; cs->ToString(&file); AutoPtr<IFile> f; CFile::New(outputDir, file, (IFile**)&f); Boolean isExist; if (!(f->Exists(&isExist), isExist)) { filesPresent = FALSE; break; } } if (filesPresent) { *result = NULL; return NOERROR; } } else { AutoPtr<ISharedPreferencesEditor> spe; prefs->Edit((ISharedPreferencesEditor**)&spe); spe->PutString(LAST_LANGUAGE, currentLanguage); spe->Apply(); } AutoPtr<StringBuilder> p = new StringBuilder(); for(Int32 i = 0; i < sMandatoryPaks->GetLength(); ++i) { String mandatoryPak = (*sMandatoryPaks)[i]; Int32 len; p->GetLength(&len); if (len > 0) p->AppendChar('|'); p->Append("\\Q"); p->Append(mandatoryPak); p->Append("\\E"); } if (sExtractImplicitLocalePak) { Int32 len; p->GetLength(&len); if (len > 0) p->AppendChar('|'); // As well as the minimum required set of .paks above, we'll also add all .paks that // we have for the user's currently selected language. p->Append(currentLanguage); p->Append("(-\\w+)?\\.pak"); } AutoPtr<IPatternHelper> pHelper; CPatternHelper::AcquireSingleton((IPatternHelper**)&pHelper); AutoPtr<IPattern> paksToInstall; pHelper->Compile(p->ToString(), (IPattern**)&paksToInstall); AutoPtr<IResources> resources; mOwner->mContext->GetResources((IResources**)&resources); AutoPtr<IAssetManager> manager; resources->GetAssets((IAssetManager**)&manager); // try { // Loop through every asset file that we have in the APK, and look for the // ones that we need to extract by trying to match the Patterns that we // created above. //byte[] buffer = null; AutoPtr<ArrayOf<Byte> > buffer; AutoPtr<ArrayOf<String> > files; manager->List(String(""), (ArrayOf<String>**)&files); //for (String file : files) for (Int32 i = 0; i < files->GetLength(); ++i) { String file = (*files)[i]; AutoPtr<IMatcher> matcher; paksToInstall->Matcher(file, (IMatcher**)&matcher); Boolean matched = FALSE; if (!matcher->Matches(&matched)) { continue; } Boolean isICUData = file.Equals(ICU_DATA_FILENAME); AutoPtr<IFile> output; CFile::New(isICUData ? mOwner->GetAppDataDir() : outputDir, file, (IFile**)&output); Boolean exists; if (output->Exists(&exists), exists) { continue; } AutoPtr<IInputStream> is; AutoPtr<IOutputStream> os; //try { manager->Open(file, (IInputStream**)&is); CFileOutputStream::New(output, (IOutputStream**)&os); Logger::I(LOGTAG, "Extracting resource %s", file.string()); if (buffer == NULL) { //buffer = new byte[BUFFER_SIZE]; buffer = ArrayOf<Byte>::Alloc(BUFFER_SIZE); } Int32 count = 0; while ((is->Read(buffer, 0, BUFFER_SIZE, &count), count) != -1) { os->Write(buffer, 0, count); } IFlushable::Probe(os)->Flush(); // Ensure something reasonable was written. Int64 outputLength; output->GetLength(&outputLength); if (outputLength == 0) { //throw new IOException(file + " extracted with 0 length!"); Logger::E(LOGTAG, "%s extracted with 0 length", file.string()); } if (!isICUData) { filenames->Add(TO_IINTERFACE(CoreUtils::Convert(file))); } else { // icudata needs to be accessed by a renderer process. Boolean res; output->SetReadable(TRUE, FALSE, &res); } //} finally { // try { if (is != NULL) { is->Close(); } // } finally { if (os != NULL) { os->Close(); } // } //} } //} catch (IOException e) { // // TODO(benm): See crbug/152413. // // Try to recover here, can we try again after deleting files instead of // // returning null? It might be useful to gather UMA here too to track if // // this happens with regularity. // Log.w(LOGTAG, "Exception unpacking required pak resources: " + e.getMessage()); // deleteFiles(); // return null; // } // Finished, write out a timestamp file if we need to. if (timestampFile != NULL) { //try { AutoPtr<IFile> file; CFile::New(outputDir, timestampFile, (IFile**)&file); Boolean res; file->CreateNewFile(&res); //} catch (IOException e) { // Worst case we don't write a timestamp, so we'll re-extract the resource // paks next start up. // Log.w(LOGTAG, "Failed to write resource pak timestamp!"); //} } // TODO(yusufo): Figure out why remove is required here. AutoPtr<ISharedPreferencesEditor> spe; prefs->Edit((ISharedPreferencesEditor**)&spe); spe->Remove(PAK_FILENAMES); spe->Apply(); spe->PutStringSet(PAK_FILENAMES, filenames); spe->Apply(); *result = NULL; return NOERROR; } String ResourceExtractor::ExtractTask::CheckPakTimestamp( /* [in] */ IFile* outputDir) { const String TIMESTAMP_PREFIX("pak_timestamp-"); AutoPtr<IPackageManager> pm; mOwner->mContext->GetPackageManager((IPackageManager**)&pm); AutoPtr<IPackageInfo> pi; // try { String packageName; mOwner->mContext->GetPackageName(&packageName); pm->GetPackageInfo(packageName, 0, (IPackageInfo**)&pi); // } catch (PackageManager.NameNotFoundException e) { // return TIMESTAMP_PREFIX; // } if (pi == NULL) { return TIMESTAMP_PREFIX; } String expectedTimestamp(TIMESTAMP_PREFIX); Int32 versionCode; pi->GetVersionCode(&versionCode); String versionCodeStr = StringUtils::ToString(versionCode); Int64 lastUpdateTime; pi->GetLastUpdateTime(&lastUpdateTime); expectedTimestamp += StringUtils::ToString(versionCode); expectedTimestamp += "-"; expectedTimestamp += StringUtils::ToString(lastUpdateTime); AutoPtr<IFilenameFilter> filenameFilter = new InnerFilenameFilter(TIMESTAMP_PREFIX); AutoPtr< ArrayOf<String> > timestamps; outputDir->List(filenameFilter, (ArrayOf<String>**)&timestamps); if (timestamps->GetLength() != 1) { // If there's no timestamp, nuke to be safe as we can't tell the age of the files. // If there's multiple timestamps, something's gone wrong so nuke. return expectedTimestamp; } if (!expectedTimestamp.Equals((*timestamps)[0])) { return expectedTimestamp; } // timestamp file is already up-to date. return String(NULL); } //===================================================================== // ResourceExtractor //===================================================================== const String ResourceExtractor::LOGTAG("ResourceExtractor"); const String ResourceExtractor::LAST_LANGUAGE("Last language"); const String ResourceExtractor::PAK_FILENAMES("Pak filenames"); const String ResourceExtractor::ICU_DATA_FILENAME("icudtl.dat"); AutoPtr< ArrayOf<String> > ResourceExtractor::sMandatoryPaks = NULL; Boolean ResourceExtractor::sExtractImplicitLocalePak = TRUE; AutoPtr<ResourceExtractor> ResourceExtractor::sInstance; AutoPtr<ResourceExtractor> ResourceExtractor::Get( /* [in] */ IContext* context) { if (sInstance == NULL) { sInstance = new ResourceExtractor(context); } return sInstance; } ECode ResourceExtractor::SetMandatoryPaksToExtract( /* [in] */ ArrayOf<String>* mandatoryPaks) { assert (sInstance == NULL || sInstance->mExtractTask == NULL); // : "Must be called before startExtractingResources is called"; sMandatoryPaks = mandatoryPaks; return NOERROR; } ECode ResourceExtractor::SetExtractImplicitLocaleForTesting( /* [in] */ Boolean extract) { assert (sInstance == NULL || sInstance->mExtractTask == NULL); // : "Must be called before startExtractingResources is called"; sExtractImplicitLocalePak = extract; return NOERROR; } ECode ResourceExtractor::WaitForCompletion() { if (ShouldSkipPakExtraction()) { return NOERROR; } assert(mExtractTask != NULL); // try { AutoPtr<IInterface> task; mExtractTask->Get((IInterface**)&task); // } catch (CancellationException e) { // // Don't leave the files in an inconsistent state. // deleteFiles(); // } catch (ExecutionException e2) { // deleteFiles(); // } catch (InterruptedException e3) { // deleteFiles(); // } return NOERROR; } ECode ResourceExtractor::StartExtractingResources() { if (mExtractTask != NULL) { return NOERROR; } if (ShouldSkipPakExtraction()) { return NOERROR; } mExtractTask = new ExtractTask(this); mExtractTask->ExecuteOnExecutor(AsyncTask::THREAD_POOL_EXECUTOR, NULL); return NOERROR; } ResourceExtractor::ResourceExtractor( /* [in] */ IContext* context) { context->GetApplicationContext((IContext**)&mContext); } AutoPtr<IFile> ResourceExtractor::GetAppDataDir() { AutoPtr<IFile> file; CFile::New(PathUtils::GetDataDirectory(mContext), (IFile**)&file); return file; } AutoPtr<IFile> ResourceExtractor::GetOutputDir() { AutoPtr<IFile> file; CFile::New(GetAppDataDir(), String("paks"), (IFile**)&file); return file; } ECode ResourceExtractor::DeleteFiles() { AutoPtr<IFile> icudata; CFile::New(GetAppDataDir(), ICU_DATA_FILENAME, (IFile**)&icudata); Boolean bExists, bDelete; if ((icudata->Exists(&bExists), bExists) && !(icudata->Delete(&bDelete), bDelete)) { String log("Unable to remove the icudata "); String name; icudata->GetName(&name); log += name; Slogger::E(LOGTAG, name); } AutoPtr<IFile> dir = GetOutputDir(); Boolean dirExists; dir->Exists(&dirExists); if (dirExists) { AutoPtr< ArrayOf<IFile*> > files; dir->ListFiles((ArrayOf<IFile*>**)&files); Int32 length = files->GetLength(); for (Int32 i = 0; i < length; i++) { AutoPtr<IFile> file = (*files)[i]; Boolean bFlag; file->Delete(&bFlag); if (!bFlag) { String log("Unable to remove existing resource "); String name; file->GetName(&name); log += name; Slogger::E(LOGTAG, log); } } } return NOERROR; } Boolean ResourceExtractor::ShouldSkipPakExtraction() { // Must call setMandatoryPaksToExtract before beginning resource extraction. assert(sMandatoryPaks != NULL); return sMandatoryPaks->GetLength() == 1 && (*sMandatoryPaks)[0].Equals(""); } } // namespace Browser } // namespace Content } // namespace Chromium } // namespace Webview } // namespace Webkit } // namespace Droid } // namespace Elastos
34.335317
97
0.604218
jingcao80
00754970455083e104426ced7bf1b2fac402f804
28,311
cpp
C++
app/benchmark.cpp
Hespian/EdgeHierarchies
b30a226d54df662a0dc635720a7000b867f96bc9
[ "MIT" ]
13
2019-08-22T19:43:21.000Z
2021-12-17T06:54:00.000Z
app/benchmark.cpp
Hespian/EdgeHierarchies
b30a226d54df662a0dc635720a7000b867f96bc9
[ "MIT" ]
null
null
null
app/benchmark.cpp
Hespian/EdgeHierarchies
b30a226d54df662a0dc635720a7000b867f96bc9
[ "MIT" ]
1
2019-08-26T07:45:11.000Z
2019-08-26T07:45:11.000Z
/******************************************************************************* * app/benchmark.cpp * * Copyright (C) 2019 Demian Hespe <hespe@kit.edu> * * All rights reserved. ******************************************************************************/ #include <string> #include <iostream> #include <chrono> #include <unistd.h> #include <cstdlib> #include <random> #include <fstream> #include <pthread.h> #include <tlx/cmdline_parser.hpp> #include <routingkit/contraction_hierarchy.h> #include <routingkit/vector_io.h> #include <routingkit/dijkstra.h> #include <routingkit/inverse_vector.h> #include <papi.hpp> #include "definitions.h" #include "edgeHierarchyGraph.h" #include "edgeHierarchyQuery.h" #include "edgeHierarchyGraphQueryOnly.h" #include "edgeHierarchyQueryOnly.h" #include "edgeHierarchyQueryOnlyNoTimestamp.h" #include "edgeHierarchyConstruction.h" #include "dimacsGraphReader.h" #include "edgeHierarchyWriter.h" #include "edgeHierarchyReader.h" #include "edgeRanking/shortcutCountingRoundsEdgeRanker.h" #include "edgeRanking/shortcutCountingSortingRoundsEdgeRanker.h" #include "edgeRanking/levelShortcutsHopsEdgeRanker.h" void pin_to_core(size_t core) { cpu_set_t cpuset; CPU_ZERO(&cpuset); CPU_SET(core, &cpuset); pthread_setaffinity_np(pthread_self(), sizeof(cpu_set_t), &cpuset); } bool fileExists (const std::string& name) { ifstream f(name.c_str()); return f.good(); } RoutingKit::ContractionHierarchy getCHFromGraph(EdgeHierarchyGraph &g) { std::vector<unsigned> tails, heads, weights; g.forAllNodes([&] (NODE_T tail) { g.forAllNeighborsOut(tail, [&] (NODE_T head, EDGEWEIGHT_T weight) { tails.push_back(tail); heads.push_back(head); weights.push_back(weight); }); }); return RoutingKit::ContractionHierarchy::build( g.getNumberOfNodes(), tails, heads, weights ); } template<class EdgeRanker> void buildAndWriteEdgeHierarchy(EdgeHierarchyGraph &g, std::string edgeHierarchyFilename) { EdgeHierarchyQuery query(g); EdgeHierarchyConstruction<EdgeRanker> construction(g, query); auto start = chrono::steady_clock::now(); construction.run(); auto end = chrono::steady_clock::now(); cout << "EH Construction took " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms" << endl; cout << "Distance in Query graph was equal to removed path " << numEquals << " times" <<endl; cout << "Writing Edge Hierarchy to " << edgeHierarchyFilename <<endl; start = chrono::steady_clock::now(); writeEdgeHierarchy(edgeHierarchyFilename, g); end = chrono::steady_clock::now(); cout << "Writing EH took " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms" << endl; } #define INVALID_QUERY_DATA std::numeric_limits<unsigned>::max() struct DijkstraRankRunningtime { unsigned source; unsigned target; unsigned rank; unsigned distance; int timeEH; int verticesSettledEH; int edgesRelaxedEH; int timeCH; int verticesSettledCH; int edgesRelaxedCH; }; std::vector<DijkstraRankRunningtime> GenerateDijkstraRankQueries(unsigned numSourceNodes, int seed, EdgeHierarchyGraph &g) { std::default_random_engine gen(seed); std::uniform_int_distribution<int> dist(0, g.getNumberOfNodes()-1); std::vector<unsigned> tails, heads, weights, first_out; g.forAllNodes([&] (NODE_T tail) { first_out.push_back(tails.size()); g.forAllNeighborsOut(tail, [&] (NODE_T head, EDGEWEIGHT_T weight) { tails.push_back(tail); heads.push_back(head); weights.push_back(weight); }); }); RoutingKit::Dijkstra dij(first_out, tails, heads); std::vector<DijkstraRankRunningtime> result; for(unsigned i=0; i<numSourceNodes; ++i){ unsigned source_node = dist(gen); unsigned r = 0; unsigned n = 0; dij.reset().add_source(source_node); while(!dij.is_finished()){ auto x = dij.settle(RoutingKit::ScalarGetWeight(weights)); ++n; if(n == (1u << r)){ if(r > 5){ result.push_back({source_node, x.node, r, x.distance, -1, -1, -1, -1}); } ++r; } } } return result; } std::vector<DijkstraRankRunningtime> GenerateRandomQueries(unsigned numQueries, int seed, EdgeHierarchyGraph &g) { std::default_random_engine gen(seed); std::uniform_int_distribution<int> dist(0, g.getNumberOfNodes()-1); std::vector<DijkstraRankRunningtime> result; for(unsigned i=0; i<numQueries; ++i){ unsigned source_node = dist(gen); unsigned target_node = dist(gen); result.push_back({source_node, target_node, INVALID_QUERY_DATA, INVALID_QUERY_DATA, -1, -1, -1, -1}); } return result; } template<bool partialStalling, bool EHForwardStalling, bool EHBackwardStalling, bool CHStallOnDemand, bool minimalSearchSpace, template<bool, bool, bool, bool> class QueryType> int benchmark(bool dijkstraRank, bool test, EdgeHierarchyGraphQueryOnly &ehGraph, RoutingKit::ContractionHierarchyQuery &chQuery, std::vector<DijkstraRankRunningtime> &queries, int stallingPercent) { QueryType<EHForwardStalling, EHBackwardStalling, partialStalling, minimalSearchSpace> newQuery = QueryType<EHForwardStalling, EHBackwardStalling, partialStalling, minimalSearchSpace>(ehGraph); // newQuery.avgSearchSpace = 626; // EdgeHierarchyQueryOnly<EHForwardStalling, EHBackwardStalling, minimalSearchSpace> newQuery = EdgeHierarchyQueryOnly<EHForwardStalling, EHBackwardStalling, minimalSearchSpace>(ehGraph); // std::cout << "Running benchmark" << std::endl; // std::cout << "EHForwardStalling: " << EHForwardStalling << std::endl; // std::cout << "EHBackwardStalling: " << EHBackwardStalling << std::endl; // std::cout << "CHStallOnDemand: " << CHStallOnDemand << std::endl; // std::cout << "minimalSearchSpace: " << minimalSearchSpace << std::endl; // std::cout << "QueryType: " << typeid(newQuery).name() << std::endl; // std::cout << "dijkstraRank: " << dijkstraRank << std::endl; // std::cout << "test: " << test << std::endl; int numMistakes = 0; int numCorrect = 0; if(test) { for(auto &generatedQuery: queries) { NODE_T u = generatedQuery.source; NODE_T v = generatedQuery.target; EDGEWEIGHT_T distance = newQuery.getDistance(u, v, stallingPercent); chQuery.reset().add_source(u).add_target(v).run<CHStallOnDemand, minimalSearchSpace>(); auto chDistance = chQuery.get_distance(); if(generatedQuery.distance == INVALID_QUERY_DATA) { generatedQuery.distance = chDistance; } if(generatedQuery.distance != distance) { cout << "EH: Wrong distance for " << u << " and " << v << ": " << distance << " (should be " << generatedQuery.distance << ")" << endl; numMistakes++; } else { numCorrect++; } if(generatedQuery.distance != chDistance) { cout << "CH: Wrong distance for " << u << " and " << v << ": " << chDistance << " (should be " << generatedQuery.distance << ")" << endl; } else { } } cout << numMistakes << " out of " << queries.size() << " WRONG!!!" << endl; cout << numCorrect << " out of " << queries.size() << " CORRECT!" << endl; cout << "Done checking. Measuring time..." << endl; } int numVerticesSettledWithActualDistance = 0; newQuery.resetCounters(); auto cache_counter_eh = common::papi_cache(); auto start = chrono::steady_clock::now(); for(auto &generatedQuery: queries) { NODE_T u = generatedQuery.source; NODE_T v = generatedQuery.target; if(dijkstraRank) { newQuery.resetCounters(); } auto queryStart = chrono::high_resolution_clock::now(); EDGEWEIGHT_T distance = newQuery.getDistance(u, v, stallingPercent); (void) distance; auto queryEnd = chrono::high_resolution_clock::now(); if(dijkstraRank) { generatedQuery.timeEH = chrono::duration_cast<chrono::nanoseconds>(queryEnd - queryStart).count(); generatedQuery.verticesSettledEH = newQuery.numVerticesSettled; generatedQuery.edgesRelaxedEH = newQuery.numEdgesRelaxed + newQuery.numEdgesLookedAtForStalling; } if constexpr(minimalSearchSpace){ for(std::pair<NODE_T, EDGEWEIGHT_T> nodeDistancePair: newQuery.verticesSettledForward) { chQuery.reset().add_source(u).add_target(nodeDistancePair.first).run(); unsigned actualDistance = chQuery.get_distance(); if(actualDistance == nodeDistancePair.second) { ++numVerticesSettledWithActualDistance; } if(actualDistance > nodeDistancePair.second) { std::cout << "IMPOSSIBLE!!!" <<std::endl; } } for(std::pair<NODE_T, EDGEWEIGHT_T> nodeDistancePair: newQuery.verticesSettledBackward) { chQuery.reset().add_source(nodeDistancePair.first).add_target(v).run(); unsigned actualDistance = chQuery.get_distance(); if(actualDistance == nodeDistancePair.second) { ++numVerticesSettledWithActualDistance; } if(actualDistance > nodeDistancePair.second) { std::cout << "IMPOSSIBLE!!!" <<std::endl; } } } } cache_counter_eh.stop(); auto end = chrono::steady_clock::now(); std::cout << cache_counter_eh.result() << std::endl; if(!dijkstraRank) { cout << "Average query time (EH): " << chrono::duration_cast<chrono::microseconds>(end - start).count() / queries.size() << " us" << endl; if constexpr(minimalSearchSpace) { cout << "MINIMAL average number of vertices settled (EH): " << numVerticesSettledWithActualDistance/queries.size() << endl; } cout << "Average number of vertices settled (EH): " << newQuery.numVerticesSettled/queries.size() << endl; cout << "Average number of edges relaxed (EH): " << newQuery.numEdgesRelaxed/queries.size() << endl; cout << "Average number of edges looked at for stalling (EH): " << newQuery.numEdgesLookedAtForStalling/queries.size() << endl; } numVerticesSettledWithActualDistance = 0; chQuery.resetCounters(); start = chrono::steady_clock::now(); auto cache_counter_ch = common::papi_cache(); for(auto &generatedQuery: queries) { NODE_T u = generatedQuery.source; NODE_T v = generatedQuery.target; if(dijkstraRank) { chQuery.resetCounters(); } auto queryStart = chrono::high_resolution_clock::now(); chQuery.reset().add_source(u).add_target(v).run<CHStallOnDemand, minimalSearchSpace>(); auto chDistance = chQuery.get_distance(); (void) chDistance; auto queryEnd = chrono::high_resolution_clock::now(); if(dijkstraRank) { generatedQuery.timeCH = chrono::duration_cast<chrono::nanoseconds>(queryEnd - queryStart).count(); generatedQuery.verticesSettledCH = chQuery.getNumVerticesSettled(); generatedQuery.edgesRelaxedCH = chQuery.getNumEdgesRelaxed() + chQuery.getNumEdgesLookedAtForStalling(); } if constexpr(minimalSearchSpace){ auto verticesSettledForward = chQuery.getVerticesSettledForward(); auto verticesSettledBackward = chQuery.getVerticesSettledBackward(); for(const std::pair<unsigned, unsigned> &nodeDistancePair: verticesSettledForward) { unsigned actualDistance = newQuery.getDistance(u, nodeDistancePair. first, stallingPercent); if(actualDistance == nodeDistancePair.second) { ++numVerticesSettledWithActualDistance; } if(actualDistance > nodeDistancePair.second) { std::cout << "IMPOSSIBLE!!! Distance from " << u << " to " << nodeDistancePair.first << " is " << actualDistance << " but was settled at " << nodeDistancePair.second <<std::endl; } } for(const std::pair<unsigned, unsigned> &nodeDistancePair: verticesSettledBackward) { unsigned actualDistance = newQuery.getDistance(nodeDistancePair.first, v, stallingPercent); if(actualDistance == nodeDistancePair.second) { ++numVerticesSettledWithActualDistance; } if(actualDistance > nodeDistancePair.second) { std::cout << "IMPOSSIBLE!!! Distance from " << nodeDistancePair.first << " to " << v << " is " << actualDistance << " but was settled at " << nodeDistancePair.second <<std::endl; } } } } cache_counter_ch.stop(); end = chrono::steady_clock::now(); std::cout << cache_counter_ch.result() << std::endl; if(!dijkstraRank) { cout << "Average query time (CH): " << chrono::duration_cast<chrono::microseconds>(end - start).count() / queries.size() << " us" << endl; if constexpr(minimalSearchSpace) { cout << "MINIMAL average number of vertices settled (CH): " << numVerticesSettledWithActualDistance/queries.size() << endl; } chQuery.printCounters(queries.size()); } if(dijkstraRank) { std::cout << "Format: rank time vertices edges" << std::endl; for(auto &generatedQuery: queries) { unsigned rank = generatedQuery.rank; int timeEH = generatedQuery.timeEH; int numVerticesSettledEH = generatedQuery.verticesSettledEH; int numEdgesRelaxedEH = generatedQuery.edgesRelaxedEH; int timeCH = generatedQuery.timeCH; int numVerticesSettledCH = generatedQuery.verticesSettledCH; int numEdgesRelaxedCH = generatedQuery.edgesRelaxedCH; std::cout << "result EH: " << rank << " " << timeEH << " " << numVerticesSettledEH << " " << numEdgesRelaxedEH << std::endl; std::cout << "result CH: " << rank << " " << timeCH << " " << numVerticesSettledCH << " " << numEdgesRelaxedCH << std::endl; } } cache_counter_ch.result().compareTo(cache_counter_eh.result()); return numMistakes; } template<bool EHForwardStalling, bool EHBackwardStalling, bool CHStallOnDemand, bool minimalSearchSpace, template<bool, bool, bool, bool> class QueryType> int benchmark(bool dijkstraRank, bool test, EdgeHierarchyGraphQueryOnly &ehGraph, RoutingKit::ContractionHierarchyQuery &chQuery, std::vector<DijkstraRankRunningtime> &queries, int stallingPercent) { if(stallingPercent == -1) { return benchmark<false, EHForwardStalling, EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, QueryType>(dijkstraRank, test, ehGraph, chQuery, queries, stallingPercent); } else { return benchmark<true, EHForwardStalling, EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, QueryType>(dijkstraRank, test, ehGraph, chQuery, queries, stallingPercent); } } template<bool EHForwardStalling, bool EHBackwardStalling, bool CHStallOnDemand, bool minimalSearchSpace> int benchmark(bool dijkstraRank, bool test, bool noTimestamp, EdgeHierarchyGraphQueryOnly &ehGraph, RoutingKit::ContractionHierarchyQuery &chQuery, std::vector<DijkstraRankRunningtime> &queries, int stallingPercent) { if(noTimestamp) { return -1; // return benchmark<EHForwardStalling, EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, EdgeHierarchyQueryOnlyNoTimestamp>(dijkstraRank, test, ehGraph, chQuery, queries, stallingPercent); } else return benchmark<EHForwardStalling, EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, EdgeHierarchyQueryOnly>(dijkstraRank, test, ehGraph, chQuery, queries, stallingPercent); } template<bool EHForwardStalling, bool EHBackwardStalling, bool CHStallOnDemand> int benchmark(bool minimalSearchSpace, bool dijkstraRank, bool test, bool noTimestamp, EdgeHierarchyGraphQueryOnly &ehGraph, RoutingKit::ContractionHierarchyQuery &chQuery, std::vector<DijkstraRankRunningtime> &queries, int stallingPercent) { if(minimalSearchSpace) return benchmark<EHForwardStalling, EHBackwardStalling, CHStallOnDemand, true>(dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); else return benchmark<EHForwardStalling, EHBackwardStalling, CHStallOnDemand, false>(dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); } template<bool EHForwardStalling, bool EHBackwardStalling> int benchmark(bool CHStallOnDemand, bool minimalSearchSpace, bool dijkstraRank, bool test, bool noTimestamp, EdgeHierarchyGraphQueryOnly &ehGraph, RoutingKit::ContractionHierarchyQuery &chQuery, std::vector<DijkstraRankRunningtime> &queries, int stallingPercent) { if(CHStallOnDemand) return benchmark<EHForwardStalling, EHBackwardStalling, true>(minimalSearchSpace, dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); else return benchmark<EHForwardStalling, EHBackwardStalling, false>(minimalSearchSpace, dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); } template<bool EHForwardStalling> int benchmark(bool EHBackwardStalling, bool CHStallOnDemand, bool minimalSearchSpace, bool dijkstraRank, bool test, bool noTimestamp, EdgeHierarchyGraphQueryOnly &ehGraph, RoutingKit::ContractionHierarchyQuery &chQuery, std::vector<DijkstraRankRunningtime> &queries, int stallingPercent) { if(EHBackwardStalling) return benchmark<EHForwardStalling, true>(CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); else return benchmark<EHForwardStalling, false>(CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); } int benchmark(bool EHForwardStalling, bool EHBackwardStalling, bool CHStallOnDemand, bool minimalSearchSpace, bool dijkstraRank, bool test, bool noTimestamp, EdgeHierarchyGraphQueryOnly &ehGraph, RoutingKit::ContractionHierarchyQuery &chQuery, std::vector<DijkstraRankRunningtime> &queries, int stallingPercent) { if(EHForwardStalling) return benchmark<true>(EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); else return benchmark<false>(EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, ehGraph, chQuery, queries, stallingPercent); } int main(int argc, char* argv[]) { pin_to_core(0); tlx::CmdlineParser cp; cp.set_description("Benchmark program for EdgeHierarchies"); cp.set_author("Demian Hespe <hespe@kit.edu>"); unsigned numQueries = 1000; cp.add_unsigned('q', "queries", "N", numQueries, "Run N queries."); unsigned seed = 0; cp.add_unsigned('s', "seed", "N", seed, "The seed to use for the prng."); std::string filename; cp.add_param_string("filename", filename, "Filename of the graph to benchmark on"); bool addTurnCosts = false; cp.add_bool ('t', "turnCosts", addTurnCosts, "If this flag is set, turn costs are added to the input graph."); unsigned uTurnCost = 1000; cp.add_unsigned('u', "uTurnCost", uTurnCost, "Cost to be added for u-turns (only has effect when turn costs are activated)."); bool useCHForEHConstruction = false; cp.add_bool ("useCH", useCHForEHConstruction, "If this flag is set, CH queries will be used during EH construction"); bool DFSPreOrder = false; cp.add_bool ("DFSPreOrder", DFSPreOrder, "If this flag is set, DFS ordering will use pre order instead of post order"); bool CHOrder = false; cp.add_bool ("CHOrder", CHOrder, "If this flag is set, EHs will use the node ordering from CHs"); bool noTimestamp = false; cp.add_bool ("noTimestamp", noTimestamp, "If this flag is set, EH queries will not use timestamp flags but instead reset all distances set after each query"); bool dijkstraRank = false; cp.add_bool ('d', "dijkstraRank", dijkstraRank, "If this flag is set, queries are generated for dijkstra ranks of powers of two with numQueries source vertices."); bool EHForwardStalling = false; cp.add_bool ("EHForwardStalling", EHForwardStalling, "If this flag is set, Edge Hierarchy queries will use forward stalling"); int partialStallingPercent = -1; cp.add_int ("partialStallingPercent", partialStallingPercent, "Determines the fraction of incoming edges looked at for backward stalling in percent. Set -1 to disable partial stalling, -2 for scaling in increments of 10%. (default: -1)"); bool EHBackwardStalling = false; cp.add_bool ("EHBackwardStalling", EHBackwardStalling, "If this flag is set, Edge Hierarchy queries will use backward stalling"); bool CHNoStallOnDemand = false; cp.add_bool ("CHNoStallOnDemand", CHNoStallOnDemand, "If this flag is set, Contraction Hierarchy queries will NOT use stall on demand"); bool minimalSearchSpace = false; cp.add_bool ("minimalSearchSpace", minimalSearchSpace, "If this flag is set, the minimal search space will be calculated"); bool test = false; cp.add_bool ("test", test, "If this flag is set, correctness will be checked"); bool rebuild = false; cp.add_bool ("rebuild", rebuild, "If this flag is set, CH and EH are rebuilt"); // process command line if (!cp.process(argc, argv)) return -1; // some error occurred and help was always written to user. // output for debugging cp.print_result(); bool CHStallOnDemand = !CHNoStallOnDemand; shortcutHelperUseCH = useCHForEHConstruction; std::string edgeHierarchyFilename = filename; if(addTurnCosts) { edgeHierarchyFilename += "Turncosts" + std::to_string(uTurnCost); } edgeHierarchyFilename += "ShortcutCountingRoundsEdgeRanker"; if(useCHForEHConstruction) { edgeHierarchyFilename += "CHForConstruction"; } edgeHierarchyFilename += ".eh"; std::string contractionHierarchyFilename = filename; if(addTurnCosts) { contractionHierarchyFilename += "Turncosts" + std::to_string(uTurnCost); } contractionHierarchyFilename += ".ch"; EdgeHierarchyGraph g(0); std::vector<DijkstraRankRunningtime> queries; if(!rebuild && fileExists(edgeHierarchyFilename) && fileExists(contractionHierarchyFilename) && !dijkstraRank) { std::cout << "Skip reading graph file because both EH and CH are already on disk and dijkstraRank is deactivated" << std::endl; } else { auto start = chrono::steady_clock::now(); g = readGraphDimacs(filename); auto end = chrono::steady_clock::now(); cout << "Reading input graph took " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms" << endl; cout << "Input graph has " << g.getNumberOfNodes() << " vertices and " << g.getNumberOfEdges() << " edges" << endl; if(addTurnCosts){ start = chrono::steady_clock::now(); g = g.getTurnCostGraph(uTurnCost); end = chrono::steady_clock::now(); cout << "Adding turn costs took " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms" << endl; cout << "Turn cost graph has " << g.getNumberOfNodes() << " vertices and " << g.getNumberOfEdges() << " edges" << endl; } if(dijkstraRank) { queries = GenerateDijkstraRankQueries(numQueries, seed, g); } } RoutingKit::ContractionHierarchy ch; if(!rebuild && fileExists(contractionHierarchyFilename)) { std::cout << "Contraction Hierarchy already stored in file. Loading it..." << std::endl; ch = RoutingKit::ContractionHierarchy::load_file(contractionHierarchyFilename); } else { std::cout << "Building Contraction Hierarchy..." << std::endl; auto start = chrono::steady_clock::now(); ch = getCHFromGraph(g); auto end = chrono::steady_clock::now(); cout << "CH Construction took " << chrono::duration_cast<chrono::milliseconds>(end - start).count() << " ms" << endl; ch.save_file(contractionHierarchyFilename); } RoutingKit::ContractionHierarchyQuery chQuery(ch); cout << "CH has " << ch.forward.first_out.back() + ch.backward.first_out.back() << " edges" << endl; shortcutHelperChQuery = chQuery; if(!rebuild && fileExists(edgeHierarchyFilename)) { std::cout << "Edge Hierarchy already stored in file. Loading it..." << std::endl; g = readEdgeHierarchy(edgeHierarchyFilename); } else { std::cout << "Building Edge Hierarchy..." << std::endl; buildAndWriteEdgeHierarchy<ShortcutCountingRoundsEdgeRanker>(g, edgeHierarchyFilename); } g.sortEdges(); cout << "Edge hierarchy graph has " << g.getNumberOfNodes() << " vertices and " << g.getNumberOfEdges() << " edges" << endl; EdgeHierarchyGraphQueryOnly newG(0); if(CHOrder) { newG = g.getReorderedGraph<EdgeHierarchyGraphQueryOnly>(ch.rank); cout << "Reordered edge hierarchy graph has " << newG.getNumberOfNodes() << " vertices and " << newG.getNumberOfEdges() << " edges" << endl; } else{ if(DFSPreOrder) { newG = g.getDFSOrderGraph<EdgeHierarchyGraphQueryOnly, true>(); } else { newG = g.getDFSOrderGraph<EdgeHierarchyGraphQueryOnly, false>(); } cout << "DFS ordered edge hierarchy graph has " << newG.getNumberOfNodes() << " vertices and " << newG.getNumberOfEdges() << " edges" << endl; } newG.makeConsecutive(); if(!dijkstraRank) { queries = GenerateRandomQueries(numQueries, seed, g); } if(EHBackwardStalling && partialStallingPercent == -2) { std::cout << "----------------------------------------" << std::endl; std::cout << "No backward stalling" << std::endl; benchmark(EHForwardStalling, false, CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, newG, chQuery, queries, -1); for(float i = 0; i <= 100; i += 10) { std::cout << "----------------------------------------" << std::endl; std::cout << "Stalling " << i << "%" << std::endl; benchmark(EHForwardStalling, EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, newG, chQuery, queries, i); } std::cout << "----------------------------------------" << std::endl; std::cout << "Full backward stalling (not partial)" << std::endl; benchmark(EHForwardStalling, true, CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, newG, chQuery, queries, -1); } else { benchmark(EHForwardStalling, EHBackwardStalling, CHStallOnDemand, minimalSearchSpace, dijkstraRank, test, noTimestamp, newG, chQuery, queries, partialStallingPercent); } return 0; }
44.029549
313
0.645014
Hespian
0075720f22d3e68212c06e73df62b3cd9ae10eac
3,104
cpp
C++
source/Ch19/chapter/vector010_2.cpp
Fantasztikus21/UDProg-Introduction
3828bf41bdfa483decd27aa1a9ab62b5d2633245
[ "CC0-1.0" ]
3
2021-11-02T08:30:53.000Z
2022-02-28T07:32:25.000Z
source/Ch19/chapter/vector010_2.cpp
Fantasztikus21/UDProg-Introduction
3828bf41bdfa483decd27aa1a9ab62b5d2633245
[ "CC0-1.0" ]
1
2020-11-10T15:58:17.000Z
2020-11-10T15:58:17.000Z
source/Ch19/chapter/vector010_2.cpp
Fantasztikus21/UDProg-Introduction
3828bf41bdfa483decd27aa1a9ab62b5d2633245
[ "CC0-1.0" ]
122
2020-09-12T08:29:45.000Z
2022-03-04T10:22:46.000Z
#include "../std_lib_facilities.h" class My_out_of_range{}; class My_vector { int sz; double* elem; int space; void debug(const string& s) { cerr << this << "->" << s << "; elem ptr: " << elem << '\n'; } public: My_vector(): sz{0}, elem{nullptr}, space{0} {} explicit My_vector(int s): sz{s}, elem{new double[s]}, space{s} { for(int i = 0; i < sz; ++i) elem[i] = 0; //debug("(int s) constructor"); } My_vector(initializer_list<double> lst): sz{lst.size()}, elem{new double[sz]}, space{sz} { copy(lst.begin(), lst.end(), elem); //debug("(initializer_list<double> lst) constructor"); } My_vector(const My_vector& arg): sz{arg.sz}, elem{new double[arg.sz]}, space{arg.sz} { copy(arg.elem, arg.elem + arg.sz, elem); //debug("copy constructor"); } My_vector& operator=(const My_vector& arg) { if(this==&arg) return *this; if(arg.sz <= space) { for(int i = 0; i < arg.sz; ++i) elem[i] = arg.elem[i]; sz = arg.sz; return *this; } double* p = new double[arg.sz]; copy(arg.elem, arg.elem + arg.sz, p); delete[] elem; space = arg.sz; sz = arg.sz; elem = p; //debug("copy assigment"); return *this; } My_vector(My_vector&& arg): sz{arg.sz}, elem{arg.elem}, space{arg.space} { arg.sz = 0; arg.space = 0; arg.elem = nullptr; //debug("move constructor"); } My_vector& operator=(My_vector&& arg) { delete[] elem; elem = arg.elem; sz = arg.sz; space = arg.space; arg.elem = nullptr; arg.sz = 0; arg.space = 0; //debug("move assigment"); return *this; } ~My_vector() { //debug("destructor"); delete[] elem; } double& operator[](int n) { return elem[n]; } double operator[](int n) const { return elem[n]; } //double get(int n) const { return elem[n]; } //void set(int n, double d) { elem[n] = d; } int size() const { return sz; } int capacity() const { return space; } void reserve(int newalloc) { if(newalloc <= space) return; double* p = new double[newalloc]; for(int i = 0; i < sz; ++i) p[i] = elem[i]; delete[] elem; elem = p; space = newalloc; } void resize(int newsize) { reserve(newsize); for(int i = sz; i < newsize; ++i) elem[i] = 0; sz = newsize; } void push_back(double d) { if(sz == 0) reserve(8); else if(sz == space) reserve(2 * space); elem[sz] = d; ++sz; } double& at(int n) { if(n < 0 || sz <= n) throw My_out_of_range{}; return elem[n]; } double at(int n) const { if(n < 0 || sz <= n) throw My_out_of_range{}; return elem[n]; } }; My_vector* some_fct() { My_vector* myvec = new My_vector(10); // fill vector return myvec; } My_vector fill() { My_vector res = {12.2, 13.3, 14.4}; return res; } int main() try { My_vector v1; cout << "\tsize: " << v1.size() << ' '; cout << "\tspace: " << v1.capacity() << '\n'; for(int i = 0; i < 9; ++i) { v1.push_back(i); cout << v1.at(i) << ' '; cout << "\tsize: " << v1.size() << ' '; cout << "\tspace: " << v1.capacity() << '\n'; } cout << v1.at(-1) << '\n'; return 0; } catch (My_out_of_range) { cerr << "Out of range!\n"; return 1; }
18.046512
73
0.568621
Fantasztikus21
00771a0edf7f2b444cfecaf17d1fb5f72d3d02e4
1,299
cpp
C++
test/math/box/structure_cast.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
test/math/box/structure_cast.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
test/math/box/structure_cast.cpp
vinzenz/fcppt
3f8cc5babdee178a9bbd06ca3ce7ad405d19aa6a
[ "BSL-1.0" ]
null
null
null
// Copyright Carl Philipp Reh 2009 - 2016. // 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 <fcppt/cast/float_to_int_fun.hpp> #include <fcppt/math/box/comparison.hpp> #include <fcppt/math/box/object_impl.hpp> #include <fcppt/math/box/output.hpp> #include <fcppt/math/box/structure_cast.hpp> #include <fcppt/preprocessor/disable_gcc_warning.hpp> #include <fcppt/preprocessor/pop_warning.hpp> #include <fcppt/preprocessor/push_warning.hpp> #include <fcppt/config/external_begin.hpp> #include <boost/test/unit_test.hpp> #include <fcppt/config/external_end.hpp> FCPPT_PP_PUSH_WARNING FCPPT_PP_DISABLE_GCC_WARNING(-Weffc++) BOOST_AUTO_TEST_CASE( math_box_structure_cast ) { FCPPT_PP_POP_WARNING typedef fcppt::math::box::object< float, 2 > box_f2; typedef fcppt::math::box::object< int, 2 > box_i2; box_f2 const box1( box_f2::vector( 1.5f, 2.5f ), box_f2::dim( 3.5f, 4.5f ) ); box_i2 const result( fcppt::math::box::structure_cast< box_i2, fcppt::cast::float_to_int_fun >( box1 ) ); BOOST_CHECK_EQUAL( result, box_i2( box_i2::vector( 1, 2 ), box_i2::dim( 3, 4 ) ) ); }
17.794521
61
0.69361
vinzenz
007955cba67a1c50ff800e34c72270db51b5487e
714
hpp
C++
Spades Game/Game/UI/CollapsibleButton.hpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
6
2017-01-04T22:40:50.000Z
2019-11-24T15:37:46.000Z
Spades Game/Game/UI/CollapsibleButton.hpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
1
2016-09-18T19:10:01.000Z
2017-08-04T23:53:38.000Z
Spades Game/Game/UI/CollapsibleButton.hpp
jmasterx/StemwaterSpades
05e5d7c6d380d2f5986bd91269887f16c3e71962
[ "Unlicense" ]
2
2015-11-21T16:42:18.000Z
2019-04-21T20:41:39.000Z
#ifndef CGE_COLLAPSIBLE_BUTTON_HPP #define CGE_COLLAPSIBLE_BUTTON_HPP #include "Game/UI/Button.hpp" #include "Game/UI/ListBox.hpp" namespace cge { class CollapsibleButton : public Button { agui::Image* m_iconRight; agui::Image* m_iconDown; int m_beginPadding; int m_midPadding; int m_yPadding; ListBox* m_list; public: CollapsibleButton(agui::Image* iconRight, agui::Image* iconDown, agui::Image* defaultImage,agui::Image* hoverImage,ListBox* list); virtual void paintBackground(const agui::PaintEvent &paintEvent); virtual void paintComponent(const agui::PaintEvent &paintEvent); virtual void resizeToContents(); ListBox* getList(); virtual ~CollapsibleButton(void); }; } #endif
26.444444
68
0.761905
jmasterx
007bdb80aac3224dded2221d1ab1258e9ad9edb8
3,733
cpp
C++
Curses/WindowSystem.cpp
takeupcode/TUCUT
17ef8064792b6b74e311d6438f43970cc97dba77
[ "MIT" ]
8
2018-10-29T02:42:52.000Z
2021-02-04T17:37:14.000Z
Curses/WindowSystem.cpp
takeupcode/TUCUT
17ef8064792b6b74e311d6438f43970cc97dba77
[ "MIT" ]
null
null
null
Curses/WindowSystem.cpp
takeupcode/TUCUT
17ef8064792b6b74e311d6438f43970cc97dba77
[ "MIT" ]
1
2019-11-07T02:18:23.000Z
2019-11-07T02:18:23.000Z
// // WindowSystem.cpp // TUCUT (Take Up Code Utility) // // Created by Abdul Wahid Tanner on 10/26/17. // Copyright © 2017 Take Up Code. All rights reserved. // #include "WindowSystem.h" #include <curses.h> #include "Colors.h" #include "CursesUtil.h" #include "ConsoleManager.h" #include "Window.h" namespace TUCUT { namespace Curses { const std::string WindowSystem::defaultToken = "WindowSystem"; std::shared_ptr<WindowSystem> WindowSystem::getSharedWindowSystem () { return std::static_pointer_cast<WindowSystem>(shared_from_this()); } WindowSystem::WindowSystem (const std::string & token, int identity) : GameSystem(token, identity), mScreenMaxX(0), mScreenMaxY(0), mMinScreenWidth(0), mMinScreenHeight(0), mMaxScreenWidth(80), mMaxScreenHeight(40), mNextWindow(nullptr), mCurrentWindow(nullptr) { } WindowSystem::~WindowSystem () { deinitialize(); } void WindowSystem::addWindow(const std::shared_ptr<Window> & window) { mWindows.push_back(window); } void WindowSystem::addWindow(std::shared_ptr<Window> && window) { mWindows.push_back(std::move(window)); } void WindowSystem::selectNextWindow(const std::string & name) { for (auto & win: mWindows) { if (win->name() == name) { mNextWindow = win.get(); break; } } } int WindowSystem::screenWidth () const { return mScreenMaxX + 1; } int WindowSystem::screenHeight () const { return mScreenMaxY + 1; } int WindowSystem::minScreenWidth () const { return mMinScreenWidth; } int WindowSystem::minScreenHeight () const { return mMinScreenHeight; } void WindowSystem::setMinScreenDimensions (int height, int width) { mMinScreenHeight = height; mMinScreenWidth = width; } int WindowSystem::maxScreenWidth () const { return mMaxScreenWidth; } int WindowSystem::maxScreenHeight () const { return mMaxScreenHeight; } void WindowSystem::setMaxScreenDimensions (int height, int width) { mMaxScreenHeight = height; mMaxScreenWidth = width; } void WindowSystem::initialize () { GameSystem::initialize(); initscr(); start_color(); raw(); noecho(); curs_set(0); nodelay(stdscr, true); keypad(stdscr, true); mousemask(ALL_MOUSE_EVENTS | REPORT_MOUSE_POSITION, nullptr); Colors::initializeColorPairs(); CursesUtil::getScreenMaxYX(mScreenMaxY, mScreenMaxX); } void WindowSystem::deinitialize () { endwin(); } void WindowSystem::handleInput () { if (mNextWindow) { // Switch current window at the beginning of the loop. mCurrentWindow = mNextWindow; mNextWindow = nullptr; } if (!mCurrentWindow) { return; } mCurrentWindow->processInput(this); } void WindowSystem::update (Game::TimeResolution elapsedTime) { if (!mCurrentWindow) { return; } CursesUtil::getScreenMaxYX(mScreenMaxY, mScreenMaxX); mCurrentWindow->resize(checkHeightBounds(screenHeight()), checkWidthBounds(screenWidth())); mCurrentWindow->update(); } void WindowSystem::render () { if (!mCurrentWindow) { return; } mCurrentWindow->draw(); doupdate(); } int WindowSystem::checkHeightBounds (int height) const { if (height < mMinScreenHeight) { return mMinScreenHeight; } if (height > mMaxScreenHeight) { return mMaxScreenHeight; } return height; } int WindowSystem::checkWidthBounds (int width) const { if (width < mMinScreenWidth) { return mMinScreenWidth; } if (width > mMaxScreenWidth) { return mMaxScreenWidth; } return width; } } // namespace Curses } // namespace TUCUT
18.665
95
0.665149
takeupcode
008201a15e8f07132fd91304cfcdb2ad15982666
1,385
cpp
C++
graphics/Win32Adapter.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
26
2015-04-22T05:25:25.000Z
2020-11-15T11:07:56.000Z
graphics/Win32Adapter.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
2
2015-01-05T10:41:27.000Z
2015-01-06T20:46:11.000Z
graphics/Win32Adapter.cpp
quyse/inanity
a39225c5a41f879abe5aa492bb22b500dbe77433
[ "MIT" ]
5
2016-08-02T11:13:57.000Z
2018-10-26T11:19:27.000Z
#include "Win32Adapter.hpp" #include "Win32Monitor.hpp" #include "../platform/Win32Window.hpp" #include "../Strings.hpp" BEGIN_INANITY_GRAPHICS Win32Adapter::Win32Adapter(const DISPLAY_DEVICE& info) : info(info), monitorsInitialized(false) { deviceName = Strings::Unicode2UTF8(info.DeviceName); deviceString = Strings::Unicode2UTF8(info.DeviceString); } String Win32Adapter::GetId() const { return deviceName; } String Win32Adapter::GetName() const { return deviceString; } const Adapter::Monitors& Win32Adapter::GetMonitors() { if(!monitorsInitialized) { for(int i = 0; ; ++i) { DISPLAY_DEVICE monitorInfo; monitorInfo.cb = sizeof(monitorInfo); if(!EnumDisplayDevices(info.DeviceName, i, &monitorInfo, EDD_GET_DEVICE_INTERFACE_NAME)) break; monitors.push_back(NEW(Win32Monitor(monitorInfo))); } monitorsInitialized = false; } return monitors; } void Win32Adapter::GetAdapters(Adapters& adapters) { for(int i = 0; ; ++i) { DISPLAY_DEVICE adapterInfo; adapterInfo.cb = sizeof(adapterInfo); if(!EnumDisplayDevices(NULL, i, &adapterInfo, 0)) break; adapters.push_back(NEW(Win32Adapter(adapterInfo))); } } ptr<Platform::Window> Win32Adapter::CreateOptimizedWindow(const String& title, int left, int top, int width, int height) { return Platform::Win32Window::CreateForOpenGL(title, left, top, width, height); } END_INANITY_GRAPHICS
22.33871
120
0.745848
quyse
0a50d5db2c733729a539c1f7b013ca3b8ed6a2bd
7,049
cpp
C++
extern/audaspace/plugins/pulseaudio/PulseAudioDevice.cpp
recogni/blender
af830498016c01c4847f00b51246bc8e3c88f6f6
[ "Naumen", "Condor-1.1", "MS-PL" ]
1
2020-01-30T01:03:05.000Z
2020-01-30T01:03:05.000Z
extern/audaspace/plugins/pulseaudio/PulseAudioDevice.cpp
recogni/blender
af830498016c01c4847f00b51246bc8e3c88f6f6
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
extern/audaspace/plugins/pulseaudio/PulseAudioDevice.cpp
recogni/blender
af830498016c01c4847f00b51246bc8e3c88f6f6
[ "Naumen", "Condor-1.1", "MS-PL" ]
null
null
null
/******************************************************************************* * Copyright 2009-2016 Jörg Müller * * 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 "PulseAudioDevice.h" #include "PulseAudioLibrary.h" #include "devices/DeviceManager.h" #include "devices/IDeviceFactory.h" #include "Exception.h" #include "IReader.h" AUD_NAMESPACE_BEGIN void PulseAudioDevice::PulseAudio_state_callback(pa_context *context, void *data) { PulseAudioDevice* device = (PulseAudioDevice*)data; device->m_state = AUD_pa_context_get_state(context); AUD_pa_threaded_mainloop_signal(device->m_mainloop, 0); } void PulseAudioDevice::PulseAudio_request(pa_stream *stream, size_t num_bytes, void *data) { PulseAudioDevice* device = (PulseAudioDevice*)data; void* buffer; AUD_pa_stream_begin_write(stream, &buffer, &num_bytes); device->mix((data_t*)buffer, num_bytes / AUD_DEVICE_SAMPLE_SIZE(device->m_specs)); AUD_pa_stream_write(stream, buffer, num_bytes, nullptr, 0, PA_SEEK_RELATIVE); } void PulseAudioDevice::PulseAudio_underflow(pa_stream *stream, void *data) { PulseAudioDevice* device = (PulseAudioDevice*)data; DeviceSpecs specs = device->getSpecs(); if(++device->m_underflows > 4 && device->m_buffersize < AUD_DEVICE_SAMPLE_SIZE(specs) * specs.rate * 2) { device->m_buffersize <<= 1; device->m_underflows = 0; pa_buffer_attr buffer_attr; buffer_attr.fragsize = -1U; buffer_attr.maxlength = -1U; buffer_attr.minreq = -1U; buffer_attr.prebuf = -1U; buffer_attr.tlength = device->m_buffersize; AUD_pa_stream_set_buffer_attr(stream, &buffer_attr, nullptr, nullptr); } } void PulseAudioDevice::playing(bool playing) { m_playback = playing; AUD_pa_stream_cork(m_stream, playing ? 0 : 1, nullptr, nullptr); } PulseAudioDevice::PulseAudioDevice(std::string name, DeviceSpecs specs, int buffersize) : m_playback(false), m_state(PA_CONTEXT_UNCONNECTED), m_buffersize(buffersize), m_underflows(0) { m_mainloop = AUD_pa_threaded_mainloop_new(); AUD_pa_threaded_mainloop_lock(m_mainloop); m_context = AUD_pa_context_new(AUD_pa_threaded_mainloop_get_api(m_mainloop), name.c_str()); if(!m_context) { AUD_pa_threaded_mainloop_unlock(m_mainloop); AUD_pa_threaded_mainloop_free(m_mainloop); AUD_THROW(DeviceException, "Could not connect to PulseAudio."); } AUD_pa_context_set_state_callback(m_context, PulseAudio_state_callback, this); AUD_pa_context_connect(m_context, nullptr, PA_CONTEXT_NOFLAGS, nullptr); AUD_pa_threaded_mainloop_start(m_mainloop); while(m_state != PA_CONTEXT_READY) { switch(m_state) { case PA_CONTEXT_FAILED: case PA_CONTEXT_TERMINATED: AUD_pa_threaded_mainloop_unlock(m_mainloop); AUD_pa_threaded_mainloop_stop(m_mainloop); AUD_pa_context_disconnect(m_context); AUD_pa_context_unref(m_context); AUD_pa_threaded_mainloop_free(m_mainloop); AUD_THROW(DeviceException, "Could not connect to PulseAudio."); break; default: AUD_pa_threaded_mainloop_wait(m_mainloop); break; } } if(specs.channels == CHANNELS_INVALID) specs.channels = CHANNELS_STEREO; if(specs.format == FORMAT_INVALID) specs.format = FORMAT_FLOAT32; if(specs.rate == RATE_INVALID) specs.rate = RATE_48000; m_specs = specs; pa_sample_spec sample_spec; sample_spec.channels = specs.channels; sample_spec.format = PA_SAMPLE_FLOAT32; sample_spec.rate = specs.rate; switch(m_specs.format) { case FORMAT_U8: sample_spec.format = PA_SAMPLE_U8; break; case FORMAT_S16: sample_spec.format = PA_SAMPLE_S16NE; break; case FORMAT_S24: sample_spec.format = PA_SAMPLE_S24NE; break; case FORMAT_S32: sample_spec.format = PA_SAMPLE_S32NE; break; case FORMAT_FLOAT32: sample_spec.format = PA_SAMPLE_FLOAT32; break; case FORMAT_FLOAT64: m_specs.format = FORMAT_FLOAT32; break; default: break; } m_stream = AUD_pa_stream_new(m_context, "Playback", &sample_spec, nullptr); if(!m_stream) { AUD_pa_threaded_mainloop_unlock(m_mainloop); AUD_pa_threaded_mainloop_stop(m_mainloop); AUD_pa_context_disconnect(m_context); AUD_pa_context_unref(m_context); AUD_pa_threaded_mainloop_free(m_mainloop); AUD_THROW(DeviceException, "Could not create PulseAudio stream."); } AUD_pa_stream_set_write_callback(m_stream, PulseAudio_request, this); AUD_pa_stream_set_underflow_callback(m_stream, PulseAudio_underflow, this); pa_buffer_attr buffer_attr; buffer_attr.fragsize = -1U; buffer_attr.maxlength = -1U; buffer_attr.minreq = -1U; buffer_attr.prebuf = -1U; buffer_attr.tlength = buffersize; if(AUD_pa_stream_connect_playback(m_stream, nullptr, &buffer_attr, static_cast<pa_stream_flags_t>(PA_STREAM_INTERPOLATE_TIMING | PA_STREAM_ADJUST_LATENCY | PA_STREAM_AUTO_TIMING_UPDATE), nullptr, nullptr) < 0) { AUD_pa_threaded_mainloop_unlock(m_mainloop); AUD_pa_threaded_mainloop_stop(m_mainloop); AUD_pa_context_disconnect(m_context); AUD_pa_context_unref(m_context); AUD_pa_threaded_mainloop_free(m_mainloop); AUD_THROW(DeviceException, "Could not connect PulseAudio stream."); } AUD_pa_threaded_mainloop_unlock(m_mainloop); create(); } PulseAudioDevice::~PulseAudioDevice() { AUD_pa_threaded_mainloop_stop(m_mainloop); AUD_pa_context_disconnect(m_context); AUD_pa_context_unref(m_context); AUD_pa_threaded_mainloop_free(m_mainloop); destroy(); } class PulseAudioDeviceFactory : public IDeviceFactory { private: DeviceSpecs m_specs; int m_buffersize; std::string m_name; public: PulseAudioDeviceFactory() : m_buffersize(AUD_DEFAULT_BUFFER_SIZE), m_name("Audaspace") { m_specs.format = FORMAT_FLOAT32; m_specs.channels = CHANNELS_STEREO; m_specs.rate = RATE_48000; } virtual std::shared_ptr<IDevice> openDevice() { return std::shared_ptr<IDevice>(new PulseAudioDevice(m_name, m_specs, m_buffersize)); } virtual int getPriority() { return 1 << 15; } virtual void setSpecs(DeviceSpecs specs) { m_specs = specs; } virtual void setBufferSize(int buffersize) { m_buffersize = buffersize; } virtual void setName(std::string name) { m_name = name; } }; void PulseAudioDevice::registerPlugin() { if(loadPulseAudio()) DeviceManager::registerDevice("PulseAudio", std::shared_ptr<IDeviceFactory>(new PulseAudioDeviceFactory)); } #ifdef PULSEAUDIO_PLUGIN extern "C" AUD_PLUGIN_API void registerPlugin() { PulseAudioDevice::registerPlugin(); } extern "C" AUD_PLUGIN_API const char* getName() { return "PulseAudio"; } #endif AUD_NAMESPACE_END
24.908127
210
0.758264
recogni
0a5c7abc3c228f7abcd6a7cf3917a7d93b2104e8
3,246
cpp
C++
test/che/assembly.cpp
shze/biosim
e9e6d97de0ccf8067e1db15980eb600389fff6ca
[ "MIT" ]
null
null
null
test/che/assembly.cpp
shze/biosim
e9e6d97de0ccf8067e1db15980eb600389fff6ca
[ "MIT" ]
null
null
null
test/che/assembly.cpp
shze/biosim
e9e6d97de0ccf8067e1db15980eb600389fff6ca
[ "MIT" ]
null
null
null
#include <boost/test/unit_test.hpp> #include "che/assembly.h" // header to test using namespace biosim; BOOST_AUTO_TEST_SUITE(suite_assembly) BOOST_AUTO_TEST_CASE(assembly_ctor) { che::assembly a; BOOST_CHECK(a.get_chain_id_list().empty()); BOOST_CHECK(a.get_ensemble_size("A") == 0); BOOST_CHECK(a.has_ensemble("A") == false); BOOST_REQUIRE_THROW(a.get_ensemble("A"), std::out_of_range); BOOST_REQUIRE_THROW(a.get_first_structure("A"), std::out_of_range); BOOST_CHECK(a.get_first_structures().empty() == true); std::string storage = "some_storage"; std::string id = "some_id"; che::structure s(storage, id); a = che::assembly(s); BOOST_CHECK(a.get_chain_id_list().size() == 1); BOOST_CHECK(a.get_ensemble_size("A") == 1); BOOST_CHECK(a.has_ensemble("A") == true); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1); BOOST_CHECK(a.get_first_structure("A").get_identifier() == id); BOOST_CHECK(a.get_first_structures().size() == 1); std::list<che::structure> structures{s, che::structure()}; che::structure_ensemble e(structures.begin(), structures.end()); a = che::assembly(e); BOOST_CHECK(a.get_chain_id_list().size() == 1); BOOST_CHECK(a.get_ensemble_size("A") == 2); BOOST_CHECK(a.has_ensemble("A") == true); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 2); BOOST_CHECK(a.get_first_structure("A").get_identifier() == id); BOOST_CHECK(a.get_first_structures().size() == 1); } BOOST_AUTO_TEST_CASE(assembly_add_set) { std::string storage = "some_storage"; std::string id = "some_id"; che::structure s(storage, id); che::assembly a; BOOST_CHECK(a.get_chain_id_list().size() == 0); BOOST_CHECK(a.add(s) == "A"); // check returned chain_id BOOST_CHECK(a.get_chain_id_list().size() == 1); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1); a.set("A", s); BOOST_CHECK(a.get_chain_id_list().size() == 1); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1); BOOST_CHECK(a.has_ensemble("B") == false); a.set("C", s); BOOST_CHECK(a.get_chain_id_list().size() == 2); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1); BOOST_CHECK(a.get_ensemble("C").get_samples().size() == 1); BOOST_CHECK(a.has_ensemble("B") == false); BOOST_CHECK(a.has_ensemble("C") == true); BOOST_CHECK(a.has_ensemble("D") == false); std::list<che::structure> structures{s, che::structure()}; che::structure_ensemble e(structures.begin(), structures.end()); a = che::assembly(); BOOST_CHECK(a.get_chain_id_list().size() == 0); BOOST_CHECK(a.add(e) == "A"); // check returned chain_id BOOST_CHECK(a.get_chain_id_list().size() == 1); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 2); a.set("A", s); BOOST_CHECK(a.get_chain_id_list().size() == 1); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1); BOOST_CHECK(a.has_ensemble("B") == false); a.set("C", e); BOOST_CHECK(a.get_chain_id_list().size() == 2); BOOST_CHECK(a.get_ensemble("A").get_samples().size() == 1); BOOST_CHECK(a.get_ensemble("C").get_samples().size() == 2); BOOST_CHECK(a.has_ensemble("B") == false); BOOST_CHECK(a.has_ensemble("C") == true); BOOST_CHECK(a.has_ensemble("D") == false); } BOOST_AUTO_TEST_SUITE_END()
37.744186
69
0.679914
shze
0a5f0d8efe00fe669f0d8175bd00f244b03de745
1,330
cpp
C++
3DRadSpace/3DRadSpaceDll/Quaternion.cpp
NicusorN5/3D_Rad_Space
029c52817deb08db17f46bef6246413a115d9e1d
[ "CC0-1.0" ]
9
2017-01-10T11:47:06.000Z
2021-11-27T14:32:55.000Z
3DRadSpace/3DRadSpaceDll/Quaternion.cpp
NicusorN5/3D_Rad_Space
029c52817deb08db17f46bef6246413a115d9e1d
[ "CC0-1.0" ]
null
null
null
3DRadSpace/3DRadSpaceDll/Quaternion.cpp
NicusorN5/3D_Rad_Space
029c52817deb08db17f46bef6246413a115d9e1d
[ "CC0-1.0" ]
6
2017-07-08T23:03:43.000Z
2022-03-08T07:47:13.000Z
#include "Quaternion.hpp" Engine3DRadSpace::Quaternion Engine3DRadSpace::Quaternion::CreateFromYawPitchRoll(float yaw, float pitch, float roll) { float halfRoll = roll * 0.5f; float halfPitch = pitch * 0.5f; float halfYaw = yaw * 0.5f; float sinRoll = sin(halfRoll); float cosRoll = cos(halfRoll); float sinPitch = sin(halfPitch); float cosPitch = cos(halfPitch); float sinYaw = sin(halfYaw); float cosYaw = cos(halfYaw); return Quaternion((cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll), (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll), (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll), (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll)); } Engine3DRadSpace::Quaternion Engine3DRadSpace::operator*(const Quaternion& q1, const Quaternion& q2) { float x = q1.X; float y = q1.Y; float z = q1.Z; float w = q1.W; float num4 = q2.X; float num3 = q2.Y; float num2 = q2.Z; float num = q2.W; float num12 = (y * num2) - (z * num3); float num11 = (z * num4) - (x * num2); float num10 = (x * num3) - (y * num4); float num9 = ((x * num4) + (y * num3)) + (z * num2); return Quaternion( ((x * num) + (num4 * w)) + num12, ((y * num) + (num3 * w)) + num11,((z * num) + (num2 * w)) + num10, (w * num) - num9); }
34.102564
139
0.616541
NicusorN5
0a610905dbf99cb1321d411431ceb988292c8cbb
3,272
hpp
C++
src/gestion-fichiers/ifile.hpp
minijackson/IGI-3004
8354f40e296cce8735b188dd3ff7406e96d5878e
[ "MIT" ]
1
2017-10-01T02:29:06.000Z
2017-10-01T02:29:06.000Z
src/gestion-fichiers/ifile.hpp
minijackson/IGI-3004
8354f40e296cce8735b188dd3ff7406e96d5878e
[ "MIT" ]
null
null
null
src/gestion-fichiers/ifile.hpp
minijackson/IGI-3004
8354f40e296cce8735b188dd3ff7406e96d5878e
[ "MIT" ]
null
null
null
#pragma once #include "utility.hpp" /*! \brief Represents an input file. * * This class implements the RAII idiom. */ template <typename flag = unbuffered_flag> class IFile : public DummyFile<flag, true> { static_assert(std::is_same<flag, buffered_flag>::value || std::is_same<flag, unbuffered_flag>::value, "An IFile must either be buffered or unbuffered."); public: /*! \brief Construct a dummy file reader. * * This object will not be associated with a file. */ IFile() noexcept; /*! \brief IFile constructor with file descriptor. * * This constructor will not open the file nor will it close it on * destruction. */ IFile(int const fd, size_t const bufSize) noexcept; /*! \brief IFile constructor with file name. * * This constructor will open the file. */ IFile(char const* filename, size_t const bufSize); /*! \brief IFile destructor. * * Will close the file if the object was constructed with the file name. */ ~IFile(); // Non-copyable object IFile(const IFile&) = delete; IFile& operator=(const IFile&) = delete; /*! \brief Move-construct the file reader. * * The previous reader will be transformed to a dummy IFile * * \param other the IFile to be moved. */ IFile(IFile&& other) noexcept; /*! \brief Move-assign the file reader. * * The previous reader will be transformed to a dummy IFile * * \param other the IFile to be moved. * \return the moved IFile */ IFile& operator=(IFile&& other) noexcept; /*! \brief Read a line from the file. * * \param line the string to write the line to. * * \return the current object (for chaining operator>>). */ IFile& operator>>(char* line); /*! \brief close the file associated with this object. */ void close(); /*! \brief Get the file's file descriptor. * * \return the file's file descriptor. */ int getFd() const; /*! \brief Get the size of the buffer. * * \return the size of the buffer. */ size_t getBufSize() const; /*! \brief Check if the end-of-file has been reached. * * \return `true` if the end-of-file has been reached. */ bool hasEnded() const; /*! \brief Check if the object opened file. * * \return `true` if the object opened the file. */ bool hasOpenedTheFile() const; protected: /*! \brief Open the file in read-only mode. * * Will set the `openedTheFile` attribute to `true`. * * \param filename The name of the file to open. * * \return the opened file's file descriptor. */ int openFile(char const* filename) noexcept(false); /*! \brief Read one line of the file. * * \param buf the buffer to write the line to. */ void getLine(char* buf) noexcept(false); /*! \brief True if this object is a dummy reader. */ bool dummy = false; /*! \brief The file descriptor of the current file. */ int fd; /*! \brief The size of the buffer for reading. * * If a line in the file is longer than the buffer size, the whole line * will not be returned. */ size_t bufSize; /*! \brief `true` if the end-of-file has been reached, `false` otherwise. */ bool ended = false; /*! \brief `true` if the current object is the one that opened the file. */ bool openedTheFile = false; }; #include "ifile.tcc"
23.371429
74
0.661369
minijackson
0a6bc0065750fa6fc0ad16ec4c90ec157bd6c068
2,606
cpp
C++
ixperial/ixperial-main/lua-entity.cpp
aw-3/ixperial
8406ac3265e572cf6a4fb4b53ae36936d550f4fe
[ "MIT" ]
1
2019-07-14T04:01:42.000Z
2019-07-14T04:01:42.000Z
ixperial/ixperial-main/lua-entity.cpp
aw-3/ixperial
8406ac3265e572cf6a4fb4b53ae36936d550f4fe
[ "MIT" ]
null
null
null
ixperial/ixperial-main/lua-entity.cpp
aw-3/ixperial
8406ac3265e572cf6a4fb4b53ae36936d550f4fe
[ "MIT" ]
null
null
null
#include "stdafx.h" void* LuaEntity::GetEntityFromIndex(int i) { static void *listPtr = (int*)sigScan((int)CSGO::GetClientHandle(), "\xBB\x00\x00\x00\x00\x83\xFF\x01\x0F\x8C\x00\x00\x00\x00\x3B\xF8"); int list = *(int*)((char*)listPtr + 1); return *(int**)(list + (i * 0x10)); } RefCountedPtr<LuaEntity> LuaEntity::GetLocalPlayer() { static void* lpPtr = (int*)sigScan((int)CSGO::GetClientHandle(), "\xA3\x00\x00\x00\x00\xC7\x05\x00\x00\x00\x00\x00\x00\x00\x00\xE8\x00\x00\x00\x00\x59\xC3\x6A\x00"); int localEntPtr = *(*((int**)((int)lpPtr + 1)) + 4); LuaEntity *localEnt = new LuaEntity(0); localEnt->pEntity = localEntPtr; return RefCountedPtr<LuaEntity>(localEnt); } void LuaEntity::UpdateEntity() const { if (!pEntity) { //pEntity = (int)GetEntityFromIndex(idx); } } bool LuaEntity::IsDormant() const { UpdateEntity(); if (!pEntity) return true; static int offset = g_pVars->GetOffset("BaseEntity", "m_bDormant"); return *(bool*)(pEntity + offset); } int LuaEntity::GetTeam() const { UpdateEntity(); if (!pEntity) return 0; static int offset = g_pVars->GetOffset("DT_BaseEntity", "m_iTeamNum"); return *(int*)(pEntity + offset); } int LuaEntity::GetFlags() const { UpdateEntity(); if (!pEntity) return 0; static int offset = g_pVars->GetOffset("DT_BasePlayer", "m_fFlags"); return *(int*)(pEntity + offset); } int LuaEntity::GetHealth() const { UpdateEntity(); if (!pEntity) return 0; static int offset = g_pVars->GetOffset("DT_BasePlayer", "m_iHealth"); return *(int*)(pEntity + offset); } int LuaEntity::GetArmor() const { return 0; } RefCountedPtr<LuaVector3> LuaEntity::GetOrigin() const { UpdateEntity(); if (!pEntity) return 0; static int offset = g_pVars->GetOffset("DT_BaseEntity", "m_vecOrigin"); float* pOrigin = (float*)(pEntity + offset); // is this safe? No. return RefCountedPtr<LuaVector3>(new LuaVector3(pOrigin[0], pOrigin[1], pOrigin[2])); } int LuaEntity::GetShotsFired() const { UpdateEntity(); if (!pEntity) return 0; static int offset = g_pVars->GetOffset("DT_CSPlayer", "m_iShotsFired"); return *(int*)(pEntity + offset); } RefCountedPtr<LuaVector3> LuaEntity::GetAimPunch() const { UpdateEntity(); if (!pEntity) return 0; static int offset = g_pVars->GetOffset("DT_CSPlayer", "m_aimPunchAngle"); float* pAimpunch = (float*)(pEntity + offset); return RefCountedPtr<LuaVector3>(new LuaVector3(pAimpunch[0], pAimpunch[1], pAimpunch[2])); } void LuaEntity::SetFlags(const int& fl) { UpdateEntity(); if (!pEntity) return; static int offset = g_pVars->GetOffset("DT_BasePlayer", "m_fFlags"); *(int*)(pEntity + offset) = fl; }
28.021505
166
0.699923
aw-3
0a6cd6fb5950cfbb2d0f805afbbefc69090df878
3,296
cc
C++
JetMETCorrections/JetVertexAssociation/src/JetVertexMain.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
JetMETCorrections/JetVertexAssociation/src/JetVertexMain.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
JetMETCorrections/JetVertexAssociation/src/JetVertexMain.cc
pasmuss/cmssw
566f40c323beef46134485a45ea53349f59ae534
[ "Apache-2.0" ]
null
null
null
#include "JetMETCorrections/JetVertexAssociation/interface/JetVertexMain.h" #include "DataFormats/JetReco/interface/CaloJet.h" #include "DataFormats/TrackReco/interface/Track.h" #include "DataFormats/TrackReco/interface/TrackFwd.h" #include "FWCore/ParameterSet/interface/ParameterSet.h" #include <cmath> #include <string> using namespace reco; using namespace edm; JetVertexMain::JetVertexMain(const ParameterSet & parameters) { cutSigmaZ = parameters.getParameter<double>("JV_sigmaZ"); cutDeltaZ = parameters.getParameter<double>("JV_deltaZ"); threshold = parameters.getParameter<double>("JV_alpha_threshold"); cone_size = parameters.getParameter<double>("JV_cone_size"); Algo = parameters.getParameter<int>("JV_type_Algo"); cutType = parameters.getParameter<std::string>("JV_cutType"); } std::pair<double,bool> JetVertexMain::Main(const reco::CaloJet& jet, edm::Handle<TrackCollection> tracks, double signal_vert_Z, double signal_vert_z_error){ std::pair<double, bool> parameter; double jet_et = jet.et(); double jet_phi = jet.phi(); double jet_eta = jet.eta(); // cout<<"JET: "<<jet_et<<endl; double Pt_jets_X = 0. ; double Pt_jets_Y = 0. ; double Pt_jets_X_tot = 0. ; double Pt_jets_Y_tot = 0. ; TrackCollection::const_iterator track = tracks->begin (); if (tracks->size() > 0 ) { for (; track != tracks->end (); track++) { double Vertex_Z = track->vz(); double Vertex_Z_Error = track->dzError(); double track_eta = track->eta(); double track_phi = track->phi(); if (DeltaR(track_eta,jet_eta, track_phi, jet_phi) < cone_size) { double DeltaZ = Vertex_Z-signal_vert_Z; double DeltaZ_Error = sqrt((Vertex_Z_Error*Vertex_Z_Error)+(signal_vert_z_error*signal_vert_z_error)); Pt_jets_X_tot += track->px(); Pt_jets_Y_tot += track->py(); if (cutType == "sig") discriminator = (fabs(DeltaZ)/DeltaZ_Error) <= cutSigmaZ; else discriminator = fabs(DeltaZ) < cutDeltaZ; if (discriminator){ Pt_jets_X += track->px(); Pt_jets_Y += track->py(); } } } } double Var = -1; if (Algo == 1) Var = Track_Pt(Pt_jets_X, Pt_jets_Y)/jet_et; else if (Algo == 2) { if (Track_Pt(Pt_jets_X_tot, Pt_jets_Y_tot)!=0) Var = Track_Pt(Pt_jets_X, Pt_jets_Y)/Track_Pt(Pt_jets_X_tot, Pt_jets_Y_tot); else std::cout << "[Jets] JetVertexAssociation: Warning! problems for Algo = 2: possible division by zero .." << std::endl; } else { Var = Track_Pt(Pt_jets_X, Pt_jets_Y)/jet_et; std::cout << "[Jets] JetVertexAssociation: Warning! Algo = " << Algo << " not found; using Algo = 1" << std::endl; } // cout<<"Var = "<<Var<<endl; if (Var >= threshold) parameter = std::pair<double, bool>(Var, true); else parameter = std::pair<double, bool>(Var, false); return parameter; } double JetVertexMain::DeltaR(double eta1, double eta2, double phi1, double phi2){ double dphi = fabs(phi1-phi2); if(dphi > M_PI) dphi = 2*M_PI - dphi; double deta = fabs(eta1-eta2); return sqrt(dphi*dphi + deta*deta); } double JetVertexMain::Track_Pt(double px, double py){ return sqrt(px*px+py*py); }
32
131
0.655036
pasmuss
0a744784f40789357813ef53dcbcb261d9e2c20f
2,720
cpp
C++
devtools/tmcdbg/tmcdbgW.cpp
flyingbluefish/tmc
27cf82a3b1b5090fc81dfc82a453ccbc932896ec
[ "BSD-2-Clause" ]
null
null
null
devtools/tmcdbg/tmcdbgW.cpp
flyingbluefish/tmc
27cf82a3b1b5090fc81dfc82a453ccbc932896ec
[ "BSD-2-Clause" ]
null
null
null
devtools/tmcdbg/tmcdbgW.cpp
flyingbluefish/tmc
27cf82a3b1b5090fc81dfc82a453ccbc932896ec
[ "BSD-2-Clause" ]
null
null
null
// tmcdbgW.cpp : Defines the class behaviors for the application. // #include "stdafx.h" #include "tmcdbgW.h" #include "SplitWnd.h" #include "tmcdbgWDlg.h" /* Copyright (C) Shmuel Safonov 2009-2012 All rights reserved. Any usage of this file must be according to TMC License. */ #ifdef HAS_PLOT_DLL #include "cplot.h" #endif #ifdef _DEBUG #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif ///////////////////////////////////////////////////////////////////////////// // CTmcdbgWApp BEGIN_MESSAGE_MAP(CTmcdbgWApp, CWinApp) //{{AFX_MSG_MAP(CTmcdbgWApp) // NOTE - the ClassWizard will add and remove mapping macros here. // DO NOT EDIT what you see in these blocks of generated code! //}}AFX_MSG ON_COMMAND(ID_HELP, CWinApp::OnHelp) END_MESSAGE_MAP() ///////////////////////////////////////////////////////////////////////////// // CTmcdbgWApp construction CTmcdbgWApp::CTmcdbgWApp() { // TODO: add construction code here, // Place all significant initialization in InitInstance } ///////////////////////////////////////////////////////////////////////////// // The one and only CTmcdbgWApp object CTmcdbgWApp theApp; ///////////////////////////////////////////////////////////////////////////// // CTmcdbgWApp initialization BOOL CTmcdbgWApp::InitInstance() { // Standard initialization // If you are not using these features and wish to reduce the size // of your final executable, you should remove from the following // the specific initialization routines you do not need. //#ifdef _AFXDLL // Enable3dControls(); // Call this when using MFC in a shared DLL //#else // Enable3dControlsStatic(); // Call this when linking to MFC statically //#endif // add doc template //CDocTemplate* pDocTemplate; //pDocTemplate = new CDocTemplate(IDR_TEXTTYPE, // RUNTIME_CLASS(CPadDoc), // RUNTIME_CLASS(CPadFrame), // RUNTIME_CLASS(CPadView)); //pDocTemplate->SetServerInfo( // IDR_TEXTTYPE_EMBEDDED, IDR_TEXTTYPE_INPLACE, // RUNTIME_CLASS(CInPlaceFrame)); //AddDocTemplate(pDocTemplate); InitTmc(); CTmcdbgWDlg dlg; m_pMainWnd = &dlg; int nResponse = dlg.DoModal(); if (nResponse == IDOK) { // TODO: Place code here to handle when the dialog is // dismissed with OK } else if (nResponse == IDCANCEL) { // TODO: Place code here to handle when the dialog is // dismissed with Cancel FreeTmc(); } //long CloseAll(); #ifdef HAS_PLOT_DLL CloseAll(); #endif // Since the dialog has been closed, return FALSE so that we exit the // applicat ion, rather than start the application's message pump. return FALSE; }
25.904762
78
0.617279
flyingbluefish
0a74bb45a4444d7806e49b342cff43c205805966
8,255
cpp
C++
10/150101053_3.cpp
roopansh/IITG-CS201-CS210-Data_Structures
6d24d720c45003ecedd4702f51f3b345c95fd77e
[ "MIT" ]
3
2017-01-12T12:49:29.000Z
2019-02-07T19:58:21.000Z
10/150101053_3.cpp
roopansh/IITG-CS201-CS210-Data_Structures
6d24d720c45003ecedd4702f51f3b345c95fd77e
[ "MIT" ]
null
null
null
10/150101053_3.cpp
roopansh/IITG-CS201-CS210-Data_Structures
6d24d720c45003ecedd4702f51f3b345c95fd77e
[ "MIT" ]
4
2017-09-01T17:46:01.000Z
2019-01-04T15:07:08.000Z
/************************************************************************************************ ROOPANSH BANSAL 150101053 CS210 ************************************************************************************************/ /************************************************************************************************ Making a Database of the books using Binary Search Tree(Based on the ISBN number of the books). ************************************************************************************************/ #include <iostream> using namespace std; // Structure of a book to store all the required details struct Book { string title; string author; int year_of_publication; float cost; int number_of_copies_sold; unsigned long long ISBN; // the following pointers are used for Database Book *left = NULL; Book *right = NULL; Book *parent = NULL; }; // Database of the books using the database Binary Search Tree class BST { private: Book *Root;// root of the database long long int BookCount;// number of books in the database public: BST()// constructor function { Root = NULL; BookCount = 0; Book *temp; } void InsertFirst5()// insert the first 5 harry potter book details in the database { Book *temp; // Book # 1 temp = NULL; temp = new Book; temp->title = "Harry Potter & The Philosopher's Stone"; temp->author = "J. K. Rowling"; temp->year_of_publication = 1997; temp->cost = 5001; temp->number_of_copies_sold = 10001; temp->ISBN = 9780439708180; InsertBook(temp); // Book # 2 temp = NULL; temp = new Book; temp->title = "Harry Potter & The Chamber of Secrets"; temp->author = "J. K. Rowling"; temp->year_of_publication = 2000; temp->cost = 5002; temp->number_of_copies_sold = 10002; temp->ISBN = 9780439064873; InsertBook(temp); // Book # 3 temp = NULL; temp = new Book; temp->title = "Harry Potter & The Prisoner of Azkaban"; temp->author = "J. K. Rowling"; temp->year_of_publication = 2001; temp->cost = 5003; temp->number_of_copies_sold = 10003; temp->ISBN = 9780439136365; InsertBook(temp); // Book # 4 temp = NULL; temp = new Book; temp->title = "Harry Potter & The Goblet of Fire"; temp->author = "J. K. Rowling"; temp->year_of_publication = 2002; temp->cost = 5004; temp->number_of_copies_sold = 10004; temp->ISBN = 9780439139601; InsertBook(temp); // Book # 5 temp = NULL; temp = new Book; temp->title = "Harry Potter & The Order of the Phoenix"; temp->author = "J. K. Rowling"; temp->year_of_publication = 2004; temp->cost = 5005; temp->number_of_copies_sold = 10005; temp->ISBN = 9780439358071; InsertBook(temp); temp = NULL; } Book *RootofClass()// return a pointer to the root of the database { return Root; } void InsertBook(Book *book)// insert a new book to the database { BookCount++;// increase the number of books in the database by one if (Root == NULL)// database is empty yet { Root = book; return; } // find the appropriate position for storing the book in the database Book *ptr1 , *ptr2; ptr1 = Root; while(ptr1 != NULL) { ptr2 = ptr1; if (ptr1->ISBN < book->ISBN) { ptr1 = ptr1->right; } else { ptr1 = ptr1->left; } } // insert the book to that position if (ptr2->ISBN < book->ISBN) { ptr2->right = book; } else { ptr2->left = book; } book->parent = ptr2; return; } void Increase10(BST *& NewBookDB)// create a new database with the same books such that price of the books is increased by 10% { NewBookDB = new BST;// allocate memory to the new database NewBookDB->InsertBook10(Root); } void InsertBook10(Book * book) { // create a new book with the same details and price increased by 10% Book *temp = new Book; temp->title = book->title; temp->author = book->author; temp->year_of_publication = book->year_of_publication; temp->cost = (book->cost)*1.10;// price is multiplied by 1.10 temp->number_of_copies_sold = book->number_of_copies_sold; temp->ISBN = book->ISBN; // insert the book to the database InsertBook(temp); // recursively add the books in the left subtree and then right subtree if (book->left != NULL) InsertBook10(book->left); if (book->right != NULL) InsertBook10(book->right); } void PrintBookDB(Book *book)// print the book database { if (book == NULL) { return; } // print the book title, ISBN, cost of the book cout<<"<"<<book->title<<", "<<book->ISBN<<", Rs. "<<book->cost<<">"<<endl; // recursively print the books details in the left and right subtrees PrintBookDB(book->left); PrintBookDB(book->right); } Book *FindCopiesSold()// returns a pointer to the book whose ISBN is given { // take the ISBN as the input cout<<endl<<"Please enter the ISBN of the book you want to find: "; unsigned long long int Book_ISBN; cin>>Book_ISBN; Book *bookPtr = Root; // find the book while(bookPtr != NULL) { // if the book is found, return the pointer to that book if (bookPtr->ISBN == Book_ISBN) { return bookPtr; } else if (bookPtr->ISBN < Book_ISBN) { bookPtr = bookPtr->right; } else { bookPtr = bookPtr->left; } } // if the book is not found, return a NULL pointer return NULL; } }; void DisplayChoice()// display the choices available to the user { cout<<"\n(1)Exit\n(2)Increase the Price of each book by 10%\n(3)Find the number of Copies Sold\n(4)Insert a New Book\n(5)Print the Books Database\n\n"; return; } int main()// main function { BST *Book_DB = NULL; int choice; // first create a database with 5 books... proceed only if the database is created while(Book_DB == NULL) { cout<<"First Enter (1) to create a Book Database with 5 books initially.\n"; cin>>choice; if (choice == 1) { Book_DB = new BST;// allocate memory for the new Books database Book_DB->InsertFirst5();// add the first 5 books to the database cout<<"Database initialised.\n\n"; } } DisplayChoice(); while(true) { cout<<"\n Now Enter choice: "; cin>>choice; switch(choice) { case 1:// exit { return 0; } case 2:// increase the prices by 10% { BST *Book_DB_New = NULL;// create a pointer to the new database Book_DB->Increase10(Book_DB_New); // after the above fucntion returns, the Book_DB_New contains all the books with prices increased by 10% delete(Book_DB);// dlete the original database Book_DB = Book_DB_New;// replace the original databse by the new database cout<<"Price of each Book Increased by 10%"; break; } case 3:// copies sold { Book *book = Book_DB->FindCopiesSold();// pointer to the require book cout<<endl; if (book != NULL) { cout<<"Number of copies Sold of '"<<book->title<<"' are '"<<book->number_of_copies_sold<<"'."<<endl; } else { cout<<"Book not found in the Database"<<endl; } break; } case 4:// Insert a new Book { // input the details of the book from the user cout<<"Enter the Book Details"<<endl; cout<<"Title:\t"; string title; cin.ignore(); getline(cin,title); cout<<"Author:\t"; string author; cin.ignore(); getline(cin,author); cout<<"Year of Publication:\t"; int year_of_publication; cin>>year_of_publication; cout<<"Cost:\t"; float cost; cin>>cost; cout<<"Number of Copies Sold:\t"; int number_of_copies_sold; cin>>number_of_copies_sold; cout<<"ISBN:\t"; unsigned long long ISBN; cin>>ISBN; // create a new book structure with the given details Book *NewBookToInsert = new Book; NewBookToInsert->title = title; NewBookToInsert->author=author; NewBookToInsert->year_of_publication=year_of_publication; NewBookToInsert->cost=cost; NewBookToInsert->number_of_copies_sold=number_of_copies_sold; NewBookToInsert->ISBN=ISBN; // insert the book to the database Book_DB->InsertBook(NewBookToInsert); break; } case 5:// print the entire books database { Book_DB->PrintBookDB(Book_DB->RootofClass()); break; } default: { cout<<"Please enter a valid choice.\n\n"; break; } } } }
24.641791
152
0.623622
roopansh
0a7662bf121ffbd99d0517cdaca25ccf500b6aff
310
cpp
C++
ntuj/0056.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
ntuj/0056.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
ntuj/0056.cpp
dk00/old-stuff
e1184684c85fe9bbd1ceba58b94d4da84c67784e
[ "Unlicense" ]
null
null
null
#include<cstdio> #include<algorithm> using namespace std; int s[1000000]; main() { int i,k,n; while(scanf("%d %d",&n,&k)==2) { for(i=0;i<n;i++) scanf("%d",s+i); sort(s,s+n); for(i=0;i<k-1;i++) printf("%d ",s[i]); printf("%d\n",s[i]); } }
17.222222
34
0.429032
dk00
0a7c03f1832f14af13c00529fff2506864848423
48
hpp
C++
src/boost_test_data_monomorphic_grid.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
10
2018-03-17T00:58:42.000Z
2021-07-06T02:48:49.000Z
src/boost_test_data_monomorphic_grid.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
2
2021-03-26T15:17:35.000Z
2021-05-20T23:55:08.000Z
src/boost_test_data_monomorphic_grid.hpp
miathedev/BoostForArduino
919621dcd0c157094bed4df752b583ba6ea6409e
[ "BSL-1.0" ]
4
2019-05-28T21:06:37.000Z
2021-07-06T03:06:52.000Z
#include <boost/test/data/monomorphic/grid.hpp>
24
47
0.791667
miathedev
0a897bad9835b03c71f3c9e79a3037c9510bdfd9
3,702
hpp
C++
boost/geometry/strategies/cartesian/densify.hpp
pranavgo/RRT
87148c3ddb91600f4e74f00ffa8af14b54689aa4
[ "MIT" ]
326
2015-02-08T13:47:49.000Z
2022-03-16T02:13:59.000Z
boost/geometry/strategies/cartesian/densify.hpp
pranavgo/RRT
87148c3ddb91600f4e74f00ffa8af14b54689aa4
[ "MIT" ]
623
2015-01-02T23:45:23.000Z
2022-03-09T11:15:23.000Z
boost/geometry/strategies/cartesian/densify.hpp
pranavgo/RRT
87148c3ddb91600f4e74f00ffa8af14b54689aa4
[ "MIT" ]
215
2015-01-14T15:50:38.000Z
2022-02-23T03:58:36.000Z
// Boost.Geometry // Copyright (c) 2017-2021, Oracle and/or its affiliates. // Contributed and/or modified by Adam Wulkiewicz, on behalf of Oracle // Licensed under the Boost Software License version 1.0. // http://www.boost.org/users/license.html #ifndef BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP #define BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP #include <boost/geometry/algorithms/detail/convert_point_to_point.hpp> #include <boost/geometry/algorithms/detail/signed_size_type.hpp> #include <boost/geometry/arithmetic/arithmetic.hpp> #include <boost/geometry/arithmetic/dot_product.hpp> #include <boost/geometry/core/assert.hpp> #include <boost/geometry/core/coordinate_dimension.hpp> #include <boost/geometry/core/coordinate_type.hpp> #include <boost/geometry/geometries/point.hpp> #include <boost/geometry/strategies/densify.hpp> #include <boost/geometry/util/algorithm.hpp> #include <boost/geometry/util/math.hpp> #include <boost/geometry/util/select_most_precise.hpp> namespace boost { namespace geometry { namespace strategy { namespace densify { /*! \brief Densification of cartesian segment. \ingroup strategies \tparam CalculationType \tparam_calculation \qbk{ [heading See also] [link geometry.reference.algorithms.densify.densify_4_with_strategy densify (with strategy)] } */ template < typename CalculationType = void > class cartesian { public: template <typename Point, typename AssignPolicy, typename T> static inline void apply(Point const& p0, Point const& p1, AssignPolicy & policy, T const& length_threshold) { typedef typename AssignPolicy::point_type out_point_t; typedef typename coordinate_type<out_point_t>::type out_coord_t; typedef typename select_most_precise < typename coordinate_type<Point>::type, out_coord_t, CalculationType >::type calc_t; typedef model::point<calc_t, geometry::dimension<Point>::value, cs::cartesian> calc_point_t; assert_dimension_equal<calc_point_t, out_point_t>(); calc_point_t cp0, dir01; // dir01 = p1 - p0 geometry::detail::for_each_dimension<calc_point_t>([&](auto index) { calc_t const coord0 = boost::numeric_cast<calc_t>(get<index>(p0)); calc_t const coord1 = boost::numeric_cast<calc_t>(get<index>(p1)); set<index>(cp0, coord0); set<index>(dir01, coord1 - coord0); }); calc_t const dot01 = geometry::dot_product(dir01, dir01); calc_t const len = math::sqrt(dot01); BOOST_GEOMETRY_ASSERT(length_threshold > T(0)); signed_size_type const n = signed_size_type(len / length_threshold); if (n <= 0) { return; } calc_t const den = calc_t(n + 1); for (signed_size_type i = 0 ; i < n ; ++i) { out_point_t out; calc_t const num = calc_t(i + 1); geometry::detail::for_each_dimension<out_point_t>([&](auto index) { // out = p0 + d * dir01 calc_t const coord = get<index>(cp0) + get<index>(dir01) * num / den; set<index>(out, boost::numeric_cast<out_coord_t>(coord)); }); policy.apply(out); } } }; #ifndef DOXYGEN_NO_STRATEGY_SPECIALIZATIONS namespace services { template <> struct default_strategy<cartesian_tag> { typedef strategy::densify::cartesian<> type; }; } // namespace services #endif // DOXYGEN_NO_STRATEGY_SPECIALIZATIONS }} // namespace strategy::densify }} // namespace boost::geometry #endif // BOOST_GEOMETRY_STRATEGIES_CARTESIAN_DENSIFY_HPP
28.697674
112
0.680173
pranavgo
0a8cb7752de7e341da237696754cfa2157dafc31
2,965
hpp
C++
src/gui/text.hpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
1
2022-01-16T07:06:13.000Z
2022-01-16T07:06:13.000Z
src/gui/text.hpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
null
null
null
src/gui/text.hpp
synaodev/apostellein
f664a88d13f533df54ad6fb58c2ad8134f8f942c
[ "BSD-3-Clause" ]
null
null
null
#pragma once #include <string> #include <apostellein/rect.hpp> #include "../video/vertex.hpp" struct bitmap_font; struct renderer; namespace gui { // utf-8 to utf-32 void unicode(const std::string& utf8, std::u32string& utf32); struct text : public not_copyable { public: void build( const glm::vec2& position, const glm::vec2& origin, const chroma& color, const bitmap_font* font, const std::string& words ); void clear(); void invalidate() const { invalidated_ = true; } void fix(const bitmap_font* font) { invalidated_ = true; font_ = font; this->generate_quads_(); } void handle() { if (!this->finished()) { invalidated_ = true; ++letter_; } } void render(renderer& rdr) const; void append(const std::string& words, bool immediate = true) { invalidated_ = true; gui::unicode(words, buffer_); const auto length = this->drawable(); if (immediate or letter_ > length) { letter_ = length; } this->generate_quads_(); } void replace(const std::string& words, bool immediate = true) { buffer_.clear(); this->append(words, immediate); } void append(const std::u32string& words, bool immediate = true) { invalidated_ = true; buffer_.append(words); const auto length = this->drawable(); if (immediate or letter_ > length) { letter_ = length; } this->generate_quads_(); } void replace(const std::u32string& words, bool immediate = true) { invalidated_ = true; buffer_ = words; const auto length = this->drawable(); if (immediate or letter_ > length) { letter_ = length; } this->generate_quads_(); } void forward(std::u32string&& words, bool immediate = true) { invalidated_ = true; buffer_ = std::move(words); const auto length = this->drawable(); if (immediate or letter_ > length) { letter_ = length; } this->generate_quads_(); } void position(glm::vec2 value); void position(r32 x, r32 y) { const glm::vec2 p { x, y }; this->position(p); } void origin(glm::vec2 value); void origin(r32 x, r32 y) { const glm::vec2 o { x, y }; this->origin(o); } void color(const chroma& value) { if (color_ != value) { invalidated_ = true; color_ = value; this->generate_attributes_(); } } const glm::vec2& position() const { return position_; } const glm::vec2& origin() const { return origin_; } const chroma& color() const { return color_; } glm::vec2 font_dimensions() const; const bitmap_font* font() const { return font_; } rect bounds() const; bool finished() const { return letter_ >= this->drawable(); } udx drawable() const; private: void generate_quads_(); void generate_attributes_(); mutable bool invalidated_ {}; glm::vec2 position_ {}; glm::vec2 origin_ {}; chroma color_ { chroma::WHITE() }; udx letter_ {}; std::u32string buffer_ {}; const bitmap_font* font_ {}; std::vector<vtx_sprite> vertices_ {}; }; }
25.560345
68
0.646543
synaodev
0a8f123b3da7cb94b773fc2592bf889744756af4
6,713
cpp
C++
src/scheduler/schedulingSimulator.cpp
Jacques-Florence/SchedSim
cd5f356ec1d177963d401b69996a19a68646d7af
[ "BSD-3-Clause" ]
1
2019-12-24T19:07:19.000Z
2019-12-24T19:07:19.000Z
src/scheduler/schedulingSimulator.cpp
Jacques-Florence/SchedSim
cd5f356ec1d177963d401b69996a19a68646d7af
[ "BSD-3-Clause" ]
null
null
null
src/scheduler/schedulingSimulator.cpp
Jacques-Florence/SchedSim
cd5f356ec1d177963d401b69996a19a68646d7af
[ "BSD-3-Clause" ]
null
null
null
/** * Copyright 2017 Jacques Florence * All rights reserved. * See License.txt file * */ #include "schedulingSimulator.h" #include <algorithm> #include <cassert> #include <cmath> #include <ctime> #include <utils/log.h> #include <utils/randomGenerator.h> #include "events/coreEvents.h" #include "events/eventList.h" #include "freqConstants.h" #include "process.h" #include "schedulerConfiguration.h" #include "system.h" #include "taskSetGenerator.h" #include "time.h" #include "xmlTaskSet.h" using namespace Scheduler; SchedulingSimulator::SchedulingSimulator() { conf = std::make_shared<SchedulerConfiguration>("configuration.conf"); System::buildSystem(conf); } SchedulingSimulator::SchedulingSimulator(std::shared_ptr<SchedulerConfiguration> c) : conf(c) { NewJob::init(); System::buildSystem(c); } SchedulingSimulator::~SchedulingSimulator() { Process::end(); } void SchedulingSimulator::initializeTaskSet() { std::string value = conf->getStringValue("taskSet", "tasksetSource"); if (!value.compare("xml")) initializeTaskSetFromXml(); else if (!value.compare("random")) initializeTaskSetRandomly(); else if (!value.compare("compiled")) initializeTaskSetAtCompileTime(); else initializeTaskSetAtCompileTime(); } void SchedulingSimulator::initializeTaskSetFromXml() { XmlTaskSet xml; std::shared_ptr<std::vector<std::shared_ptr<Process>>> taskset = xml.getRealTimeTaskSetFromXml("xml/taskset.xml"); for (size_t i = 0; i < taskset->size(); i++) { System::getInstance()->addRealTimeTask((*taskset)[i]); double startTime = 0.1; //TODO HARDCODED !!! std::shared_ptr<Event> rt = std::make_shared<NewJob>(startTime); rt->setTask((*taskset)[i]); EventList::getInstance()->insert(rt); //std::cerr << "added real-time task. The event list is:\n"; //EventList::getInstance()->print(); } } void SchedulingSimulator::initializeTaskSetRandomly() { int nbOfTasks = conf->getIntValue("taskSet","nbOfTasks"); double utilization = conf->getDoubleValue("taskSet", "utilization"); time_t tasksetSeed = conf->getIntValue("taskSet","seed"); std::shared_ptr<Utils::BoundedRandomDistribution> dist; dist = conf->getDistributionFromFile(&randomGenerator); TaskSetGenerator::generate(this, nbOfTasks, utilization, tasksetSeed, true, true, dist); } void SchedulingSimulator::initializeTaskSetAtCompileTime() { #if 0 /*Utilization for this task set is 0.792*/ createRealTimeTask(0.1, 35.0, 10.0*100, 25.0); createRealTimeTask(0.1, 25.0, 6.0*100, 6.0); createRealTimeTask(0.1, 15.0, 4.0*100, 14.9); #endif #if 0 /*Utilization for this task set is 0.972*/ createRealTimeTask(0.1, 35.0, 10.0*100); createRealTimeTask(0.1, 25.0, 8.0*100); createRealTimeTask(0.1, 15.0, 3.0*100); createRealTimeTask(0.1, 30.0, 5.0*100); #endif #if 0 /*Utilization for this task set is 0.967*/ createRealTimeTask(0.1, 30.0, 6.0*100); createRealTimeTask(0.1, 20.0, 8.0*100); createRealTimeTask(0.1, 15.0, 3.0*100); createRealTimeTask(0.1, 30.0, 5.0*100); #endif //simulator.createRealTimeTask(0.0, 15.0, 7.0, 15.0); #if 0 createInteractiveProcess(1.0); createInteractiveProcess(1.0); createInteractiveProcess(10.0); createInteractiveProcess(100.0); createInteractiveProcess(300.0); #endif #if 1 createRealTimeTask(0.1, 200, 6000, 200, 2, 6000, 1.5); createRealTimeTask(0.1, 100, 3000, 200, 1, 3000, 1.0); #endif #if 0 createRealTimeTask(0.1, 30.0, 5.0*100.0, 20.0, 0, 499.0, 1.0); createRealTimeTask(0.1, 20.0, 5.0*100.0, 20.0, 0, 499.0, 1.5); #endif } std::shared_ptr<Process> SchedulingSimulator::createRealTimeTask(double startTime, double period, double wcet, double deadline, int priority, double bcet, double powerCoeff) { if (deadline <= 0.0) deadline = period; std::shared_ptr<Process> p = Process::createRealTimeTask(wcet, period, deadline, Process::getNewPid(), priority, bcet); p->setPowerCoeff(powerCoeff); std::shared_ptr<Event> rt = std::make_shared<NewJob>(startTime); rt->setTask(p); EventList::getInstance()->insert(rt); System::getInstance()->addRealTimeTask(p); return p; } void SchedulingSimulator::createInteractiveProcess(double startTime) { EventList::getInstance()->insert(std::make_shared<NewInteractiveProcess>(startTime)); } void SchedulingSimulator::seedRandomGenerator(time_t seed) { randomGenerator.seed(seed); } void SchedulingSimulator::endSimulation(double time) { EventList *eventList = EventList::getInstance();; std::shared_ptr<Event> stopEvent = std::make_shared<StopSimulation>(time); eventList->insert(stopEvent); } void SchedulingSimulator::setUsageCalculationTimeout(double start, double interval) { std::shared_ptr<UsageUpdate> cpuUsageUpdate = std::make_shared<UsageUpdate>(start); cpuUsageUpdate->setInterval(interval); EventList::getInstance()->insert(cpuUsageUpdate); } void SchedulingSimulator::setStatsTick(double start, double interval) { std::shared_ptr<StatsTick> tick = std::make_shared<StatsTick>(start); tick->setInterval(interval); EventList::getInstance()->insert(tick); } void SchedulingSimulator::setFreqUpdate(double start, double interval) { std::shared_ptr<FreqUpdate> freqTO = std::make_shared<FreqUpdate>(start); freqTO->setInterval(interval); EventList::getInstance()->insert(freqTO); } void SchedulingSimulator::setSchedulerTimeout(double start, double interval) { std::shared_ptr<SchedTimeOut> timeout = std::make_shared<SchedTimeOut>(start); timeout->setInterval(interval); EventList::getInstance()->insert(timeout); } void SchedulingSimulator::setDummyEvent(double start, double interval) { std::shared_ptr<DummyEvent> dummy = std::make_shared<DummyEvent>(start); dummy->setInterval(interval); EventList::getInstance()->insert(dummy); } void SchedulingSimulator::startScheduler() { EventList *list = EventList::getInstance(); //std::cerr << "list of events:\n"; //list->print(); list->setRandomGenerator(&randomGenerator); Process::setRandomGenerator(&randomGenerator); while(!list->isEmpty()) { std::shared_ptr<Event> e = list->getHead(); Utils::Log log; Time::updateTime(e->getTime()); double timeInterval = e->getTime() - previousTime; previousTime = e->getTime(); System::getInstance()->updateTemperature(timeInterval); e->process(); list->pop(); static double previousTimeTrack = 0.0; double timeTrack = e->getTime(); if (timeTrack - previousTimeTrack > 100000.0) { std::cerr << "time: "<< timeTrack <<"\n"; previousTimeTrack = timeTrack; } } std::cerr << "after the startScheduler\n"; } void SchedulingSimulator::turnOnProcessor(double start) { Utils::Log log; std::shared_ptr<StartProc> startProc = std::make_shared<StartProc>(start); EventList::getInstance()->insert(startProc); }
26.429134
93
0.733651
Jacques-Florence
0a8faa85e2f1a0bac579ead44b7fc85f8b5f6392
1,567
cpp
C++
app/cpp/mysimplegimp/src/core/transformations/map_normal.cpp
jaroslaw-wieczorek/lpo-image-processing
505494cff99cc8e054106998f86b599f0509880b
[ "MIT" ]
null
null
null
app/cpp/mysimplegimp/src/core/transformations/map_normal.cpp
jaroslaw-wieczorek/lpo-image-processing
505494cff99cc8e054106998f86b599f0509880b
[ "MIT" ]
null
null
null
app/cpp/mysimplegimp/src/core/transformations/map_normal.cpp
jaroslaw-wieczorek/lpo-image-processing
505494cff99cc8e054106998f86b599f0509880b
[ "MIT" ]
null
null
null
#include "map_normal.h" #include "edge_sobel.h" #include "map_height.h" #include <iostream> MapNormal::MapNormal(PNM* img) : Convolution(img) { } MapNormal::MapNormal(PNM* img, ImageViewer* iv) : Convolution(img, iv) { } PNM* MapNormal::transform() { int width = image->width(); int height = image->height(); // The power constant of the generated normal map. double strength = getParameter("strength").toDouble(); PNM* newImage = new PNM(width, height, image->format()); MapHeight* mh = new MapHeight(image); PNM* image = mh->transform(); EdgeSobel* es = new EdgeSobel(image); math::matrix<float>* Gx = es->rawHorizontalDetection(); math::matrix<float>* Gy = es->rawVerticalDetection(); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { // For each pixel (i,j), determine the coordinates of the vector d float dx = (*Gx)(i, j) / 255; float dy = (*Gy)(i, j) / 255; float dz = 1.0 / strength; // Normalise the vector d double dw = sqrt(pow(dx, 2) + pow(dy, 2) + pow(dz, 2)); // Scale these values to the interval dx = dx / dw; dy = dy / dw; dz = dz / dw; dx = (dx + 1.0) * (255 / strength); dy = (dy + 1.0) * (255 / strength); dz = (dz + 1.0) * (255 / strength); QColor newPixel = QColor(dx, dy, dz); newImage->setPixel(i, j, newPixel.rgb()); } } return newImage; }
25.274194
78
0.532865
jaroslaw-wieczorek
0a91b7e39e5de21cba064b8b399b9727984e730f
2,481
cpp
C++
kobold-layer.nucleus.test/src/texture/texture_manager_test.cpp
BeardedPlatypus/kobold-layer
c258c79afe06213bf44cbcbb1474968350cfeec3
[ "MIT" ]
null
null
null
kobold-layer.nucleus.test/src/texture/texture_manager_test.cpp
BeardedPlatypus/kobold-layer
c258c79afe06213bf44cbcbb1474968350cfeec3
[ "MIT" ]
1
2021-01-24T09:58:14.000Z
2021-01-24T10:04:03.000Z
kobold-layer.nucleus.test/src/texture/texture_manager_test.cpp
BeardedPlatypus/kobold-layer
c258c79afe06213bf44cbcbb1474968350cfeec3
[ "MIT" ]
null
null
null
#include "kobold-layer.nucleus.mock/texture/texture_factory_mock.hpp" #include "kobold-layer.nucleus.mock/texture/texture_mock.hpp" #include <gmock/gmock.h> #include <gtest/gtest.h> #include "texture/texture_manager_implementation.hpp" using ::testing::Return; using ::testing::ByMove; using ::testing::IsTrue; using ::testing::IsFalse; namespace kobold_layer::nucleus::texture { TEST(texture_manager_test, load_texture_first_time_the_texture_is_added_to_the_manager) { // Setup auto p_texture_mock = std::make_unique<texture_mock>(); texture const* texture = p_texture_mock.get(); const auto texture_path = std::filesystem::path(); auto p_texture_factory_mock = std::make_unique<texture_factory_mock>(); EXPECT_CALL(*(p_texture_factory_mock.get()), construct_texture(texture_path)) .Times(1) .WillOnce(Return(ByMove(std::move(p_texture_mock)))); auto texture_manager = texture_manager_implementation(std::move(p_texture_factory_mock)); const std::string key = "key"; // Call texture_manager.load_texture(key, texture_path); // Assert ASSERT_THAT(texture_manager.has_texture(key), IsTrue); ASSERT_THAT(texture_manager.get_texture(key), texture); } TEST(texture_manager_test, load_texture_twice_only_one_time_constructed) { auto p_texture_mock = std::make_unique<texture_mock>(); texture const* texture = p_texture_mock.get(); const auto texture_path_a = std::filesystem::path(); const auto texture_path_b = std::filesystem::path(); auto p_texture_factory_mock = std::make_unique<texture_factory_mock>(); EXPECT_CALL(*(p_texture_factory_mock.get()), construct_texture(texture_path_a)) .Times(1) .WillOnce(Return(ByMove(std::move(p_texture_mock)))); auto texture_manager = texture_manager_implementation(std::move(p_texture_factory_mock)); const std::string key = "key"; // Call texture_manager.load_texture(key, texture_path_a); texture_manager.load_texture(key, texture_path_b); // Assert ASSERT_THAT(texture_manager.has_texture(key), IsTrue); ASSERT_THAT(texture_manager.get_texture(key), texture); } TEST(texture_manager_test, has_texture_not_loaded_returns_false) { // Setup auto p_texture_factory_mock = std::make_unique<texture_factory_mock>(); const auto texture_manager = texture_manager_implementation(std::move(p_texture_factory_mock)); // Call bool const result = texture_manager.has_texture("any_not_loaded_key"); // Assert ASSERT_THAT(result, IsFalse()); } }
31.405063
97
0.771463
BeardedPlatypus
0a95ad0e93f390ce48b0c482da2f16a1bf6df28c
8,359
cpp
C++
c++/src/util/itree.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
31
2016-12-09T04:56:59.000Z
2021-12-31T17:19:10.000Z
c++/src/util/itree.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
6
2017-03-10T17:25:13.000Z
2021-09-22T15:49:49.000Z
c++/src/util/itree.cpp
OpenHero/gblastn
a0d6c1c288fe916ab85fc637a44cdd6e79ebd2a8
[ "MIT" ]
20
2015-01-04T02:15:17.000Z
2021-12-03T02:31:43.000Z
/* $Id: itree.cpp 103491 2007-05-04 17:18:18Z kazimird $ * =========================================================================== * * 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. * * =========================================================================== * * Author: Eugene Vasilchenko * * File Description: * Implementation of interval search tree. * * =========================================================================== */ #include <ncbi_pch.hpp> #include <corelib/ncbistd.hpp> #include <util/itree.hpp> BEGIN_NCBI_SCOPE inline CIntervalTree::coordinate_type CIntervalTree::GetMaxRootCoordinate(void) const { coordinate_type max = m_Root.m_Key * 2; if ( max <= 0 ) max = TTraits::GetMaxCoordinate(); return max; } inline CIntervalTree::coordinate_type CIntervalTree::GetNextRootKey(void) const { coordinate_type nextKey = m_Root.m_Key * 2; _ASSERT(nextKey > 0); return nextKey; } void CIntervalTree::DoInsert(const interval_type& interval, TTreeMapI value) { _ASSERT(TTraits::IsNormal(interval)); // ensure our tree covers specified interval if ( interval.GetTo() > GetMaxRootCoordinate() ) { // insert one more level on top if ( m_Root.m_Left || m_Root.m_Right || m_Root.m_NodeIntervals ) { // non empty tree, insert new root node do { TTreeNode* newLeft = AllocNode(); // copy root node contents *newLeft = m_Root; // fill new root m_Root.m_Key = GetNextRootKey(); m_Root.m_Left = newLeft; m_Root.m_Right = 0; m_Root.m_NodeIntervals = 0; } while ( interval.GetTo() > GetMaxRootCoordinate() ); } else { // empty tree, just recalculate root do { m_Root.m_Key = GetNextRootKey(); } while ( interval.GetTo() > GetMaxRootCoordinate() ); } } TTreeNode* node = &m_Root; coordinate_type nodeSize = m_Root.m_Key; for ( ;; ) { coordinate_type key = node->m_Key; nodeSize = (nodeSize + 1) / 2; TTreeNode** nextPtr; coordinate_type nextKeyOffset; if ( interval.GetFrom() > key ) { nextPtr = &node->m_Right; nextKeyOffset = nodeSize; } else if ( interval.GetTo() < key ) { nextPtr = &node->m_Left; nextKeyOffset = -nodeSize; } else { // found our tile TTreeNodeInts* nodeIntervals = node->m_NodeIntervals; if ( !nodeIntervals ) node->m_NodeIntervals = nodeIntervals = CreateNodeIntervals(); nodeIntervals->Insert(interval, value); return; } TTreeNode* next = *nextPtr; if ( !next ) // create new node (*nextPtr) = next = InitNode(AllocNode(), key + nextKeyOffset); _ASSERT(next->m_Key == key + nextKeyOffset); node = next; } } bool CIntervalTree::DoDelete(TTreeNode* node, const interval_type& interval, TTreeMapI value) { _ASSERT(node); coordinate_type key = node->m_Key; if ( interval.GetFrom() > key ) { // left return DoDelete(node->m_Right, interval, value) && !node->m_NodeIntervals && !node->m_Left; } else if ( interval.GetTo() < key ) { // right return DoDelete(node->m_Left, interval, value) && !node->m_NodeIntervals && !node->m_Right; } else { // inside TTreeNodeInts* nodeIntervals = node->m_NodeIntervals; _ASSERT(nodeIntervals); if ( !nodeIntervals->Delete(interval, value) ) return false; // node intervals non empty // remove node intervals DeleteNodeIntervals(nodeIntervals); node->m_NodeIntervals = 0; // delete node if it doesn't have leaves return !node->m_Left && !node->m_Right; } } void CIntervalTree::Destroy(void) { ClearNode(&m_Root); m_ByX.clear(); } CIntervalTree::iterator CIntervalTree::Insert(const interval_type& interval, const mapped_type& value) { TTreeMapI iter = m_ByX.insert(TTreeMapValue(interval.GetFrom(), interval.GetTo(), value)); DoInsert(interval, iter); return iterator(0, TTraits::GetMaxCoordinate(), &TTreeMap::get(iter)); } CIntervalTree::const_iterator CIntervalTree::IntervalsOverlapping(const interval_type& interval) const { coordinate_type x = interval.GetFrom(); coordinate_type y = interval.GetTo(); const_iterator it(x, TTraits::GetMaxCoordinate(), 0, &m_Root); TTreeMapCI iter = m_ByX.lower_bound(TTreeMapValue(x + 1, 0, mapped_type())); if ( iter != m_ByX.end() && iter->GetKey() <= y ) { it.m_SearchLimit = y; it.m_CurrentMapValue = &*iter; } else { it.NextLevel(); } return it; } CIntervalTree::iterator CIntervalTree::IntervalsOverlapping(const interval_type& interval) { coordinate_type x = interval.GetFrom(); coordinate_type y = interval.GetTo(); iterator it(x, TTraits::GetMaxCoordinate(), 0, &m_Root); TTreeMapI iter = m_ByX.lower_bound(TTreeMapValue(x + 1, 0, mapped_type())); if ( iter != m_ByX.end() && iter->GetKey() <= y ) { it.m_SearchLimit = y; it.m_CurrentMapValue = &TTreeMap::get(iter); } else { it.NextLevel(); } return it; } CIntervalTree::TTreeNode* CIntervalTree::AllocNode(void) { return m_NodeAllocator.allocate(1, (TTreeNode*) 0); } void CIntervalTree::DeallocNode(TTreeNode* node) { m_NodeAllocator.deallocate(node, 1); } CIntervalTree::TTreeNodeInts* CIntervalTree::AllocNodeIntervals(void) { return m_NodeIntervalsAllocator.allocate(1, (TTreeNodeInts*) 0); } void CIntervalTree::DeallocNodeIntervals(TTreeNodeInts* ptr) { m_NodeIntervalsAllocator.deallocate(ptr, 1); } CIntervalTree::TTreeNodeInts* CIntervalTree::CreateNodeIntervals(void) { TTreeNodeInts* ints = new (AllocNodeIntervals())TTreeNodeInts(); #if defined(_RWSTD_VER) && !defined(_RWSTD_STRICT_ANSI) ints->m_ByX.allocation_size(16); ints->m_ByY.allocation_size(16); #endif return ints; } void CIntervalTree::DeleteNodeIntervals(TTreeNodeInts* ptr) { if ( ptr ) { ptr->~TTreeNodeInts(); DeallocNodeIntervals(ptr); } } void CIntervalTree::ClearNode(TTreeNode* node) { DeleteNodeIntervals(node->m_NodeIntervals); DeleteNode(node->m_Left); DeleteNode(node->m_Right); node->m_Left = node->m_Right = 0; } pair<double, CIntervalTree::size_type> CIntervalTree::Stat(void) const { SStat stat; stat.total = stat.count = stat.max = 0; Stat(&m_Root, stat); return make_pair(double(stat.total) / stat.count, stat.max); } void CIntervalTree::Stat(const TTreeNode* node, SStat& stat) const { if ( !node ) return; if ( node->m_NodeIntervals ) { size_type len = node->m_NodeIntervals->m_ByX.size(); ++stat.count; stat.total += len; stat.max = max(stat.max, len); } Stat(node->m_Right, stat); Stat(node->m_Left, stat); } END_NCBI_SCOPE
29.747331
78
0.609882
OpenHero
0a980d851f0981083c1bcde0b59a87844265920d
1,719
hpp
C++
include/containers/range_view.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
44
2020-10-03T21:37:52.000Z
2022-03-26T10:08:46.000Z
include/containers/range_view.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
1
2021-01-01T23:22:39.000Z
2021-01-01T23:22:39.000Z
include/containers/range_view.hpp
davidstone/bounded-integer
d4f9a88a12174ca8382af60b00c5affd19aa8632
[ "BSL-1.0" ]
null
null
null
// Copyright David Stone 2018. // 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) #pragma once #include <containers/begin_end.hpp> #include <containers/is_range.hpp> #include <containers/iter_difference_t.hpp> #include <containers/iter_value_t.hpp> #include <bounded/integer.hpp> #include <operators/bracket.hpp> #include <operators/forward.hpp> #include <iterator> #include <utility> namespace containers { template<typename Iterator, typename Sentinel = Iterator> struct range_view { using value_type = iter_value_t<Iterator>; constexpr range_view(Iterator first, Sentinel last): m_begin(std::move(first)), m_end(std::move(last)) { } constexpr explicit range_view(std::pair<Iterator, Sentinel> pair): range_view(std::move(pair).first, std::move(pair).second) { } constexpr range_view(range auto && r): range_view(containers::begin(OPERATORS_FORWARD(r)), containers::end(OPERATORS_FORWARD(r))) { } constexpr auto begin() const { return m_begin; } constexpr auto end() const { return m_end; } OPERATORS_BRACKET_SEQUENCE_RANGE_DEFINITIONS friend auto operator==(range_view, range_view) -> bool = default; private: [[no_unique_address]] Iterator m_begin; [[no_unique_address]] Sentinel m_end; }; template<typename Range> range_view(Range &&) -> range_view<decltype(containers::begin(std::declval<Range &&>()), containers::end(std::declval<Range &&>()))>; template<typename> inline constexpr auto is_range_view = false; template<typename Iterator, typename Sentinel> inline constexpr auto is_range_view<range_view<Iterator, Sentinel>> = true; } // namespace containers
25.656716
133
0.753345
davidstone
0a989e6bdbd9ec69c91af1f3073924420396ccb2
2,118
cpp
C++
src/core/src/scene/scene.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
2
2020-07-29T04:27:22.000Z
2021-10-11T01:27:43.000Z
src/core/src/scene/scene.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
null
null
null
src/core/src/scene/scene.cpp
zZnghialamZz/Ethan
e841b0a07f75022fab6634d53827c64dd1a466de
[ "Apache-2.0" ]
2
2020-08-03T03:29:28.000Z
2020-08-03T08:01:14.000Z
/** * ================================================== * _____ * __|___ |__ __ __ _ ____ ____ _ * | ___| | _| |_ | |_| || \ | \ | | * | ___| ||_ _|| _ || \ | \| | * |______| __| |__| |__| |_||__|\__\|__/\____| * |_____| * * Game Engine * ================================================== * * @file scene.cpp * @author Nghia Lam <nghialam12795@gmail.com> * * @brief * * @license Copyright 2020 Nghia Lam * * 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 "ethan/core/scene/scene.h" #include "ethan/core/graphic/camera/camera_controller.h" #include "ethan/core/graphic/renderer/renderer2D.h" #include "ethan/ecs.h" namespace Ethan { Scene::Scene(const std::string& name) : name_(name) { entity_manager_ = MakeScope<ECS::EntityManager>(); scene_camera_ = MakeShared<Camera>(CameraMode::CAMERA_2D); camera_controller_.SetCurrentCamera(scene_camera_); } Scene::~Scene() {} void Scene::Update() { // Update float dt = DeltaTime::GetSeconds(); camera_controller_.UpdateCamera(dt); // Render Renderer2D::Begin(*scene_camera_); { // NOTE(Nghia Lam): Draw Quads auto group = entity_manager_->GetEntitiesWithTypes<ECS::TransformComponent, ECS::SpriteRenderComponent>(); for (auto entity : group) { auto [transform, sprite] = group.get<ECS::TransformComponent, ECS::SpriteRenderComponent>(entity); Renderer2D::DrawQuad(transform.Transform, sprite.Color); } } Renderer2D::End(); } }
29.830986
112
0.603872
zZnghialamZz
0a99019e7a666a80348cb175b394bfc3d891f154
4,160
cpp
C++
earth_enterprise/src/fusion/rasterfuse/vipm/heap.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
2,661
2017-03-20T22:12:50.000Z
2022-03-30T09:43:19.000Z
earth_enterprise/src/fusion/rasterfuse/vipm/heap.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
1,531
2017-03-24T17:20:32.000Z
2022-03-16T18:11:14.000Z
earth_enterprise/src/fusion/rasterfuse/vipm/heap.cpp
ezeeyahoo/earthenterprise
b6cac9e6228946f2f17d1edb75e118aeb3e8e8c9
[ "Apache-2.0" ]
990
2017-03-24T11:54:28.000Z
2022-03-22T11:51:47.000Z
// Copyright 2017 Google Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #include <assert.h> #include "heap.h" ////////////////////////////////////////////////////////////////////////////// etHeap::~etHeap() { delete [] table; } ////////////////////////////////////////////////////////////////////////////// void etHeap::init(const int sz) { assert(sz != 0); delete [] table; table = new etHeapable*[sz]; size = sz; length = 0; reset(); } ////////////////////////////////////////////////////////////////////////////// void etHeap::reset() { for(unsigned int i=0;i<size;i++) table[i] = 0; length = 0; } ////////////////////////////////////////////////////////////////////////////// void etHeap::up(unsigned int i) { etHeapable *moving = table[i]; unsigned int index = i; unsigned int p = parent(i); while( index > 0 && moving->getKey() > table[p]->getKey() ) { place(table[p], index); index = p; p = parent(p); } if( index != i ) place(moving, index); } ////////////////////////////////////////////////////////////////////////////// void etHeap::down(unsigned int i) { etHeapable *moving = table[i]; unsigned int index = i; unsigned int l = left(i); unsigned int r = right(i); unsigned int largest; while( l < length ) { if( r < length && table[l]->getKey() < table[r]->getKey() ) largest = r; else largest = l; if( moving->getKey() < table[largest]->getKey() ) { place(table[largest], index); index = largest; l = left(index); r = right(index); } else break; } if( index != i ) place(moving, index); } ////////////////////////////////////////////////////////////////////////////// void etHeap::insert(etHeapable *t) { assert(!t->isInHeap() ); table[length++] = t; t->setHeapPos(length-1); up(length-1); } ////////////////////////////////////////////////////////////////////////////// void etHeap::update(etHeapable *t) { assert(t->isInHeap() ); double v = t->getKey(); unsigned int i = t->getHeapPos(); if( i > 0 && v > table[parent(i)]->getKey() ) up(i); else down(i); } ////////////////////////////////////////////////////////////////////////////// etHeapable *etHeap::extract() { if( !length ) return 0; etHeapable *dead = table[0]; table[0] = table[--length]; table[0]->setHeapPos(0); down(0); dead->resetHepeable(); assert(!dead->isInHeap() ); return dead; } ////////////////////////////////////////////////////////////////////////////// etHeapable *etHeap::remove(etHeapable *t) { if( !t->isInHeap() ) return 0; int i = t->getHeapPos(); table[i] = table[--length]; table[i]->setHeapPos(i); down(i); t->resetHepeable(); assert(!t->isInHeap() ); return t; } ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////
25.838509
78
0.377885
ezeeyahoo
0a9b18fbbb21f8edf69284f4bdc7b83cd2f811b1
1,564
hpp
C++
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/backtrace.hpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
284
2017-02-26T08:49:15.000Z
2022-03-30T21:55:37.000Z
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/backtrace.hpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
24
2017-09-05T21:02:41.000Z
2022-03-07T10:09:59.000Z
NeuKaDiS/KaDiS/external/RBC/external/tlx/tlx/backtrace.hpp
bingmann/distributed-string-sorting
238bdfd5f6139f2f14e33aed7b4d9bbffac5d295
[ "BSD-2-Clause" ]
62
2017-02-23T12:29:27.000Z
2022-03-31T07:45:59.000Z
/******************************************************************************* * tlx/backtrace.hpp * * Part of tlx - http://panthema.net/tlx * * Copyright (C) 2008-2017 Timo Bingmann <tb@panthema.net> * * All rights reserved. Published under the Boost Software License, Version 1.0 ******************************************************************************/ #ifndef TLX_BACKTRACE_HEADER #define TLX_BACKTRACE_HEADER #include <tlx/define/attribute_format_printf.hpp> #include <cstdio> namespace tlx { //! \name Stack Backtrace Printing //! \{ /*! * Print a plain hex stack backtrace of the called function to FILE* out. */ void print_raw_backtrace(FILE* out = stderr, unsigned int max_frames = 63); /*! * Print a plain hex stack backtrace of the called function to FILE* out, * prefixed with the given printf formatted output. */ void print_raw_backtrace(FILE* out, unsigned int max_frames, const char* fmt, ...) TLX_ATTRIBUTE_FORMAT_PRINTF(3, 4); /*! * Print a demangled stack backtrace of the caller function to FILE* out. * * \warning The binary has to be compiled with <tt>-rdynamic</tt> for meaningful * output. */ void print_cxx_backtrace(FILE* out = stderr, unsigned int max_frames = 63); /*! * Install SIGSEGV signal handler and output backtrace on segmentation fault. * Compile with `-rdynamic` for more useful output. */ void enable_segv_backtrace(); //! \} } // namespace tlx #endif // !TLX_BACKTRACE_HEADER /******************************************************************************/
27.438596
80
0.602941
bingmann
0a9be70b12d75382827b0693f6c54e1bc1834952
2,527
cc
C++
mysql-server/mysys/mf_fn_ext.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/mysys/mf_fn_ext.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
mysql-server/mysys/mf_fn_ext.cc
silenc3502/MYSQL-Arch-Doc-Summary
fcc6bb65f72a385b9f56debc9b2c00cee5914bae
[ "MIT" ]
null
null
null
/* Copyright (c) 2000, 2018, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2.0, as published by the Free Software Foundation. This program is also distributed with certain software (including but not limited to OpenSSL) that is licensed under separate terms, as designated in a particular file or component or in included license documentation. The authors of MySQL hereby grant you an additional permission to link the program and your derivative works with the separately licensed software that they have included with MySQL. Without limiting anything contained in the foregoing, this file, which is part of C Driver for MySQL (Connector/C), is also subject to the Universal FOSS Exception, version 1.0, a copy of which can be found at http://oss.oracle.com/licenses/universal-foss-exception. 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, version 2.0, 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 St, Fifth Floor, Boston, MA 02110-1301 USA */ /** @file mysys/mf_fn_ext.cc */ #include <string.h> #include "m_string.h" #include "my_dbug.h" #include "my_io.h" #if defined(FN_DEVCHAR) || defined(_WIN32) #include "my_sys.h" #include "mysys/mysys_priv.h" #endif /* Return a pointer to the extension of the filename. SYNOPSIS fn_ext() name Name of file DESCRIPTION The extension is defined as everything after the last extension character (normally '.') after the directory name. RETURN VALUES Pointer to to the extension character. If there isn't any extension, points at the end ASCII(0) of the filename. */ const char *fn_ext(const char *name) { #if defined(FN_DEVCHAR) || defined(_WIN32) char buff[FN_REFLEN]; size_t res_length; const char *gpos = name + dirname_part(buff, name, &res_length); #else const char *gpos = strrchr(name, FN_LIBCHAR); if (gpos == nullptr) gpos = name; #endif const char *pos = strrchr(gpos, FN_EXTCHAR); return pos ? pos : strend(gpos); } char *fn_ext(char *name) { return const_cast<char *>(fn_ext(static_cast<const char *>(name))); }
34.148649
79
0.735259
silenc3502
0a9e15b58201f9a274e83f6a202fb8234327d7e5
927
hpp
C++
gamess/libqc/src/matrix/ops.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/src/matrix/ops.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
gamess/libqc/src/matrix/ops.hpp
andremirt/v_cond
6b5c364d7cd4243686488b2bd4318be3927e07ea
[ "Unlicense" ]
null
null
null
#ifndef _MATRIX_OPS_HPP_ #define _MATRIX_OPS_HPP_ namespace matrix { template<class M> void assign(M &A, typename M::value_type s) { for (uint j = 0; j < A.size2(); ++j) { for (uint i = 0; i < A.size1(); ++i) { A(i,j) = s; } } } template<class M, class E> typename disable_if< is_arithmetic<E> >::type assign(M &A, const E &e) { for (uint j = 0; j < A.size2(); ++j) { for (uint i = 0; i < A.size1(); ++i) { A(i,j) = e(i,j); } } } template<class Matrix> void symmeterize(Matrix &A) { for (uint j = 0; j < A.size2(); ++j) { for (uint i = j+1; i < A.size1(); ++i) { A(i,j) += A(j,i); A(j,i) = A(i,j); } } } template<class Matrix> void zero(Matrix &A) { for (uint j = 0; j < A.size2(); ++j) { for (uint i = 0; i < A.size1(); ++i) { A(i,j) = typename Matrix::value_type(0); } } } } #endif /* _MATRIX_OPS_HPP_ */
19.723404
50
0.495146
andremirt
0aa01a783110b5fae6238bbfc340dc6c3d9e4006
1,543
hpp
C++
include/thectci/factory.hpp
PeterHajdu/thectci
7ffe4c7d8ccbf55490e155f93ef8637d6f9c4119
[ "MIT" ]
null
null
null
include/thectci/factory.hpp
PeterHajdu/thectci
7ffe4c7d8ccbf55490e155f93ef8637d6f9c4119
[ "MIT" ]
null
null
null
include/thectci/factory.hpp
PeterHajdu/thectci
7ffe4c7d8ccbf55490e155f93ef8637d6f9c4119
[ "MIT" ]
null
null
null
#pragma once #include <thectci/id.hpp> #include <memory> #include <cassert> #include <functional> #include <unordered_map> namespace the { namespace ctci { template < typename Base > class Creator { public: typedef std::unique_ptr< Base > base_pointer; virtual ~Creator() {} virtual base_pointer create() = 0; }; template < typename Base, typename Child > class ExactCreator : public Creator< Base > { public: typedef std::unique_ptr< Base > base_pointer; base_pointer create() override { return std::unique_ptr< Base >( new Child() ); } }; template < typename Base > class Factory { public: typedef std::unique_ptr< Base > base_pointer; typedef Creator< Base > BaseCreator; void register_creator( Id class_id, BaseCreator& base_creator ) { assert( !is_registered( class_id ) ); m_creators.emplace( std::make_pair( class_id, std::ref( base_creator ) ) ); } base_pointer create( Id class_id ) const { typename Creators::const_iterator creator_iterator( m_creators.find( class_id ) ); if ( creator_iterator == end( m_creators ) ) { return base_pointer( nullptr ); } return creator_iterator->second.get().create(); } bool is_registered( Id class_id ) const { return m_creators.find( class_id ) != m_creators.end(); } private: typedef std::reference_wrapper< BaseCreator > CreatorReference; typedef std::unordered_map< Id, CreatorReference > Creators; Creators m_creators; }; } }
21.136986
88
0.668179
PeterHajdu
0aa179af3f6ec42779f78f69d3ab00914dff12e0
4,840
cpp
C++
rotor.cpp
101010b/LEDBall
01d11100262e2cf73d337aad02013044cfc32475
[ "Apache-2.0" ]
null
null
null
rotor.cpp
101010b/LEDBall
01d11100262e2cf73d337aad02013044cfc32475
[ "Apache-2.0" ]
null
null
null
rotor.cpp
101010b/LEDBall
01d11100262e2cf73d337aad02013044cfc32475
[ "Apache-2.0" ]
null
null
null
#include <arduino.h> #include <stdint.h> #include "rotor.h" const uint8_t rowcos[19]={0,44,87,127,164,195,221,240,251,255,251,240,221,195,164,128,87,44,0}; const uint8_t colexp1[60]={255,246,238,230,222,215,208,201,194,187,181,175,169,164,158,153,148,143,138,133,129,125,120,116,113,109,105,102,98,95,92,89, 86,83,80,77,75,72,70,67,65,63,61,59,57,55,53,51,50,48,46,45,43,42,40,39,38,36,35,34}; const uint8_t colexp2[60]={255,234,215,197,181,166,153,140,129,118,109,100,92,84,77,71,65,60,55,50,46,43,39,36,33,30,28,25,23,21,20,18, 16,15,14,13,12,11,10,9,8,7,7,6,6,5,5,4,4,4,3,3,3,2,2,2,2,2,1,1}; const uint8_t colexp3[60]={255,215,181,153,129,109,92,77,65,55,46,39,33,28,23,20,16,14,12,10,8,7,6,5,4,3,3,2,2,1,1,1, 1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; const uint8_t colexp4[60]={255,181,129,92,65,46,33,23,16,12,8,6,4,3,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; const uint8_t colexp1b[60]={0,46,85,119,147,171,191,207,221,231,239,246,250,253,254,255,254,252,250,247,244,240,236,231,227,222,217,212,206,201,196,191, 185,180,175,170,165,160,156,151,146,142,137,133,129,125,121,117,113,110,106,103,99,96,93,90,87,84,81,79}; const uint8_t colexp2b[60]={0,95,161,205,233,248,255,254,250,242,232,220,208,196,183,171,159,148,137,127,117,108,100,92,85,78,72,66,61,56,51,47, 43,40,37,34,31,28,26,24,22,20,18,17,15,14,13,12,11,10,9,8,8,7,6,6,5,5,4,4}; const uint8_t colexp3b[60]={0,161,233,255,250,232,208,183,159,137,117,100,85,72,61,51,43,37,31,26,22,18,15,13,11,9,8,6,5,4,4,3, 2,2,2,1,1,1,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; const uint8_t colexp4b[60]={0,237,255,212,162,120,87,62,44,31,22,16,11,8,5,4,2,2,1,1,0,0,0,0,0,0,0,0,0,0,0,0, 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0}; typedef const uint8_t *colexp_t; const colexp_t colexp[8] = {colexp1, colexp2, colexp3, colexp4, colexp1b, colexp2b, colexp3b, colexp4b}; rotor::rotor():effect("Rotor",0) { rotv = newintparam("v", -50, 50, 25); col = newcolparam("Col", 255, 255, 255); useglobalcol = newboolparam("global", true); decayr = newintparam("decayr", 0, 7, 3); decayg = newintparam("decayg", 0, 7, 3); decayb = newintparam("decayb", 0, 7, 1); globalcol = NULL; ofs=0; rotdelay=0; xtabler = (uint8_t*) malloc(LEDW); xtableg = (uint8_t*) malloc(LEDW); xtableb = (uint8_t*) malloc(LEDW); recalcshape(); } void rotor::recalcshape() { uint8_t r,g,b; if (useglobalcol->d.b.val && globalcol) { r = globalcol->r; g = globalcol->g; b = globalcol->b; } else { r = col->d.c.r; g = col->d.c.g; b = col->d.c.b; } const uint8_t *exptabler = colexp[decayr->d.i.val]; const uint8_t *exptableg = colexp[decayg->d.i.val]; const uint8_t *exptableb = colexp[decayb->d.i.val]; int dir = (rotv->d.i.val<0)?-1:1; for (int i=0;i<LEDW;i++) { int x = (i + ofs) % LEDW; uint16_t xr = (dir==1)?exptabler[x]:exptabler[LEDW-1-x]; uint16_t xg = (dir==1)?exptableg[x]:exptableg[LEDW-1-x]; uint16_t xb = (dir==1)?exptableb[x]:exptableb[LEDW-1-x]; xtabler[i] = (xr * r) / 256; xtableg[i] = (xg * g) / 256; xtableb[i] = (xb * b) / 256; } for (int i=0;i<LEDS;i++) { int x = phitable[i]; int y = thetatable[i]; list->r[i] = ((uint16_t)xtabler[x] * rowcos[y]) / 256; list->g[i] = ((uint16_t)xtableg[x] * rowcos[y]) / 256; list->b[i] = ((uint16_t)xtableb[x] * rowcos[y]) / 256; } /* for (int u=0;u<LEDW;u++) { int x=(u + ofs) % LEDW; uint16_t xr = (dir==1)?exptabler[x]:exptabler[LEDW-1-x]; uint16_t xg = (dir==1)?exptableg[x]:exptableg[LEDW-1-x]; uint16_t xb = (dir==1)?exptableb[x]:exptableb[LEDW-1-x]; uint16_t vr = (xr * r) / 256; uint16_t vg = (xg * g) / 256; uint16_t vb = (xb * b) / 256; for (int y=0;y<LEDH;y++) { int q = y * LEDW + u; field->r[q] = (vr * rowcos[y]) / 256; field->g[q] = (vg * rowcos[y]) / 256; field->b[q] = (vb * rowcos[y]) / 256; } }*/ } void rotor::updateparams() { //recalcshape(); } void rotor::updateparam(param_t *param) { //if ((param == rotv) || (param == decayr)|| (param == decayg)|| (param == decayb)) // recalcshape(); } void rotor::setGlobalCol(colorgen *_col) { globalcol = _col; } void rotor::tick() { recalcshape(); int rv = rotv->d.i.val; if (rv == 0) return; int dir = (rv < 0)?-1:1; rv = (rv < 0)?-rv:rv; if (rv < 20) { int spd = 21 - rv; if (rotdelay >= spd) { if (dir > 0) { ofs++; if (ofs >= LEDW) ofs-=LEDW; } else { ofs--; if (ofs < 0) ofs+=LEDW; } rotdelay = 0; } rotdelay++; } else { int spd = rv - 19; if (dir > 0) { ofs+=spd; if (ofs >= LEDW) ofs-=LEDW; } else { ofs-=spd; if (ofs < 0) ofs+=LEDW; } } }
34.326241
152
0.578926
101010b
0aa42c79a0f46d9b2c1477582c12c3a27d66dff9
18,768
cpp
C++
src/DE_Scene.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
1
2018-09-20T10:01:30.000Z
2018-09-20T10:01:30.000Z
src/DE_Scene.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
null
null
null
src/DE_Scene.cpp
daher-alfawares/xr.desktop
218a7cff7a9be5865cf786d7cad31da6072f7348
[ "Apache-2.0" ]
null
null
null
//C++ /* ---------------------------------------------------- The Desktop Project ------------------ Copyright 2004 Daher Alfawares 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 "DE_Config.h" #ifdef DE_SCENE #undef DE_SCENE #include "DShared.H" #include "DSys.H" #include "DGL.H" #include "DUI_Main.H" #include "Demo_Camera.h" #include "Demo_Effect.h" #include "Demo_Scene.h" #include "Demo_Registery.h" // Demos #include "DE_IntroScene.h" ////////////////////////////////////////// // Scene Objects namespace objects { enum objects_e { no_object, wall_bottom, wall_front, wall_left, wall_right, wall_back }; } #include "DE_Lighting_fx.h" #include "DE_TerrainScene.h" #include "DE_GetMrFrench.h" //#include "DE_CG.h" ////////////////////////////////////////// // Shared variables DSys::Var_float gl_fov ("gl_Fov", "90"); DSys::Var_float gl_near ("gl_Near", "2"); DSys::Var_float gl_far ("gl_Far", "25"); DSys::Var_bool gl_drawFaces ("gl_drawfaces", "1"); DSys::Var_bool gl_avi ("gl_avi", "0"); DSys::Var_bool r_drawFPS ("r_drawFPS", "1"); DSys::Var_bool r_reflections ("r_reflections", "1"); DSys::Var_bool r_loopDemo ("r_loopDemo", "1"); DSys::Var_bool r_drawTimer ("r_drawTimer", "0"); DSys::Var_bool r_modelBounds ("r_modelBounds", "0"); DSys::Var_bool r_Lighting ("r_lighting", "0"); DSys::Var_bool r_VSync ("r_VSync", "1"); DSys::Var_int g_speed ("g_speed", "1"); DSys::Var_int g_cameraMotion ("g_cameraMotion", "0"); /////////////////////////////////////////// // User Interface Declerations void UI_Init(); void UI_OnLeftClick(int button); void UI_OnRightClick(int button); void UI_Update(float msec); void UI_OnKey(char key); void UI_Render(); ////////////////////////////////////////// // Scene Mode enum HScene_Mode { MODE_PLAYBACK, MODE_UI } SceneMode; ////////////////////////////////////////// // Macros #define AT_KEY_DOWN(key) if(DSys::Input::KeyDown((key))) #define AT_KEY_CHAR(key) if(DSys::Input::KeyChar((key))) #define CHECK_QUIT { DSys::Input::Update();\ if(DSys::Input::KeyDown(DIK_ESCAPE)){\ DSys::SendConsoleCommand("quit");\ DMacro_TraceLeave();\ return false;}\ } ////////////////////////////////////////// // Scene Objects static DGL::LoadingScreen g_loadingScreen; static DAudio::Sound2D g_bakmusic; static DGL::ParticleEngine g_fireEngine; static DGL::FadeScreen g_fadeOut; static DGL::FadeScreen g_fadeIn; static DGL::UserMessage g_userMessage; static DGL::Font3D g_font3D; static DGL::Font g_font; static GLFT_Font g_fontft; static DGL::Texture g_refMap; static DGL::Texture g_menuBack; static float g_timeCounter; static DGL::Camera g_camera; static DGL::Train g_train; static bool g_trainUpdate; static bool g_bQuitting; static Horror::IntroScene *g_introScene; static DGL::Lighting_fx *g_lightingScene; static Horror::TerrainScene *g_terrainScene; static GetMrFrench::Game *g_mrFrenchGame; //static cg::cgDemo *g_cgDemo; static Demo::Registery g_registery; ////////////////////////////////////////// // Final Scene Functions /* Add New Console Commands Here */ void AddConsoleCommands(){ } bool Init(void){ DMacro_TraceEnter(Init); // // OpenGL // DGL::Font::Init(); // Texture glEnable( GL_TEXTURE_2D); g_loadingScreen.Init(); CHECK_QUIT; g_loadingScreen.SetStage( 5, "Initializing OpenGL ..."); DGL::InitQuadrics(); DSys::Physics::Init(); DGL::Extensions::Init(); // g_userMessage.SetFont(g_font); if(DGL::Extensions::IsEnabled_WGL_EXT_swap_control()){ DSys::Logger::Print("Setting monitor v-sync ..."); wglSwapIntervalEXT(r_VSync); } if(DGL::Extensions::IsEnabled_GL_EXT_clip_volume_hint()){ DSys::Logger::Print("Enabling volume clipping ..."); glHint( GL_CLIP_VOLUME_CLIPPING_HINT_EXT, GL_NICEST); } if(DGL::Extensions::IsEnabled_GL_EXT_point_parameters()){ DSys::Logger::Print("Setting point parameters ..."); // glPointSize(5); // glPointParameterfEXT( GL_POINT_SIZE_MIN_EXT, 1); // glPointParameterfEXT( GL_POINT_SIZE_MAX_EXT, 10); // glPointParameterfEXT( GL_POINT_FADE_THRESHOLD_SIZE_EXT, 50); // glPointParameterfEXT( GL_DISTANCE_ATTENUATION_EXT, 60); } // Depth buffer glClearDepth( 20.0f); glEnable( GL_DEPTH_TEST ); glDepthFunc( GL_LEQUAL ); #if 0 if(DGL::Extensions::IsEnabled_GL_NV_texgen_reflection()){ glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_NV); glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_REFLECTION_MAP_NV); } else { glTexGeni( GL_S, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); glTexGeni( GL_T, GL_TEXTURE_GEN_MODE, GL_SPHERE_MAP); } #endif // shade model // glShadeModel(GL_SMOOTH); // clear color // glClearColor(0,0,0,1); // hints // glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST); // glHint( GL_POINT_SMOOTH_HINT, GL_NICEST); // glHint( GL_LINE_SMOOTH_HINT, GL_NICEST); // glHint( GL_POLYGON_SMOOTH_HINT, GL_NICEST); // polygon mode // glPolygonMode( GL_FRONT_AND_BACK, GL_FILL ); // Back Face Is Solid glEnable( GL_LIGHTING ); // glDisable( GL_CULL_FACE ); g_font.Create( "Font"); g_fontft.open("arial.ttf",16); glLoadIdentity(); // // Media // CHECK_QUIT; g_loadingScreen.SetStage(10, "Loading Media..."); #ifndef _DEBUG if(!DSys::sv_bDeveloper) // g_bakmusic.Load( "sounds/music/The Prophecy.mp3"); // g_bakmusic.Load( "sounds/music/Lothlorien.mp3"); // g_bakmusic.Load( "sounds/music/Inshallah.mp3"); #endif // User interface CHECK_QUIT; g_loadingScreen.SetStage(20, "Loading User Interface..."); UI_Init(); CHECK_QUIT; g_loadingScreen.SetStage(30, "Building Particle Systems ..."); g_fireEngine.Init( Vector(0,-5,-20), Vector(0,2,0), Vector(0,0,0), DGL::Color::ColorYellow(), DGL::Color::ColorRed(), 0.5f, 3, 0); CHECK_QUIT; g_loadingScreen.SetStage(50, "Building 3D Font..."); // g_font3D.Build("Gaze Bold", DSys::Window::GetDC()); /*/ CHECK_QUIT; g_loadingScreen.SetStage(70, "Initializing MrFrench..."); g_mrFrenchGame = new GetMrFrench::Game; g_registery.Register(g_mrFrenchGame, NULL); // CHECK_QUIT; g_loadingScreen.SetStage(60, "Initializing Intro Scene ..."); g_introScene = new Horror::IntroScene; g_registery.Register(g_introScene, NULL); /**/ CHECK_QUIT; g_loadingScreen.SetStage(75, "Initializing desktop ..."); g_lightingScene = new DGL::Lighting_fx; g_registery.Register( g_lightingScene, DSys::sv_bDeveloper ? NULL : "lfx"); /*/ CHECK_QUIT; g_loadingScreen.SetStage(80, "Initializing Terrain Scene ..."); g_terrainScene = new Horror::TerrainScene; g_registery.Register(g_terrainScene, DSys::sv_bDeveloper ? NULL : "TerrainScene"); // CHECK_QUIT; g_loadingScreen.SetStage(93, "Initializing cg shaders demo..."); g_cgDemo = new cg::cgDemo; g_registery.Register(g_cgDemo, NULL); /**/ CHECK_QUIT; g_loadingScreen.SetStage(95, "Initializing Effects..."); // fade effect g_fadeIn.Init( DGL::Color(0.0f,0.0f,0.0f,1.0f), DGL::Color(0.0f,0.0f,0.0f,0.0f), 1000); g_fadeOut.Init( DGL::Color(0.0f,0.0f,0.0f,0.0f), DGL::Color(0.0f,0.0f,0.0f,1.0f), 2000); // g_refMap.Build("textures/ref.tga"); // g_menuBack.Build("textures/menuBack.jpg"); CHECK_QUIT; // g_loadingScreen.SetStage(100, "Awaiting Snapshot..."); /////////////// // now start the back music // g_bakmusic.Play(); /////////////// // setup initial camera location g_camera.Set( g_camera.POSITION, Vector( 0, 4, -4 ) ); DMacro_TraceLeave(); return true; } void Update(float msec){ DMacro_TraceEnter(Update); DSys::Input::Update(); DSys::Physics::Update(msec/1000.0f); /* AT_KEY_CHAR(DIK_F10) DSys::SendConsoleCommand("quit"); if( DSys::sv_bDeveloper ) { AT_KEY_CHAR(DIK_ESCAPE) (void ( SceneMode == MODE_UI ? SceneMode = MODE_PLAYBACK : SceneMode = MODE_UI ) ); } else { AT_KEY_CHAR(DIK_ESCAPE) g_bQuitting = true; } */ if(SceneMode == MODE_PLAYBACK) { if(DSys::Input::KeyDown(DIK_LALT) || DSys::Input::KeyDown(DIK_RALT)){ //////////////// //************// //* ALT KEYS *// //************// //////////////// if(DSys::sv_bDeveloper) { AT_KEY_CHAR(DIK_A){ Vector p,d; g_camera.Get(g_camera.POSITION, p); g_camera.Get(g_camera.DIRECTION, d); g_train.PushNode(p,d); } AT_KEY_CHAR(DIK_Z){ DSys::Logger::Print("Turning camera train: %s", g_trainUpdate ? "OFF" : "ON"); g_trainUpdate = !g_trainUpdate; } AT_KEY_CHAR(DIK_S){ static int i; g_train.Dump(va("autosave%d", i++)); } AT_KEY_CHAR(DIK_C){ g_train.Destroy(); } AT_KEY_CHAR(DIK_X){ g_train.RemoveLast(); } } } else { /////////////////// //***************// //* NORMAL KEYS *// //***************// /////////////////// if(!gl_avi){ AT_KEY_CHAR(DIK_F12) DSys::SendConsoleCommand("screenshot"); } else { DSys::SendConsoleCommand("screenshot"); } if(DGL::r_freeCam) { ///////////// // Camera movement AT_KEY_DOWN(DIK_W) g_camera.MoveCameraFarward((DSys::Input::KeyValue(DIK_W)/10000.0f) * g_speed.floatval() * msec ); AT_KEY_DOWN(DIK_S) g_camera.MoveCameraFarward(-(DSys::Input::KeyValue(DIK_S)/10000.0f) * g_speed.floatval() * msec ); AT_KEY_DOWN(DIK_D) g_camera.MovePlaneRight((DSys::Input::KeyValue(DIK_D)/10000.0f) * g_speed.floatval() * msec ); AT_KEY_DOWN(DIK_A) g_camera.MovePlaneRight(-(DSys::Input::KeyValue(DIK_A)/10000.0f) * g_speed.floatval() * msec ); AT_KEY_DOWN(DIK_SPACE) g_camera.MovePlaneUp((DSys::Input::KeyValue(DIK_SPACE)/10000.0f) * g_speed.floatval() * msec ); AT_KEY_DOWN(DIK_C) g_camera.MovePlaneUp(-(DSys::Input::KeyValue(DIK_C)/10000.0f) * g_speed.floatval() * msec ); g_camera.RotateRight( DSys::Input::MouseXDelta() /200.0f ); g_camera.RotateUp( -DSys::Input::MouseYDelta() /200.0f ); } } g_registery.Update(msec); /* if(g_registery.Done()) DSys::SendConsoleCommand("quit"); if(DSys::sv_bDeveloper) { if(g_trainUpdate){ Vector p,d; g_train.Update(msec,p,d); g_camera.Set(g_camera.POSITION, p); g_camera.Set(g_camera.DIRECTION, d); } } */ } else if( SceneMode == MODE_UI ){ // user interface should think now UI_Update(msec); } /////////////////////// //*******************// //* Non-Key Related *// //*******************// /////////////////////// // static float sceneTime; // if(sceneTime>2){ // sceneTime += msec/1000.0f; // g_userMessage.ShowMessage("Master Is Teh Tant = 6an6", 3,g_userMessage.STYLE_POPUP,6,DGL::Color::ColorGray()); // } // g_fireEngine.Update(msec); // g_userMessage.Update(msec); // g_timeCounter += msec/50.0f; // g_fadeIn.Update(msec); // if(g_bQuitting) // g_fadeOut.Update(msec); DMacro_TraceLeave(); } void Render3D(){ DMacro_TraceEnter(Render3D); if( r_Lighting ) glEnable( GL_LIGHTING ); else glDisable( GL_LIGHTING ); // render the scene // if(DSys::sv_bDeveloper) // g_camera.Setup(); g_registery.Render(); DSys::Physics::Render(); DMacro_TraceLeave(); } void Render2D(float msec){ // all 2d drawings happens here DMacro_TraceEnter(Render2D); DGL::Color::ColorWhite().MakeCurrent(); DGL::MatrixOp::Ortho::Begin(); //============================================================== if(r_drawFPS.intval()) { g_font.SetStyle(g_font.STYLE_SHADOWS|g_font.STYLE_RIGHT); g_font.SetColor(DGL::Color::ColorGray()); // g_font.Print(638,468, "%ifps", DGL::GetFPS(msec)); std::stringstream str; str << DGL::GetFPS(msec) << " fps"; g_fontft.drawText(10,10, str.str() ); } if(r_drawTimer.intval()){ static float totaltime; static char *timer; totaltime+= msec; g_font.SetStyle(g_font.STYLE_SHADOWS|g_font.STYLE_RIGHT); g_font.SetColor(DGL::Color::ColorGray()); g_font.Print(10, 20, "%s", D_Msec2String(totaltime)); } // g_font.SetColor( DGL::Color::ColorCyan()); // g_font.SetStyle( g_font.STYLE_SHADOWS|g_font.STYLE_LEFT); // g_font.Print( 20, 460, "Hello %s", DSys::sv_sUserName.strval()); // g_font.Print( 20, 470, "DaherEngine \"%s\"", SceneTitle.strval()); if(SceneMode == MODE_UI) { UI_Render(); } else { // g_userMessage.Render(); // g_fadeIn.Render(); // if(g_bQuitting) // if(!g_fadeOut.Render()) // DSys::SendConsoleCommand("quit"); } //=========================================================== DGL::MatrixOp::Ortho::End(); DMacro_TraceLeave(); } void Shutdown(){ g_registery.Destroy(); delete g_introScene; delete g_terrainScene; // delete g_cgDemo; DUI::Destroy(); g_bakmusic.Destroy(); g_refMap.Delete(); g_menuBack.Delete(); } ////////////////////////// // User Interface /* Add UI Button ID Here */ enum UI_Button_e { UIB_CONTINUE, // continues to the scene UIB_RESTART_CURRENT,// restarts the current scene UIB_RESTART_ALL, // restarts the whole demo UIB_END_CURRENT, // ends the current scene (skip) UIB_START_MUSIC, // starts music UIB_CONSOLE, // show console UIB_PUSH_CURRENT, // stores the current camera node UIB_REMOVE_LAST, // remove the last node UIB_TOGGLE_TRAIN, // toggles camera train UIB_SAVE_TRAIN, // saves train data UIB_CLEAR_TRAIN, // clears train data UIB_EXIT, // exits scene UIB_NUMBER }; static DUI_MenuButton ui_buttons[ UIB_NUMBER]; #define MENU_Y 200 #define BUTTON_H 15 #define BUTTON_X 320 #define BUTTON_Y(id) MENU_Y - (id) * BUTTON_H void UI_Init(){ DUI::Init(); DUI::CreateObject( &ui_buttons[UIB_CONTINUE], "Start Scene", BUTTON_X, BUTTON_Y(UIB_CONTINUE), 60, 30, "CONTINUE"); DUI::CreateObject( &ui_buttons[UIB_RESTART_CURRENT], "Restart Current", BUTTON_X, BUTTON_Y(UIB_RESTART_CURRENT), 60, 30, "RESTART CURRENT"); DUI::CreateObject( &ui_buttons[UIB_RESTART_ALL], "Restart Demo", BUTTON_X, BUTTON_Y(UIB_RESTART_ALL), 60, 30, "RESTART ALL"); DUI::CreateObject( &ui_buttons[UIB_END_CURRENT], "End Current", BUTTON_X, BUTTON_Y(UIB_END_CURRENT), 60, 30, "END CURRENT"); DUI::CreateObject( &ui_buttons[UIB_START_MUSIC], "Play", BUTTON_X, BUTTON_Y(UIB_START_MUSIC), 60, 30, "PLAY MUSIC"); DUI::CreateObject( &ui_buttons[UIB_CONSOLE], "Console", BUTTON_X, BUTTON_Y(UIB_CONSOLE), 60, 30, "TOGGLE CONSOLE"); DUI::CreateObject( &ui_buttons[UIB_EXIT], "Exit", BUTTON_X, BUTTON_Y(UIB_EXIT), 60, 30, "EXIT TO SYSTEM"); DUI::CreateObject( &ui_buttons[UIB_PUSH_CURRENT], "Push Current", BUTTON_X, BUTTON_Y(UIB_PUSH_CURRENT), 60, 30, "PUSH CURRENT", DSys::sv_bDeveloper); DUI::CreateObject( &ui_buttons[UIB_REMOVE_LAST], "Remove Last", BUTTON_X, BUTTON_Y(UIB_REMOVE_LAST), 60, 30, "REMOVE LAST", DSys::sv_bDeveloper); DUI::CreateObject( &ui_buttons[UIB_TOGGLE_TRAIN], "Toggle Train", BUTTON_X, BUTTON_Y(UIB_TOGGLE_TRAIN), 60, 30, "TOGGLE TRAIN", DSys::sv_bDeveloper); DUI::CreateObject( &ui_buttons[UIB_SAVE_TRAIN], "Save Train", BUTTON_X, BUTTON_Y(UIB_SAVE_TRAIN), 60, 30, "SAVE TRAIN", DSys::sv_bDeveloper); DUI::CreateObject( &ui_buttons[UIB_CLEAR_TRAIN], "Clear Train", BUTTON_X, BUTTON_Y(UIB_CLEAR_TRAIN), 60, 30, "CLEAR TRAIN", DSys::sv_bDeveloper); } void UI_OnLeftClick(int button){ switch (button) { case UIB_CONTINUE: SceneMode = MODE_PLAYBACK; break; case UIB_RESTART_CURRENT: g_registery.RestartCurrent(); SceneMode = MODE_PLAYBACK; break; case UIB_RESTART_ALL: g_registery.RestartAll(); SceneMode = MODE_PLAYBACK; break; case UIB_END_CURRENT: g_registery.EndCurrent(); SceneMode = MODE_PLAYBACK; break; case UIB_START_MUSIC: // Play(&g_bakmusic, 1); break; case UIB_CONSOLE: DSys::SendConsoleCommand("toggle"); break; case UIB_EXIT: { #ifdef _DEBUG DSys::SendConsoleCommand("quit"); #endif g_bQuitting = true; SceneMode = MODE_PLAYBACK; g_userMessage.ShowMessage("Good Bye",3,g_userMessage.STYLE_POPUP,3,DGL::Color::ColorGray()); } break; case UIB_PUSH_CURRENT: { g_userMessage.ShowMessage("Node Pushed", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan()); Vector p,d; g_camera.Get(g_camera.POSITION, p); g_camera.Get(g_camera.DIRECTION, d); g_train.PushNode(p,d); SceneMode = MODE_PLAYBACK; } break; case UIB_REMOVE_LAST: { if(g_train.RemoveLast()) g_userMessage.ShowMessage("Last Removed", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan()); else g_userMessage.ShowMessage("Error: No more nodes", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorRed()); SceneMode = MODE_PLAYBACK; } break; case UIB_TOGGLE_TRAIN: { DSys::Logger::Print("Turning camera train: %s", g_trainUpdate ? "OFF" : "ON"); g_userMessage.ShowMessage("Train %s", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan(), g_trainUpdate? "OFF" : "ON"); g_trainUpdate = !g_trainUpdate; SceneMode = MODE_PLAYBACK; } break; case UIB_SAVE_TRAIN: { static int i; g_train.Dump(va("autosave%d", i)); g_userMessage.ShowMessage("Saved to %s", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan(), va("autosave%d", i++)); SceneMode = MODE_PLAYBACK; } break; case UIB_CLEAR_TRAIN: { g_userMessage.ShowMessage("Train Cleared", 2, g_userMessage.STYLE_FADE,2,DGL::Color::ColorCyan()); g_train.Destroy(); SceneMode = MODE_PLAYBACK; } break; } } void UI_OnRightClick(int button){ } void UI_Update(float msec) { static int i; static bool MouseLeftClicked; static bool MouseRightClicked; MouseLeftClicked = DSys::Input::MouseChar(0); MouseRightClicked= DSys::Input::MouseChar(1); DUI::MouseMoved(DSys::Input::MouseXDelta(), DSys::Input::MouseYDelta()); for(i=0; i< UIB_NUMBER; i++){ DUI::SelectObject(&ui_buttons[i]); DUI::CheckMouseOver(msec); if(MouseLeftClicked) if(DUI::OnMouseLeftClick()) UI_OnLeftClick(i); if(MouseRightClicked) if(DUI::OnMouseRightClick()) UI_OnRightClick(i); } } void UI_OnKey(char key){ static int i; for(i=0; i< UIB_NUMBER; i++){ DUI::SelectObject(&ui_buttons[i]); DUI::OnKey(key); } } void UI_Render(){ static int i; for(i=0; i< UIB_NUMBER; i++){ DUI::SelectObject(&ui_buttons[i]); DUI::RenderObject(); } DUI::MouseRender(); for(i=0; i< UIB_NUMBER; i++){ DUI::SelectObject(&ui_buttons[i]); DUI::RenderObjectToolTip(); } } #endif // DE_SCENE
25.85124
150
0.662671
daher-alfawares
0aa542229e1e710e5b5af1b4ee47d67503952136
33,815
cpp
C++
dynamic_mapping/src/main.cpp
tuw-cpsg/dynamic_mapping
12c5c9a9e66e16cb451c457d46a4d6cab5e2213b
[ "CC0-1.0" ]
9
2017-12-17T07:43:15.000Z
2021-10-10T15:03:39.000Z
dynamic_mapping/src/main.cpp
tuw-cpsg/dynamic_mapping
12c5c9a9e66e16cb451c457d46a4d6cab5e2213b
[ "CC0-1.0" ]
null
null
null
dynamic_mapping/src/main.cpp
tuw-cpsg/dynamic_mapping
12c5c9a9e66e16cb451c457d46a4d6cab5e2213b
[ "CC0-1.0" ]
6
2016-01-27T03:40:58.000Z
2021-06-15T08:12:14.000Z
#include "ros/ros.h" #include <tf/transform_listener.h> #include <tf/transform_broadcaster.h> #include "std_msgs/String.h" #include <signal.h> #include <termios.h> #include "nav_msgs/GetMap.h" #include "dynamic_mapping/GetDynamicMap.h" #include "nav_msgs/MapMetaData.h" #include <nav_msgs/OccupancyGrid.h> #include <sensor_msgs/LaserScan.h> #include "dynamic_mapping/DynamicGrid.h" #include "dynamic_mapping/ExportMap.h" #include <geometry_msgs/PoseWithCovarianceStamped.h> #include <geometry_msgs/PolygonStamped.h> #include <nav_msgs/GridCells.h> #include <math.h> #include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <fstream> #include "ros/console.h" #include "image_loader.h" #include "nav_msgs/MapMetaData.h" #include "yaml-cpp/yaml.h" #include "mapping.h" #include <SDL/SDL_image.h> //#define DEBUG using namespace std; nav_msgs::OccupancyGrid::ConstPtr map_; nav_msgs::OccupancyGrid::ConstPtr slam_map_; class DynamicMapping { public: DynamicMapping(tf::TransformListener *listener) { tf_listener = listener; double res = 0.0; std::string mapfname = ""; double origin[3]; int negate; uint32_t map_array_size; uint32_t *dynamic_imp; double occ_th, free_th; ros::NodeHandle nh("~"); /* * read command line params */ // yaml file to be importet (map import) nh.param("file_name", fname, std::string("")); // size of the area to check if there are unknown pixels arround a pixel nh.param("area_size", area_size, 10); // size of the area to check if there are free pixels arround a pixel nh.param("free_area_size", free_area_size, 3); // weight factor map_weight = dyn_map / slam_map at the map merging // near to 1 means the dyn_map pixel have more impact on the merged map // near to 0 means the slam_map pixel have more impact on the merged map nh.param("map_weight", map_weight, 0.8); // windows size for the deltation algorithm // bigger value leads to more delation nh.param("dilate_size", dilate_size, 5); // dynamic_weight for dynamic rate calculation nh.param("dynamic_weight", dynamic_weight, 0.8); // dynamic_time_max for calculating dynamic areas in milliseconds //nh.param("dynamic_time_max", dynamic_time_max, 600000); // 10 minutes nh.param("dynamic_time_max", dynamic_time_max, 60000); // 1 minutes // dynamic_remove_time for resetting dynamic areas in milliseconds nh.param("dynamic_remove_time", dynamic_remove_time, 86400000); // 1 day // time_period for updating dynamic_time values in milliseconds nh.param("time_period", time_period, 5000); // hysteresis for calculating the trend // set this to 1 or higher to avoid extrema caused by measurement errors nh.param("hysteresis", hysteresis, 0); // laser_map topic usage // set this to 1 to use the laser_map topic instead of the probability for generating dynamic areas nh.param("laser_map", use_laser_map, 1); init_dynamic_trend = true; init_dynamic_time = true; deprecated = (res != 0); if(strcmp(fname.c_str(), "") != 0) { map_is_imported = true; ROS_INFO("Starting import of map '%s'... \n", fname.c_str()); if (!deprecated) { std::ifstream fin(fname.c_str()); if (fin.fail()) { ROS_ERROR("Map_import could not open %s.", fname.c_str()); exit(-1); } YAML::Parser parser(fin); YAML::Node doc; parser.GetNextDocument(doc); try { doc["resolution"] >> res; } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain a resolution tag or it is invalid."); exit(-1); } try { doc["negate"] >> negate; } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain a negate tag or it is invalid."); exit(-1); } try { doc["map_array_size"] >> map_array_size; dynamic_imp = (uint32_t*) malloc(map_array_size * sizeof(uint32_t)); } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain a negate tag or it is invalid."); exit(-1); } try { const YAML::Node& dynamics = doc["dynamic"]; for(int i = 0; i < dynamics.size(); i++) { dynamics[i] >> dynamic_imp[i]; } ROS_INFO("dynamic value import successful\n"); } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain a dynamic tag or it is invalid."); exit(-1); } try { if(const YAML::Node *trend= doc.FindValue("dynamic_trend")) { int32_t *dynamic_tmp = (int32_t*) malloc(map_array_size * sizeof(int32_t)); dynamic_trend = (int8_t*) malloc(map_array_size * sizeof(int8_t)); for(int i = 0; i < (*trend).size(); i++) { (*trend)[i] >> dynamic_tmp[i]; dynamic_trend[i] = (int8_t) dynamic_tmp[i]; } init_dynamic_trend = false; ROS_INFO("dynamic_trend import successful\n"); } } catch (YAML::InvalidScalar) { ROS_ERROR("The file does not contain a dynamic_trend tag or it is invalid."); exit(-1); } try { if(const YAML::Node *time = doc.FindValue("dynamic_time")) { dynamic_time = (uint32_t*) malloc(map_array_size * sizeof(uint32_t)); for(int i = 0; i < (*time).size(); i++) { (*time)[i] >> dynamic_time[i]; } init_dynamic_time = false; } ROS_INFO("dynamic_time import successful\n"); } catch (YAML::InvalidScalar) { ROS_ERROR("TThe file does not contain a dynamic_time tag or it is invalid."); exit(-1); } try { doc["occupied_thresh"] >> occ_th; } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain an occupied_thresh tag or it is invalid."); exit(-1); } try { doc["free_thresh"] >> free_th; } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain a free_thresh tag or it is invalid."); exit(-1); } try { doc["origin"][0] >> origin[0]; doc["origin"][1] >> origin[1]; doc["origin"][2] >> origin[2]; } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain an origin tag or it is invalid."); exit(-1); } try { doc["image"] >> mapfname; if(mapfname.size() == 0) { ROS_ERROR("The image tag cannot be an empty string."); exit(-1); } if(mapfname[0] != '/') { // dirname can modify what you pass it char* fname_copy = strdup(fname.c_str()); mapfname = std::string(dirname(fname_copy)) + '/' + mapfname; free(fname_copy); } } catch (YAML::InvalidScalar) { ROS_ERROR("The map does not contain an image tag or it is invalid."); exit(-1); } } else { nh.param("negate", negate, 0); nh.param("occupied_thresh", occ_th, 0.65); nh.param("free_thresh", free_th, 0.196); mapfname = fname; origin[0] = origin[1] = origin[2] = 0.0; } ROS_INFO("Loading map from \"%s\"", fname.c_str()); FILE* file = fopen(fname.c_str(), "r"); char buf[512]; size_t nread; if(file) { while((nread = fread(buf, 1, sizeof(buf), file)) > 0) fwrite(buf, 1, nread, stdout); } loadMapFromFile(&dyn_map_import,mapfname.c_str(),res,negate,occ_th,free_th, origin, dynamic_imp); dyn_map_import.map.info.map_load_time = ros::Time::now(); dyn_map_import.map.header.frame_id = "dyn_map"; dyn_map_import.map.header.stamp = ros::Time::now(); dyn_map_import.map.dynamic_time_max = dynamic_time_max; ROS_INFO("Read a %d X %d map @ %.3lf m/cell", dyn_map_import.map.info.width, dyn_map_import.map.info.height, dyn_map_import.map.info.resolution); meta_data_message_ = dyn_map_import.map.info; dyn_map_out = dyn_map_import; map_import.map.info = dyn_map_import.map.info; map_import.map.header = dyn_map_import.map.header; map_import.map.data = dyn_map_import.map.data; } else { ROS_INFO("Starting with an empty and new map from the scratch... \n"); map_is_imported = false; dyn_map_import.map.info.map_load_time = ros::Time::now(); dyn_map_import.map.header.frame_id = "dyn_map"; dyn_map_import.map.header.stamp = ros::Time::now(); dyn_map_import.map.dynamic_time_max = dynamic_time_max; dyn_map_out = dyn_map_import; } // subscribe to slam_map topic slam_map = n.subscribe("slam_map", 1, &DynamicMapping::slamMapCallback, this); // subscribe to initial position topic init_pose = n.subscribe("initialpose", 1, &DynamicMapping::initPoseCallback, this); // subscribe to laser scan topic sub_laser = n.subscribe("scan", 1, &DynamicMapping::laserCallback, this); // service for map export service = n.advertiseService("export_map", &DynamicMapping::export_map, this); if(use_laser_map == 1) { laser_map = n.subscribe("laser_map", 1, &DynamicMapping::laserMapCallback, this); hasLaserMap = false; hasOldLaserMap = false; } // Latched publisher for metadata metadata_pub= n.advertise<nav_msgs::MapMetaData>("map_metadata", 1, true); map_pub = n.advertise<nav_msgs::OccupancyGrid>("map", 1, true); dyn_map_pub = n.advertise<dynamic_mapping::DynamicGrid>("dyn_map", 1, true); if(map_is_imported) { map_out.map.info = dyn_map_out.map.info; map_out.map.header.frame_id = "map"; map_out.map.data = dyn_map_out.map.data; map_pub.publish( map_out.map ); dyn_map_pub.publish( dyn_map_out.map ); metadata_pub.publish( meta_data_message_ ); } // Init merging variables position_ready = false; x_position_final = 0; y_position_final = 0; angle_final = 0; first_time = true; // start timer time_update = nh.createTimer(ros::Duration(time_period/1000), &DynamicMapping::dynamicTimeUpdateCallback, this); } private: /* * PRIVATE VARIBALES */ // publisher, subscriber, services, listener ros::NodeHandle n; ros::Publisher map_pub; ros::Publisher dyn_map_pub; ros::Publisher dyn_area_pub; ros::Publisher metadata_pub; ros::Subscriber slam_map; ros::Subscriber laser_map; ros::Subscriber init_pose; ros::Subscriber sub_laser; ros::ServiceServer service; ros::Timer time_update; tf::TransformListener *tf_listener; // dynamic value calculation variables int8_t *dynamic_trend; bool init_dynamic_trend; uint32_t *dynamic_time; bool init_dynamic_time; int time_period; int hysteresis; int use_laser_map; bool hasLaserMap, hasOldLaserMap; // map data is cached here nav_msgs::MapMetaData meta_data_message_; nav_msgs::GetMap::Response map_import, map_out, map_slam, map_laser, map_laser_old; dynamic_mapping::GetDynamicMap::Response dyn_map_import; dynamic_mapping::GetDynamicMap::Response dyn_map_out; // dynamic update area geometry_msgs::PolygonStamped update_area; ros::Publisher laser_polygon_pub; unsigned int update_area_size; // variables of the postion of the robot in the imported map bool position_ready; double x_position_final; double y_position_final; double angle_final; // params to be overwritten by commandline std::string fname; int area_size; int free_area_size; double map_weight; int dilate_size; double dynamic_weight; int dynamic_time_max; int dynamic_remove_time; // auxilary variables bool deprecated; bool map_is_imported; bool first_time; /* * PRIVATE FUNCIONS */ /* * check if point is in update_area polygon * if yes, increase its dynamic_time value */ void dynamicTimeUpdateCallback(const ros::TimerEvent& event) { tf::StampedTransform transform; tf_listener->lookupTransform("/update_area", "/dyn_map", ros::Time(0), transform); for(unsigned int x = 0; x < dyn_map_import.map.info.width; ++x) { for(unsigned int y = 0; y < dyn_map_import.map.info.height; ++y) { unsigned int i = x + (dyn_map_import.map.info.height - y -1) * dyn_map_import.map.info.width; if(dyn_map_import.map.data[i] != -1) { tf::Vector3 map_point( ((int) x - (int) (dyn_map_import.map.info.width / 2)) * dyn_map_import.map.info.resolution, ((int) (dyn_map_import.map.info.height / 2) - (int) y) * dyn_map_import.map.info.resolution, 0.0); try { // updating dynamic_time values if they are in the scanned area tf::Vector3 laser_point; laser_point = transform * map_point; if(pointInPolygon(laser_point.x(), laser_point.y())) { if(!use_laser_map || use_laser_map && laser_map_static_area(i, 10, true)) { dynamic_time[i] = dynamic_time[i] + time_period; if(dynamic_time[i] > dynamic_remove_time) dyn_map_import.map.dynamic[i] = 0; } } } catch(tf::TransformException& e) { ROS_ERROR("Transform error: %s", e.what()); } } } } } void initPoseCallback(const geometry_msgs::PoseWithCovarianceStamped::ConstPtr init_pose) { if(!position_ready) { // set initialpose of the map if not already set x_position_final = init_pose->pose.pose.position.x; y_position_final = init_pose->pose.pose.position.y; // matrix to angle calculation (euler numeric integration) angle_final = atan2(2*(init_pose->pose.pose.orientation.z * (- init_pose->pose.pose.orientation.w)), 1-2*(init_pose->pose.pose.orientation.z*init_pose->pose.pose.orientation.z)); position_ready = true; // take the whole importet map at first dyn_map_out = dyn_map_import; ROS_INFO("-----> Initial robot Position: (x,y,angle) : (%f, %f, %f)\n", x_position_final, y_position_final, angle_final); } } bool slam_map_known_area(unsigned int slam, int window_size) { for(int h = -window_size / 2; h < window_size / 2; h++) { for(int w = -window_size / 2; w < window_size / 2; w++) { int index = slam + (h*map_slam.map.info.width) + w; if(index < map_slam.map.info.width * map_slam.map.info.height && index >= 0 && map_slam.map.data[index] == -1) { return false; } } } return true; } bool dyn_map_known_area(unsigned int dyn, int window_size) { for(int h = -window_size / 2; h < window_size / 2; h++) { for(int w = -window_size / 2; w < window_size / 2; w++) { int index = dyn + (h*dyn_map_out.map.info.width) + w; if(index < dyn_map_out.map.info.width * dyn_map_out.map.info.height && index >= 0 && dyn_map_out.map.data[index] == -1) { return false; } } } return true; } bool laser_map_static_area(unsigned int dyn, int window_size, bool isOldMap) { for(int h = -window_size / 2; h < window_size / 2; h++) { for(int w = -window_size / 2; w < window_size / 2; w++) { if(isOldMap) { int index = dyn + (h*map_laser_old.map.info.width) + w; if(index > map_laser_old.map.info.width * map_laser_old.map.info.height || index < 0) continue; if(map_laser_old.map.data[index] == 100) { return false; } } else { int index = dyn + (h*map_laser.map.info.width) + w; if(index > map_laser.map.info.width * map_laser.map.info.height || index < 0) continue; if(map_laser.map.data[index] == 100) { return false; } } } } return true; } void dyn_map_dilation(unsigned int dyn, int window_size) { for(int k = 0; k < 2; k++) { int first = -window_size - 1; int first_dyn = 0; int second = -window_size - 1; int second_dyn = 0; for(int h = -window_size / 2; h < window_size / 2; h++) { int index = 0; if(k == 0) index = dyn + (h*dyn_map_out.map.info.width); else index = dyn + h; if(index < dyn_map_out.map.info.width * dyn_map_out.map.info.height && index >= 0 && dyn_map_out.map.dynamic[index]) { if(h < 0) { first = h; first_dyn = dyn_map_out.map.dynamic[index]; } if(h > 0) { second = h; second_dyn = dyn_map_out.map.dynamic[index]; } } } if(first > -window_size - 1 && second > -window_size - 1) { for(int i = first; i < second; i++) { int index = 0; if(k == 0) index = dyn + (i*dyn_map_out.map.info.width); else index = dyn + i; dyn_map_out.map.dynamic[index] = (first_dyn + second_dyn) / 2; } } } } /* * merging the slam_map from the gmapping module and the importet dyn_map * and publish it as dyn_map type and map type */ int8_t mergeDynamicMaps(unsigned int dyn, unsigned int slam) { /* * case slam_map area is known, dyn_map area is unknown */ if(map_slam.map.data[dyn] != -1 && dyn_map_out.map.data[dyn] != -1) { // init trend if(dynamic_trend[dyn] == -1) { if(dyn_map_out.map.data[dyn] == 0) dynamic_trend[dyn] = 0; else dynamic_trend[dyn] = 1; } if(slam_map_known_area(slam, area_size) && dyn_map_known_area(dyn, area_size)) { // use map_laser or map_slam for dynamic area generation if(use_laser_map == 1) { if(hasOldLaserMap && (map_laser.map.data[slam] == 100 || map_laser_old.map.data[slam] == 100) && map_laser.map.data[slam] != map_laser_old.map.data[slam]) { if((map_laser.map.data[slam] == 100 && laser_map_static_area(slam, 10, true)) || (map_laser_old.map.data[slam] == 100 && laser_map_static_area(slam, 10, false))) { if(dyn_map_out.map.dynamic[dyn] == 0) { if(dynamic_time[dyn] == 0) dyn_map_out.map.dynamic[dyn] = time_period; else dyn_map_out.map.dynamic[dyn] = dynamic_time[dyn]; } else { dyn_map_out.map.dynamic[dyn] = dyn_map_out.map.dynamic[dyn] * dynamic_weight + dynamic_time[dyn] * (1 - dynamic_weight); } dynamic_time[dyn] = 0; } } } // change dynamic value else if(map_slam.map.data[slam] != dyn_map_out.map.data[dyn] ) { // Tiefpunkt or Hochpunkt if((map_slam.map.data[dyn] > dyn_map_out.map.data[dyn] && dynamic_trend[dyn] == 0) || (map_slam.map.data[dyn] < dyn_map_out.map.data[dyn] && dynamic_trend[dyn] == 1)) { #ifdef DEBUG printf("dynamic_time[%d]: %d\n", dyn, dynamic_time[dyn]); #endif if(dyn_map_out.map.dynamic[dyn] == 0) { if(dynamic_time[dyn] == 0) dyn_map_out.map.dynamic[dyn] = time_period; else dyn_map_out.map.dynamic[dyn] = dynamic_time[dyn]; } else { dyn_map_out.map.dynamic[dyn] = dyn_map_out.map.dynamic[dyn] * dynamic_weight + dynamic_time[dyn] * (1 - dynamic_weight); } dynamic_time[dyn] = 0; } } } /* * calculate trend */ if(map_slam.map.data[dyn] > dyn_map_out.map.data[dyn] + hysteresis) dynamic_trend[dyn] = 1; else if(map_slam.map.data[dyn] + hysteresis < dyn_map_out.map.data[dyn]) dynamic_trend[dyn] = 0; } } int8_t mergeDataMaps(unsigned int dyn, unsigned int slam) { dyn_map_out.map.data[dyn] = (int8_t) (map_slam.map.data[slam] * (float) (1.0-map_weight) + (float) dyn_map_out.map.data[dyn] * map_weight); } /* * Laser Callback for determining the update area */ void laserCallback(const sensor_msgs::LaserScan::ConstPtr &lscan) { int laserSize = (lscan->angle_max - lscan->angle_min) / lscan->angle_increment; float polyX[laserSize]; float polyY[laserSize]; update_area_size = laserSize + 1; update_area.polygon.points.resize(update_area_size); update_area.header.seq = 0; update_area.header.frame_id = "/update_area"; update_area.header.stamp = ros::Time(0); // ros::Time::now() will lead to ROS problems for(int i = 0; i < laserSize; i++) { update_area.polygon.points[i].x = lscan->ranges[i] * sin(lscan->angle_min + i * lscan->angle_increment); update_area.polygon.points[i].y = lscan->ranges[i] * cos(lscan->angle_min + i * lscan->angle_increment); update_area.polygon.points[i].z = 0; polyX[i] = lscan->ranges[i] * sin(lscan->angle_min + i * lscan->angle_increment); polyY[i] = lscan->ranges[i] * cos(lscan->angle_min + i * lscan->angle_increment); } // add the robot origin as last point update_area.polygon.points[laserSize].x = 0; update_area.polygon.points[laserSize].y = 0; update_area.polygon.points[laserSize].z = 0; laser_polygon_pub = n.advertise<geometry_msgs::PolygonStamped>("update_area", 1, true); laser_polygon_pub.publish( update_area ); } bool pointInPolygon(float x, float y) { int i = 0, j=update_area_size-1 ; bool oddNodes=false; for (i=0; i<update_area_size; i++) { if (update_area.polygon.points[i].y < y && update_area.polygon.points[j].y >= y || update_area.polygon.points[j].y < y && update_area.polygon.points[i].y >= y) { if (update_area.polygon.points[i].x + (y-update_area.polygon.points[i].y) / (update_area.polygon.points[j].y - update_area.polygon.points[i].y)* (update_area.polygon.points[j].x - update_area.polygon.points[i].x)<x) { oddNodes=!oddNodes; } } j=i; } return oddNodes; } void laserMapCallback(const nav_msgs::OccupancyGridConstPtr& laser_map) { if(position_ready) { if(dyn_map_import.map.info.resolution != laser_map->info.resolution) { // wrong resolution error ROS_ERROR("Laser map must have a resolution of %f.", dyn_map_import.map.info.resolution); } else { int laser_map_width = (int) laser_map->info.width; int laser_map_height = (int) laser_map->info.height; // save old laser value if(hasLaserMap) { // deep copy of laser_map map_laser_old.map.data.resize(laser_map_width * laser_map_height); for(int x = 0; x < laser_map_width; x++) { for(int y = 0; y < laser_map_height; y++) { unsigned int i = x + (laser_map_height - y -1) * laser_map_width; map_laser_old.map.data[i] = map_laser.map.data[i]; } } map_laser_old.map.header = map_laser.map.header; map_laser_old.map.info = map_laser.map.info; hasOldLaserMap = true; } map_laser.map.data = laser_map->data; map_laser.map.header = laser_map->header; map_laser.map.info = laser_map->info; // position of the robot in the laser map int x_position_laser_map = laser_map_width / 2; int y_position_laser_map = laser_map_height / 2; int x_position_import_map; int y_position_import_map; double angle; // only merge the maps if the position of the roboter is estimated good enought x_position_import_map = (x_position_final / laser_map->info.resolution) + x_position_laser_map; y_position_import_map = laser_map_height - ((y_position_final / laser_map->info.resolution) + y_position_laser_map); angle = angle_final;; // init new rotated laser_map map for(int x = 0; x < laser_map_width; x++) { for(int y = 0; y < laser_map_height; y++) { unsigned int i = x + (laser_map_height - y -1) * laser_map_width; map_laser.map.data[i] = 0; } } for(int x = 0; x < laser_map_width; x++) { for(int y = 0; y < laser_map_height; y++) { int xt = x - x_position_laser_map; int yt = y - y_position_laser_map; double sinma = sin(-angle); double cosma = cos(-angle); int x_old = (int)round((cosma * xt - sinma * yt) + x_position_laser_map); int y_old = (int)round((sinma * xt + cosma * yt) + y_position_laser_map); // calculate position in the rotated laser map unsigned int i = x + (laser_map_height - y -1) * laser_map_width; // calculate position in the unrotated laser map unsigned int j = x_old + (laser_map_height - y_old -1) * laser_map_width; if(x_old >= 0 && x_old < laser_map_width && y_old >= 0 && y_old < laser_map_height) { // rotate pixel j to position i map_laser.map.data[i] = laser_map->data[j]; } } } hasLaserMap = true; } } } void slamMapCallback(const nav_msgs::OccupancyGridConstPtr& slam_map) { map_slam.map.data = slam_map->data; map_slam.map.header = slam_map->header; map_slam.map.info = slam_map->info; update_area.header.seq = 0; update_area.header.frame_id = "/update_area"; update_area.header.stamp = ros::Time(0); laser_polygon_pub = n.advertise<geometry_msgs::PolygonStamped>("update_area", 1, true); laser_polygon_pub.publish( update_area ); if(!map_is_imported) { map_slam.map.header.frame_id = "map"; // Latched publisher for metadata metadata_pub= n.advertise<nav_msgs::MapMetaData>("map_metadata", 1, true); metadata_pub.publish( map_slam.map.info ); // Latched publisher for data map_pub = n.advertise<nav_msgs::OccupancyGrid>("map", 1, true); map_pub.publish( map_slam.map ); dyn_map_import.map.info = slam_map->info; dyn_map_import.map.header = slam_map->header; dyn_map_import.map.header.frame_id = "dyn_map"; dyn_map_import.map.data = slam_map->data; dyn_map_import.map.dynamic.resize(dyn_map_import.map.info.width * dyn_map_import.map.info.height); dyn_map_import.map.dynamic_time_max = dynamic_time_max; dynamic_trend = (int8_t*) malloc(dyn_map_import.map.info.width * dyn_map_import.map.info.height); if(dynamic_trend == NULL) { ROS_ERROR("MALLOC dynamic_trend array failed."); exit(-1); } dynamic_time = (uint32_t*) malloc(dyn_map_import.map.info.width * dyn_map_import.map.info.height * sizeof(uint32_t)); if( dynamic_time == NULL) { ROS_ERROR("MALLOC dynamic_time array failed."); exit(-1); } for(int i = 0; i < dyn_map_import.map.info.width * dyn_map_import.map.info.height; i++) { dyn_map_import.map.dynamic[i] = 0; dynamic_trend[i] = -1; dynamic_time[i] = 0; } dyn_map_out = dyn_map_import; dyn_map_pub = n.advertise<dynamic_mapping::DynamicGrid>("dyn_map", 1, true); dyn_map_pub.publish( dyn_map_out.map ); x_position_final = 0; y_position_final = 0; angle_final = 0; position_ready = true; map_is_imported = true; init_dynamic_trend = false; init_dynamic_time = false; return; } else { // init dynamic trend if(init_dynamic_trend) { dynamic_trend = (int8_t*) malloc(dyn_map_import.map.info.width * dyn_map_import.map.info.height); if(dynamic_trend == NULL) { ROS_ERROR("MALLOC dynamic_trend array failed."); exit(-1); } } //init dynamic time if(init_dynamic_time) { dynamic_time = (uint32_t*) malloc(dyn_map_import.map.info.width * dyn_map_import.map.info.height * sizeof(uint32_t)); if( dynamic_time == NULL) { ROS_ERROR("MALLOC dynamic_time array failed."); exit(-1); } } for(int i = 0; i < dyn_map_import.map.info.width * dyn_map_import.map.info.height; i++) { if(init_dynamic_trend) dynamic_trend[i] = -1; if(init_dynamic_time) dynamic_time[i] = 0; } init_dynamic_trend = false; init_dynamic_time = false; } ROS_INFO("Dynamic map %d X %d map @ %.3lf m/cell", dyn_map_import.map.info.width, dyn_map_import.map.info.height, dyn_map_import.map.info.resolution); ROS_INFO("SLAM map %d X %d map @ %.3lf m/cell", slam_map->info.width, slam_map->info.height, slam_map->info.resolution); if(dyn_map_import.map.info.resolution != slam_map->info.resolution) { // wrong resolution error ROS_ERROR("SLAM map must have a resolution of %f.", dyn_map_import.map.info.resolution); } else { int slam_map_width = (int) slam_map->info.width; int slam_map_height = (int) slam_map->info.height; // position of the robot in the slam map int x_position_slam_map = slam_map_width / 2; int y_position_slam_map = slam_map_height / 2; int x_position_import_map; int y_position_import_map; double angle; // only merge the maps if the position of the roboter is estimated good enought if(position_ready) { x_position_import_map = (x_position_final / slam_map->info.resolution) + x_position_slam_map; y_position_import_map = slam_map_height - ((y_position_final / slam_map->info.resolution) + y_position_slam_map); angle = angle_final;; #ifdef DEBUG printf("final_x: %d\n", x_position_import_map); printf("final_y: %d\n", y_position_import_map); printf("final_winkel: %f\n", angle); #endif // init new rotated slam_map map for(int x = 0; x < slam_map_width; x++) { for(int y = 0; y < slam_map_height; y++) { unsigned int i = x + (slam_map_height - y -1) * slam_map_width; map_slam.map.data[i] = -1; } } /* * rotate slam_map to fit in the imported map */ for(int x = 0; x < slam_map_width; x++) { for(int y = 0; y < slam_map_height; y++) { int xt = x - x_position_slam_map; int yt = y - y_position_slam_map; double sinma = sin(-angle); double cosma = cos(-angle); int x_old = (int)round((cosma * xt - sinma * yt) + x_position_slam_map); int y_old = (int)round((sinma * xt + cosma * yt) + y_position_slam_map); // calculate position in the rotated slam map unsigned int i = x + (slam_map_height - y -1) * slam_map_width; // calculate position in the unrotated slam map unsigned int j = x_old + (slam_map_height - y_old -1) * slam_map_width; if(x_old >= 0 && x_old < slam_map_width && y_old >= 0 && y_old < slam_map_height) { // rotate pixel j to position i map_slam.map.data[i] = slam_map->data[j]; } } } int map_import_width = (int) dyn_map_import.map.info.width; int map_import_height = (int) dyn_map_import.map.info.height; /* * calculate startpoint (top-left) and endpoint (right-bottom) * of the imported map */ int x_start = max((int) (x_position_import_map - map_import_width / 2), 0); int y_start = max((int) (y_position_import_map - map_import_height / 2), 0); int x_end = min((int) (x_position_import_map + x_position_slam_map), map_import_width); int y_end = min((int) (y_position_import_map + y_position_slam_map), map_import_height); int window_width = x_end - x_start; int window_height = y_end - y_start; /* * calculate startpoint (top-left) and endpoint (right-bottom) * of the slam generated map (topic /slam_map) */ int x_start_s = max(slam_map_width - x_end, 0); int y_start_s = max(slam_map_height - y_end, 0); int x_end_s = min(x_start_s + window_width, slam_map_width); int y_end_s = min(y_start_s + window_height, slam_map_height); #ifdef DEBUG printf("WINDOW: width: %d, height: %d\n", window_width, window_height); printf("IMPORT: startpoint (%d, %d) endpoint (%d, %d)\n", x_start, y_start, x_end, y_end); printf("SLAM: startpoint (%d, %d) endpoint (%d, %d)\n", x_start_s, y_start_s, x_end_s, y_end_s); #endif // dynamic: merge it with the slam map for(unsigned int x = 0; x < window_width; ++x) { for(unsigned int y = 0; y < window_height; ++y) { // calculate position in the importet map unsigned int i = x_start + x + (map_import_height - (y_start + y) - 1) * map_import_width; // calculate position in the slam map unsigned int j = x_start_s + x + (slam_map_height - (y_start_s + y) -1) * slam_map_width; // merging logic for dynamic values if(dyn_map_out.map.data[i] != -1 && map_slam.map.data[j] != -1) { mergeDynamicMaps(i, j); if(dilate_size > 0) dyn_map_dilation(i, dilate_size); } } } // data: merge it with the slam map for(unsigned int x = 0; x < window_width; ++x) { for(unsigned int y = 0; y < window_height; ++y) { // calculate position in the importet map unsigned int i = x_start + x + (map_import_height - (y_start + y) - 1) * map_import_width; // calculate position in the slam map unsigned int j = x_start_s + x + (slam_map_height - (y_start_s + y) -1) * slam_map_width; // merging logic mergeDataMaps(i, j); } } meta_data_message_ = dyn_map_import.map.info; ROS_INFO("Publishing merged map now...\n"); map_out.map.info = dyn_map_out.map.info; map_out.map.header.frame_id = "map"; map_out.map.data = dyn_map_out.map.data; // Latched publisher for metadata metadata_pub= n.advertise<nav_msgs::MapMetaData>("map_metadata", 1, true); metadata_pub.publish( meta_data_message_ ); // Latched publisher for data map_pub = n.advertise<nav_msgs::OccupancyGrid>("map", 1, true); map_pub.publish( map_out.map ); // publish dyn_map dyn_map_pub = n.advertise<dynamic_mapping::DynamicGrid>("dyn_map", 1, true); dyn_map_pub.publish( dyn_map_out.map ); } } } /* * Service for map export */ bool export_map(dynamic_mapping::ExportMap::Request &req, dynamic_mapping::ExportMap::Response &res) { ROS_INFO("Service export_map called\n"); if(req.init == 1) { printf("init\n"); res.dynamic_trend.resize(dyn_map_out.map.info.width * dyn_map_out.map.info.height); res.dynamic_time.resize(dyn_map_out.map.info.width * dyn_map_out.map.info.height); res.dynamic_map.data.resize(dyn_map_out.map.info.width * dyn_map_out.map.info.height); res.dynamic_map.dynamic.resize(dyn_map_out.map.info.width * dyn_map_out.map.info.height); res.dynamic_map.info = dyn_map_out.map.info; res.dynamic_map.header = dyn_map_out.map.header; for(int i = 0; i < dyn_map_out.map.info.width * dyn_map_out.map.info.height; i++) { res.dynamic_trend[i] = dynamic_trend[i]; res.dynamic_time[i] = dynamic_time[i]; res.dynamic_map.data[i] = dyn_map_out.map.data[i]; res.dynamic_map.dynamic[i] = dyn_map_out.map.dynamic[i]; } #ifdef DEBUG printf("dyn_map_import.map.dynamic_time_max: %d\n", dyn_map_import.map.dynamic_time_max); #endif res.dynamic_time_max = dyn_map_import.map.dynamic_time_max; } return true; } }; int main(int argc, char **argv) { ros::init(argc, argv, "dynamic"); tf::TransformListener listener; try { DynamicMapping ms = DynamicMapping(&listener); ros::spin(); } catch(std::runtime_error& e) { ROS_ERROR("Dynamic Mapping Exception: %s", e.what()); return -1; } }
34.087702
161
0.659559
tuw-cpsg
0aa5fff6ca7ae472914aad4a22ac51badd3713c3
5,200
cc
C++
src/pub_key.cc
gladosconn/ecdsa-
3b8d4b6df48843742fc33c931b9fadc225ae439b
[ "MIT" ]
11
2019-11-20T21:38:22.000Z
2022-03-18T08:45:25.000Z
src/pub_key.cc
gladosconn/ecdsa-
3b8d4b6df48843742fc33c931b9fadc225ae439b
[ "MIT" ]
1
2021-04-01T15:06:55.000Z
2021-04-01T15:06:55.000Z
src/pub_key.cc
gladosconn/ecdsa-
3b8d4b6df48843742fc33c931b9fadc225ae439b
[ "MIT" ]
4
2017-11-03T17:34:27.000Z
2022-03-21T18:40:49.000Z
#include "pub_key.h" #include <cstring> namespace ecdsa { /** This function is taken from the libsecp256k1 distribution and implements * DER parsing for ECDSA signatures, while supporting an arbitrary subset of * format violations. * * Supported violations include negative integers, excessive padding, garbage * at the end, and overly long length descriptors. This is safe to use in * Bitcoin because since the activation of BIP66, signatures are verified to be * strict DER before being passed to this module, and we know it supports all * violations present in the blockchain before that point. */ static int ecdsa_signature_parse_der_lax(const secp256k1_context *ctx, secp256k1_ecdsa_signature *sig, const unsigned char *input, size_t inputlen) { size_t rpos, rlen, spos, slen; size_t pos = 0; size_t lenbyte; unsigned char tmpsig[64] = {0}; int overflow = 0; /* Hack to initialize sig with a correctly-parsed but invalid signature. */ secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig); /* Sequence tag byte */ if (pos == inputlen || input[pos] != 0x30) { return 0; } pos++; /* Sequence length bytes */ if (pos == inputlen) { return 0; } lenbyte = input[pos++]; if (lenbyte & 0x80) { lenbyte -= 0x80; if (pos + lenbyte > inputlen) { return 0; } pos += lenbyte; } /* Integer tag byte for R */ if (pos == inputlen || input[pos] != 0x02) { return 0; } pos++; /* Integer length for R */ if (pos == inputlen) { return 0; } lenbyte = input[pos++]; if (lenbyte & 0x80) { lenbyte -= 0x80; if (pos + lenbyte > inputlen) { return 0; } while (lenbyte > 0 && input[pos] == 0) { pos++; lenbyte--; } if (lenbyte >= sizeof(size_t)) { return 0; } rlen = 0; while (lenbyte > 0) { rlen = (rlen << 8) + input[pos]; pos++; lenbyte--; } } else { rlen = lenbyte; } if (rlen > inputlen - pos) { return 0; } rpos = pos; pos += rlen; /* Integer tag byte for S */ if (pos == inputlen || input[pos] != 0x02) { return 0; } pos++; /* Integer length for S */ if (pos == inputlen) { return 0; } lenbyte = input[pos++]; if (lenbyte & 0x80) { lenbyte -= 0x80; if (pos + lenbyte > inputlen) { return 0; } while (lenbyte > 0 && input[pos] == 0) { pos++; lenbyte--; } if (lenbyte >= sizeof(size_t)) { return 0; } slen = 0; while (lenbyte > 0) { slen = (slen << 8) + input[pos]; pos++; lenbyte--; } } else { slen = lenbyte; } if (slen > inputlen - pos) { return 0; } spos = pos; /* Ignore leading zeroes in R */ while (rlen > 0 && input[rpos] == 0) { rlen--; rpos++; } /* Copy R value */ if (rlen > 32) { overflow = 1; } else { std::memcpy(tmpsig + 32 - rlen, input + rpos, rlen); } /* Ignore leading zeroes in S */ while (slen > 0 && input[spos] == 0) { slen--; spos++; } /* Copy S value */ if (slen > 32) { overflow = 1; } else { std::memcpy(tmpsig + 64 - slen, input + spos, slen); } if (!overflow) { overflow = !secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig); } if (overflow) { /* Overwrite the result again with a correctly-parsed but invalid signature if parsing failed. */ std::memset(tmpsig, 0, 64); secp256k1_ecdsa_signature_parse_compact(ctx, sig, tmpsig); } return 1; } PubKey::PubKey(const std::vector<uint8_t> &pub_key_data) : pub_key_data_(pub_key_data) { // Create secp256k1 context. ctx_ = secp256k1_context_create(SECP256K1_CONTEXT_VERIFY); } PubKey::PubKey(PubKey &&rhs) { pub_key_data_.assign(std::begin(rhs.pub_key_data_), std::end(rhs.pub_key_data_)); ctx_ = rhs.ctx_; rhs.pub_key_data_.clear(); rhs.ctx_ = nullptr; } PubKey &PubKey::operator=(PubKey &&rhs) { if (this != &rhs) { pub_key_data_.assign(std::begin(rhs.pub_key_data_), std::end(rhs.pub_key_data_)); ctx_ = rhs.ctx_; rhs.pub_key_data_.clear(); rhs.ctx_ = nullptr; } return *this; } PubKey::~PubKey() { secp256k1_context_destroy(ctx_); ctx_ = nullptr; } bool PubKey::Verify(const std::vector<uint8_t> &hash, const std::vector<uint8_t> &sig_in) const { // Parse public key. secp256k1_pubkey pubkey; if (!secp256k1_ec_pubkey_parse(ctx_, &pubkey, pub_key_data_.data(), pub_key_data_.size())) { return false; } // Parse signature. secp256k1_ecdsa_signature sig; if (!ecdsa_signature_parse_der_lax(ctx_, &sig, sig_in.data(), sig_in.size())) { return false; } /* libsecp256k1's ECDSA verification requires lower-S signatures, which have * not historically been enforced in Bitcoin, so normalize them first. */ secp256k1_ecdsa_signature_normalize(ctx_, &sig, &sig); return secp256k1_ecdsa_verify(ctx_, &sig, hash.data(), &pubkey); } } // namespace ecdsa
24.413146
80
0.587115
gladosconn
0aa646d269e6b30a2850b48c3c2509f4f1091711
5,569
cpp
C++
lib/utility.cpp
CreRecombinase/tomahawk
0e816bca4f49732d2c56f01fa4e7ec68bb10b60b
[ "MIT" ]
39
2018-02-01T14:05:05.000Z
2022-03-23T08:33:36.000Z
lib/utility.cpp
CreRecombinase/tomahawk
0e816bca4f49732d2c56f01fa4e7ec68bb10b60b
[ "MIT" ]
16
2018-02-03T02:24:30.000Z
2022-03-15T02:04:18.000Z
lib/utility.cpp
CreRecombinase/tomahawk
0e816bca4f49732d2c56f01fa4e7ec68bb10b60b
[ "MIT" ]
12
2018-02-03T02:03:20.000Z
2021-02-19T10:58:22.000Z
#include <sys/time.h> #include <regex> #include "utility.h" namespace tomahawk { namespace utility { std::string remove_whitespace(std::string& string){ string.erase(remove_if(string.begin(), string.end(), isspace), string.end()); return(string); } std::string remove_excess_whitespace(const std::string& string){ return(std::regex_replace(string, std::regex("^ +| +$|( ) +"), std::string("$1"))); } int IsBigEndian(){ union { uint32_t i; uint8_t c[4]; } val = {0x01020304}; return val.c[0] == 1; } std::vector<std::string> &split(std::string& s, char delim, std::vector<std::string>& elems, const bool keepEmpty) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { if(!item.empty() || (item.empty() && keepEmpty)) elems.push_back(item); } return elems; } std::vector<std::string> split(std::string& s, char delim, const bool keepEmpty) { std::vector<std::string> elems; split(s, delim, elems, keepEmpty); return elems; } std::vector<std::string> &split(const std::string& s, char delim, std::vector<std::string>& elems, const bool keepEmpty) { std::stringstream ss(s); std::string item; while (std::getline(ss, item, delim)) { if(!item.empty() || (item.empty() && keepEmpty)) elems.push_back(item); } return elems; } std::vector<std::string> split(const std::string& s, char delim, const bool keepEmpty) { std::vector<std::string> elems; split(s, delim, elems, keepEmpty); return elems; } std::vector<std::string> splitLastOf(const std::string& s, const char delim, const bool includeLast){ std::size_t found = s.find_last_of(delim); std::vector<std::string> ret; ret.push_back(s.substr(0, found + includeLast)); ret.push_back(s.substr(found + 1)); return(ret); } std::string datetime(){ time_t t = time(0); struct timeval tv; struct timezone tz; struct tm *now = localtime(&t); gettimeofday(&tv, &tz); char buffer[48]; sprintf(buffer, "%04u-%02u-%02u %02u:%02u:%02u,%03u", now->tm_year + 1900, now->tm_mon + 1, now->tm_mday, now->tm_hour, now->tm_min, now->tm_sec, (uint32_t)tv.tv_usec / 1000); return std::string(&buffer[0], 23); } std::string timestamp(const std::string type){ std::stringstream ret; ret << "[" << datetime() << "]"; ret << "[" << type << "] "; return(ret.str()); } std::string timestamp(const std::string type, const std::string type2){ std::stringstream ret; ret << "[" << datetime() << "]"; ret << "[" << type << "]"; ret << "[" << type2 << "] "; return(ret.str()); } std::string SecondsToTimestring(const double& value){ uint32_t internalVal = value; std::string retVal; const uint32_t hours = internalVal / 3600; if(hours > 0) retVal += std::to_string(hours) + "h"; internalVal %= 3600; const uint32_t min = internalVal / 60; if(min > 0) retVal += std::to_string(min) + "m"; internalVal %= 60; const uint32_t sec = internalVal; retVal += std::to_string(sec) + "s"; return(retVal); } std::string BasePath(const std::string& input){ size_t found = input.find_last_of("/\\"); if(found != std::string::npos) return(input.substr(0, found)); else return std::string(); } std::string BaseName(const std::string& input){ size_t found = input.find_last_of("/\\"); if(found == std::string::npos) found = -1; return(input.substr(found+1, input.size())); } std::string ExtensionName(const std::string& input){ std::string base = BaseName(input); size_t foundDot = base.rfind('.'); if(foundDot == std::string::npos) foundDot = base.size() - 1; return(base.substr(foundDot+1, base.size())); } std::vector<std::string> FilePathBaseExtension(const std::string& input){ std::vector<std::string> ret; const std::string base = BaseName(input); ret.push_back(BasePath(input)); ret.push_back(base); size_t foundDot = base.rfind('.'); if(foundDot == std::string::npos){ ret.push_back(base); ret.push_back(std::string()); } else { ret.push_back(base.substr(0, foundDot)); ret.push_back(base.substr(foundDot+1, base.size())); } ret.push_back(ExtensionName(input)); return(ret); } std::string NumberThousandsSeparator(std::string number){ int insertPosition = number.length() - 3; char EndPos = 0; if(number[0] == '-') EndPos = 1; // Todo: fix NNNN.MMMM while (insertPosition > EndPos) { number.insert(insertPosition, ","); insertPosition -= 3; } if(number[0] == '-'){ std::string numberTemp = "&ndash;"; numberTemp += number.substr(1,10000); return numberTemp; } return number; } int32_t ConvertCharToInt(const char& input){ if(input >= '0' && input <= '9') return input - '0'; else if(input >= 'A' && input <= 'F') return input - 'A' + 10; else if(input >= 'a' && input <= 'f') return input - 'a' + 10; throw std::invalid_argument("Invalid input string"); } bool HexToBytes(const std::string& hex, uint8_t* target){ if(hex.size() % 2 != 0){ std::cerr << "illegal uneven hex" << std::endl; return false; } uint32_t p = 0; for (uint32_t i = 0; i < hex.length(); i += 2, ++p) target[p] = ConvertCharToInt(hex[i])*16 + ConvertCharToInt(hex[i+1]); return true; } } void SerializeString(const std::string& string, std::ostream& stream){ size_t size_helper = string.size(); stream.write((const char*)&size_helper, sizeof(size_t)); stream.write(string.data(), string.size()); } void DeserializeString(std::string& string, std::istream& stream){ size_t l_string; stream.read((char*)&l_string, sizeof(size_t)); string.resize(l_string); stream.read(&string[0], l_string); } }
24.861607
122
0.650745
CreRecombinase
0aa66afae74665ada6a69df962f5c287155a7b93
772
cpp
C++
tests/job/test_co_generator.cpp
grandmaster789/bop
909d4156503f83b66de3f7e3284e086bd98905eb
[ "MIT" ]
null
null
null
tests/job/test_co_generator.cpp
grandmaster789/bop
909d4156503f83b66de3f7e3284e086bd98905eb
[ "MIT" ]
null
null
null
tests/job/test_co_generator.cpp
grandmaster789/bop
909d4156503f83b66de3f7e3284e086bd98905eb
[ "MIT" ]
null
null
null
#include <iostream> #include <memory> #include <array> #include <algorithm> #include "../../src/job/co_generator.h" #include <catch2/catch.hpp> namespace testing { int test_iota() { int sum = 0; // derives to int for (auto x : bop::job::iota(6)) sum += x; return sum; } uint32_t test_generator_range_sum() { uint32_t sum = 0; // explicitly made uint32_t for (auto x : bop::job::range<uint32_t>(5, 10)) sum += x; return sum; } } TEST_CASE("test_generator[iota]") { REQUIRE(testing::test_iota() == (0 + 1 + 2 + 3 + 4 + 5)); // == 15 } TEST_CASE("test_generator[range]") { REQUIRE(testing::test_generator_range_sum() == (5 + 6 + 7 + 8 + 9)); // == 35 }
19.794872
81
0.546632
grandmaster789
0aa76275b50109f71a7984004babf9c66b584393
1,571
cpp
C++
leetcode/0122_Best_Time_to_Buy_and_Sell_Stock_2/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0122_Best_Time_to_Buy_and_Sell_Stock_2/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
leetcode/0122_Best_Time_to_Buy_and_Sell_Stock_2/result.cpp
theck17/notes
f32f0f4b8f821b1ed38d173ef0913efddd094b91
[ "MIT" ]
null
null
null
/** * Copyright (C) 2021 All rights reserved. * * FileName :result.cpp * Author :C.K * Email :theck17@163.com * DateTime :2021-02-04 21:50:26 * Description : */ #include <stdexcept> //标准异常类 #include <streambuf> //底层输入/输出支持 #include <string> //字符串类 #include <vector> //STL 动态数组容器 #include <valarray> //对包含值的数组的操作 #include <ctime> //定义关于时间的函数 using namespace std; class Solution { public: int maxProfit(vector<int>& prices) { int sum = 0; // to store result int minCost = prices[0]; // initialise minimum cost as first day price int maxProfit = 0; // initially profit is zero for(int i = 1; i < prices.size(); i++) { // Now check from day 2 if(prices[i] > minCost && prices[i] > prices[i-1]) { // if current day price is better than previous day price & also greater than minimum cost so that to get maximum profit till date maxProfit = max(maxProfit, prices[i] - minCost); cout << maxProfit << " "; } else { // since current day price is less as compared to previous also we have got maximum profit till date sum = sum + maxProfit; minCost = prices[i]; // Again we will set minimum cost as current day price maxProfit = 0; // Now again from next day we will buy i.e maximum profit is now zero in hand } } sum = sum + maxProfit; return sum; } }; int main(){ return 0; }
34.911111
196
0.563972
theck17
0aac1cb8984bd62f4179e4ad6dfc968d2fdab19d
2,323
cpp
C++
Sources/ElkCraft/Sources/Utils/ItemsInfo.cpp
adriengivry/ElkCraft
7147b1aae7183eee692f2691cac24505a61515c1
[ "MIT" ]
10
2018-11-09T03:38:30.000Z
2022-01-31T11:46:10.000Z
Sources/ElkCraft/Sources/Utils/ItemsInfo.cpp
adriengivry/ElkCraft
7147b1aae7183eee692f2691cac24505a61515c1
[ "MIT" ]
null
null
null
Sources/ElkCraft/Sources/Utils/ItemsInfo.cpp
adriengivry/ElkCraft
7147b1aae7183eee692f2691cac24505a61515c1
[ "MIT" ]
10
2018-09-30T05:07:35.000Z
2021-12-22T04:41:38.000Z
#include "stdafx.h" #include "ElkCraft/Utils/ItemsInfo.h" using namespace ElkCraft::Utils; using namespace ElkTools::Utils; bool ItemsInfo::IsItem(uint8_t p_type) { return p_type >= 100; } bool ElkCraft::Utils::ItemsInfo::IsTool(uint8_t p_type) { return p_type >= 101 && p_type <= 106; } ItemsInfo::Quality ElkCraft::Utils::ItemsInfo::GetQuality(uint8_t p_type) { switch (GetItemType(p_type)) { case ItemType::WOOD_AXE: case ItemType::WOOD_PICKAXE: case ItemType::WOOD_SHOVEL: return Quality::WOOD; case ItemType::STONE_AXE: case ItemType::STONE_PICKAXE: case ItemType::STONE_SHOVEL: return Quality::STONE; default: return Quality::NONE; } } ItemsInfo::ToolType ElkCraft::Utils::ItemsInfo::GetToolType(uint8_t p_type) { switch (GetItemType(p_type)) { case ItemType::WOOD_AXE: case ItemType::STONE_AXE: return ToolType::AXE; case ItemType::WOOD_PICKAXE: case ItemType::STONE_PICKAXE: return ToolType::PICKAXE; case ItemType::WOOD_SHOVEL: case ItemType::STONE_SHOVEL: return ToolType::SHOVEL; default: return ToolType::NONE; } } ItemsInfo::ItemType ElkCraft::Utils::ItemsInfo::GetItemType(uint8_t p_type) { return static_cast<ItemType>(p_type); } bool ElkCraft::Utils::ItemsInfo::IsEfficientOn(uint8_t p_tool, uint8_t p_block) { ToolType neededTool; switch (static_cast<BlocksInfo::BlockType>(p_block)) { case BlocksInfo::BlockType::GRASS: neededTool = ToolType::SHOVEL; break; case BlocksInfo::BlockType::DIRT: neededTool = ToolType::SHOVEL; break; case BlocksInfo::BlockType::GRAVEL: neededTool = ToolType::SHOVEL; break; case BlocksInfo::BlockType::STONE: neededTool = ToolType::PICKAXE; break; case BlocksInfo::BlockType::COBBLESTONE: neededTool = ToolType::PICKAXE; break; case BlocksInfo::BlockType::WOOD: neededTool = ToolType::AXE; break; case BlocksInfo::BlockType::WOODEN_PLANKS: neededTool = ToolType::AXE; break; case BlocksInfo::BlockType::SAND: neededTool = ToolType::SHOVEL; break; case BlocksInfo::BlockType::BRICK: neededTool = ToolType::PICKAXE; break; case BlocksInfo::BlockType::STONE_BRICK: neededTool = ToolType::PICKAXE; break; case BlocksInfo::BlockType::COAL_ORE: neededTool = ToolType::PICKAXE; break; default: return false; } return (GetToolType(p_tool) == neededTool); }
19.521008
79
0.739991
adriengivry
0aaf55ab55b59df8f013e9d382902c69780f7018
1,968
cpp
C++
src/image_file_factory.cpp
tymion/cpp_training
c465ac46fcf5e667acc480b4ccdb35f8e60003da
[ "Apache-2.0" ]
null
null
null
src/image_file_factory.cpp
tymion/cpp_training
c465ac46fcf5e667acc480b4ccdb35f8e60003da
[ "Apache-2.0" ]
null
null
null
src/image_file_factory.cpp
tymion/cpp_training
c465ac46fcf5e667acc480b4ccdb35f8e60003da
[ "Apache-2.0" ]
null
null
null
#include <sys/stat.h> #include <stdexcept> #include <cstring> #include <iostream> #include "image_file_factory.h" #include "libpng_wrapper.h" #define PNG_HEADER_SIZE 8 char PNG_HEADER[PNG_HEADER_SIZE] = {'\211', 'P', 'N', 'G', '\r', '\n', '\032', '\n'}; bool ImageFileFactory::isPNG(FILE *file) { if (ftell(file) != 0) { fseek (file, 0, SEEK_SET); } uint8_t header[PNG_HEADER_SIZE]; if (fread(header, sizeof(uint8_t), PNG_HEADER_SIZE, file) == 0) { throw std::invalid_argument("Can't read file header."); } if (png_sig_cmp(header, 0, PNG_HEADER_SIZE) != 0) { return false; } fseek (file, 0, SEEK_SET); return true; } ImageFile* ImageFileFactory::openImageFile(std::string filename) { struct stat stbuf; if (lstat(filename.c_str(), &stbuf) != 0) { throw std::invalid_argument("File not found"); } if (!S_ISREG(stbuf.st_mode)) { throw std::invalid_argument("Invalid parameter. Pass picture file name."); } FILE *file = fopen(filename.c_str(), "rb"); if (!file) { throw std::invalid_argument("Can't open file."); } ImageFile *image = NULL; if (isPNG(file)) { image = new PNGFileWrapper(file); if (image) { std::cout << "Width: " << image->getWidth() << std::endl; std::cout << "Height: " << image->getHeight() << std::endl; } } return image; } ImageFile* ImageFileFactory::createImageFile(std::string filename, size_t width, size_t height, size_t color_depth, ColorSpace color) { struct stat stbuf; if (lstat(filename.c_str(), &stbuf) == -1 && errno != ENOENT) { throw std::invalid_argument("File already exists."); } FILE *file = fopen(filename.c_str(), "wb"); if (!file) { throw std::invalid_argument("Can't create file."); } return new PNGFileWrapper(file, width, height, color_depth, color); }
32.262295
95
0.598069
tymion
0ab146c51d7c82f4c86242f7174fb169e42e3398
447
cpp
C++
solved/easy/1221. Split a String in Balanced Strings/main.cpp
SlaveWilson/leetcode
b762380594908ed44ae278ca1a14e9185eec2f0e
[ "MIT" ]
null
null
null
solved/easy/1221. Split a String in Balanced Strings/main.cpp
SlaveWilson/leetcode
b762380594908ed44ae278ca1a14e9185eec2f0e
[ "MIT" ]
null
null
null
solved/easy/1221. Split a String in Balanced Strings/main.cpp
SlaveWilson/leetcode
b762380594908ed44ae278ca1a14e9185eec2f0e
[ "MIT" ]
null
null
null
#include <iostream> #include <string> using namespace std; class Solution { public: int balancedStringSplit(string s) { int count = 0, l = 0, r = 0; for (char c : s) { if (c == 'R') r++; else l++; if (r == l) count++; } return count; } }; int main() { string s = "RRLRRLRLLLRL"; Solution solution; int output = solution.balancedStringSplit(s); cout << output << endl; }
14.9
47
0.532438
SlaveWilson
0ab1ce011da3066e1e9019811eb1eed8170a10ce
660
cpp
C++
snake/Food.cpp
kriss95/snake-game
cfd2121e6818f08b5275b16c03261c8ab538530e
[ "MIT" ]
null
null
null
snake/Food.cpp
kriss95/snake-game
cfd2121e6818f08b5275b16c03261c8ab538530e
[ "MIT" ]
null
null
null
snake/Food.cpp
kriss95/snake-game
cfd2121e6818f08b5275b16c03261c8ab538530e
[ "MIT" ]
null
null
null
#include "Food.h" Food::Food(Boardd* board, Snake* snake) { int x, y; srand(time(NULL)); do { x = rand() % board->GetM(); y = rand() % board->GetN(); } while (!snake->SnakeMach(x,y)); foodPlace = make_pair(x, y); outP = new GameOutput; } void Food::NewPlace(Boardd* board, Snake* snake) { int x, y; srand(time(NULL)); do { x = rand() % board->GetM(); y = rand() % board->GetN(); } while (!snake->SnakeMach(x, y)); foodPlace = make_pair(x, y); } void Food::DisplayFood() { outP->gotoxy(foodPlace.first + 1, foodPlace.second + 1); printf("*"); } pair<int, int> Food::GetFoodPlace() { return foodPlace; } Food::~Food() { delete outP; }
16.5
57
0.60303
kriss95
0ab5f2c0b7b2e12ed3e705c7f050146f2aaecc2e
2,405
hpp
C++
OptFrame/Experimental/NSIterators/IteratorNSSeqMultiRoute.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
2
2018-05-24T11:04:12.000Z
2020-03-03T13:37:07.000Z
OptFrame/Experimental/NSIterators/IteratorNSSeqMultiRoute.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
null
null
null
OptFrame/Experimental/NSIterators/IteratorNSSeqMultiRoute.hpp
216k155/bft-pos
80c1c84b8ca9a5c1c7462b21b011c89ae97666ae
[ "MIT" ]
1
2019-06-06T16:57:49.000Z
2019-06-06T16:57:49.000Z
// OptFrame - Optimization Framework // Copyright (C) 2009-2015 // http://optframe.sourceforge.net/ // // This file is part of the OptFrame optimization framework. This framework // is free software; you can redistribute it and/or modify it under the // terms of the GNU Lesser General Public License v3 as published by the // Free Software Foundation. // This framework 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 v3 for more details. // You should have received a copy of the GNU Lesser General Public License v3 // along with this library; see the file COPYING. If not, write to the Free // Software Foundation, 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, // USA. #ifndef OPTFRAME_ITERATORNSSEQMULTIROUTE_HPP_ #define OPTFRAME_ITERATORNSSEQMULTIROUTE_HPP_ // Framework includes #include "../../Move.hpp" #include "../../NSIterator.hpp" using namespace std; class NSSeqMultiRouteIteratorOutOfBound { public: NSSeqMultiRouteIteratorOutOfBound() { } }; template<class T, class DS = OPTFRAME_DEFAULT_EMEMORY, class MOVE = MoveMultiRoute<T, DS > > class IteratorNSSeqMultiRoute: public NSIterator<vector<vector<T> > , DS > { typedef vector<T> Route; typedef vector<vector<T> > MultiRoute; private: vector<NSIterator<Route, DS >*>& iterators; int i; public: IteratorNSSeqMultiRoute(vector<NSIterator<Route, DS >*>& it) : iterators(it) { i = 0; } virtual ~IteratorNSSeqMultiRoute() { for (int j = 0; j < iterators.size(); j++) delete iterators[j]; delete &iterators; } void first() { for (int j = 0; j < iterators.size(); j++) iterators[j]->first(); i = 0; while (i < iterators.size()) if (!iterators[i]->isDone()) break; else i++; } void next() { iterators[i]->next(); while (i < iterators.size()) if (!iterators[i]->isDone()) break; else i++; } bool isDone() { for (int j = i; j < iterators.size(); j++) if (!iterators[j]->isDone()) return false; return true; } Move<MultiRoute, DS >& current() { if ((i < iterators.size()) && (!iterators[i]->isDone())) return *new MOVE(i, iterators[i]->current()); else throw NSSeqMultiRouteIteratorOutOfBound(); } }; #endif /*OPTFRAME_ITERATORNSSEQMULTIROUTE_HPP_*/
22.904762
92
0.69106
216k155
0ab9fcba1b89f2f4da1d2146193717ef41bf6e71
3,551
hpp
C++
src/sdk/math.hpp
mov-rax-rax/gamesneeze
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
[ "MIT" ]
1
2022-01-13T07:05:26.000Z
2022-01-13T07:05:26.000Z
src/sdk/math.hpp
mov-rax-rax/gamesneeze
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
[ "MIT" ]
null
null
null
src/sdk/math.hpp
mov-rax-rax/gamesneeze
09b2d9d6ef5b6ad7c9c820f98f1a6339bf1405a1
[ "MIT" ]
1
2021-12-31T13:02:42.000Z
2021-12-31T13:02:42.000Z
#pragma once #include "sdk.hpp" inline QAngle originalAngle{}; inline float originalForwardMove = 0.0f; inline float originalSideMove = 0.0f; inline void startMovementFix(Command* cmd) { originalAngle = cmd->viewAngle; originalForwardMove = cmd->move.x; originalSideMove = cmd->move.y; } inline void endMovementFix(Command* cmd) { // this was just taken from designer bc im lazy // https://github.com/designer1337/csgo-cheat-base/blob/09fa2ba8de52eef482bbc82f682976e369191077/dependencies/math/math.cpp#L4 float deltaViewAngle; float f1; float f2; if (originalAngle.y < 0.f) f1 = 360.0f + originalAngle.y; else f1 = originalAngle.y; if (cmd->viewAngle.y < 0.0f) f2 = 360.0f + cmd->viewAngle.y; else f2 = cmd->viewAngle.y; if (f2 < f1) deltaViewAngle = abs(f2 - f1); else deltaViewAngle = 360.0f - abs(f1 - f2); deltaViewAngle = 360.0f - deltaViewAngle; cmd->move.x = cos( sdk::to_radians(deltaViewAngle)) * originalForwardMove + cos(sdk::to_radians(deltaViewAngle + 90.f)) * originalSideMove; cmd->move.y = sin( sdk::to_radians(deltaViewAngle)) * originalForwardMove + sin(sdk::to_radians(deltaViewAngle + 90.f)) * originalSideMove; // TODO: support upmove } inline void normalizePitch(float& pitch) { pitch = std::clamp(pitch, -89.0f, 89.0f); } inline void normalizeYaw(float& yaw) { while (yaw > 180.0f) { yaw -= 360.0f; } while (yaw < -180.0f) { yaw += 360.0f; } } inline void normalizeAngle(QAngle& angle) { normalizePitch(angle.x); normalizeYaw(angle.y); angle.z = 0.0f; } inline void clampAngle(QAngle& angle) { angle.x = std::clamp(angle.x, -89.0f, 89.0f); angle.y = std::clamp(angle.y, -180.0f, 180.0f); angle.z = 0.0f; } inline QAngle calcAngle(const Vector& src, const Vector& dst) { QAngle vAngle; Vector delta((src.x - dst.x), (src.y - dst.y), (src.z - dst.z)); double hyp = sqrt(delta.x*delta.x + delta.y*delta.y); vAngle.x = float(atanf(float(delta.z / hyp)) * 57.295779513082f); vAngle.y = float(atanf(float(delta.y / delta.x)) * 57.295779513082f); vAngle.z = 0.0f; if (delta.x >= 0.0) vAngle.y += 180.0f; return vAngle; } inline void angleVectors(const QAngle &angles, Vector& forward) { forward.x = cos(sdk::to_radians(angles.x)) * cos(sdk::to_radians(angles.y)); forward.y = cos(sdk::to_radians(angles.x)) * sin(sdk::to_radians(angles.y)); forward.z = -sin(sdk::to_radians(angles.x)); } inline float getDistance(Vector pos1, Vector pos2) { // Do 3d pythag float a = abs(pos1.x-pos2.x); float b = abs(pos1.y-pos2.y); float c = abs(pos1.z-pos2.z); return sqrt(pow(a, 2.f) + pow(b, 2.f) + pow(c, 2.f)); } inline float getDistanceNoSqrt(Vector pos1, Vector pos2) { // When you dont need an exact distance and just want to see if // something is x further than something else for example theres no need to sqrt it float a = abs(pos1.x-pos2.x); float b = abs(pos1.y-pos2.y); float c = abs(pos1.z-pos2.z); return pow(a, 2.f) + pow(b, 2.f) + pow(c, 2.f); } inline Vector2D directionFromYawAndVelocity(float yaw, Vector velocity) { auto cosYaw = std::cos(yaw / 180.0f * sdk::numeric_consts<float>::pi()); auto sinYaw = std::cos(yaw / 180.0f * sdk::numeric_consts<float>::pi()); return Vector2D { (velocity.x * cosYaw) + (velocity.y * sinYaw), (velocity.y * cosYaw) - (velocity.x * sinYaw), }; } bool worldToScreen(const Vector& origin, Vector& screen); inline float randomFloat(float div) { return static_cast<float>(std::rand()) / static_cast<float>(RAND_MAX / div); }
27.10687
130
0.672768
mov-rax-rax
0ac075f0ec84cebf2087c2465b308daef61587c9
4,632
cpp
C++
ModelViewer/ViewModels/TransformViewModel.cpp
seanisom/glTF-DXViewer
f1e7d88581e3598e397e563f529e7ee2bb4befd6
[ "MIT" ]
64
2018-05-25T06:18:42.000Z
2019-04-15T17:27:38.000Z
ModelViewer/ViewModels/TransformViewModel.cpp
seanisom/glTF-DXViewer
f1e7d88581e3598e397e563f529e7ee2bb4befd6
[ "MIT" ]
4
2018-05-26T10:53:33.000Z
2018-10-20T20:46:41.000Z
ModelViewer/ViewModels/TransformViewModel.cpp
seanisom/glTF-DXViewer
f1e7d88581e3598e397e563f529e7ee2bb4befd6
[ "MIT" ]
13
2019-09-19T00:50:07.000Z
2022-03-22T13:39:52.000Z
#include "pch.h" #include "TransformViewModel.h" using namespace ViewModels; float TransformViewModel::PositionX::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); return derived->GetTranslation().x; } return 0.0f; } void TransformViewModel::PositionX::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetTranslation(val, derived->GetTranslation().y, derived->GetTranslation().z); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::PositionY::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); return derived->GetTranslation().y; } return 0.0f; } void TransformViewModel::PositionY::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetTranslation(derived->GetTranslation().x, val, derived->GetTranslation().z); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::PositionZ::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); return derived->GetTranslation().z; } return 0.0f; } void TransformViewModel::PositionZ::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetTranslation(derived->GetTranslation().x, derived->GetTranslation().y, val); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::RotationX::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); //return derived->GetRotationX(); return derived->GetRotation().x; } return 0.0f; } void TransformViewModel::RotationX::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetRotationRoll(val); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::RotationY::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); //return derived->GetRotationY(); return derived->GetRotation().y; } return 0.0f; } void TransformViewModel::RotationY::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetRotationPitch(val); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::RotationZ::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); //return derived->GetRotationZ(); return derived->GetRotation().z; } return 0.0f; } void TransformViewModel::RotationZ::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetRotationYaw(val); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::ScaleX::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); return derived->GetScale().x; } return 0.0f; } void TransformViewModel::ScaleX::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetScale(val, derived->GetScale().y, derived->GetScale().z); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::ScaleY::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); return derived->GetScale().y; } return 0.0f; } void TransformViewModel::ScaleY::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetScale(derived->GetScale().x, val, derived->GetScale().z); OnPropertyChanged(getCallerName(__FUNCTION__)); } float TransformViewModel::ScaleZ::get() { if (_selectedNode) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); return derived->GetScale().z; } return 0.0f; } void TransformViewModel::ScaleZ::set(float val) { shared_ptr<GraphContainerNode> derived = dynamic_pointer_cast<GraphContainerNode>(_selectedNode); derived->SetScale(derived->GetScale().x, derived->GetScale().y, val); OnPropertyChanged(getCallerName(__FUNCTION__)); }
25.877095
88
0.778713
seanisom
0ac45f621c2bf5081e1d5aa4f16c7ed2f6087267
16,013
hpp
C++
Types.hpp
johndoe31415/acheron
16b7c05113fc02f41a5ac2705d209548e0e1b0d8
[ "CC0-1.0" ]
null
null
null
Types.hpp
johndoe31415/acheron
16b7c05113fc02f41a5ac2705d209548e0e1b0d8
[ "CC0-1.0" ]
null
null
null
Types.hpp
johndoe31415/acheron
16b7c05113fc02f41a5ac2705d209548e0e1b0d8
[ "CC0-1.0" ]
null
null
null
#ifndef __TYPES_HPP__ #define __TYPES_HPP__ #include <string> #include <set> #include <iostream> #include <sstream> #include <time.h> #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> #include <netdb.h> #include "kernel/sharedinfo.h" #define TYPEEXCEPTION(stream) { std::stringstream Strm; Strm << stream; throw TypeException(Strm.str()); } class TypeException { private: std::string Reason; public: TypeException(const std::string &Reason) { this->Reason = Reason; }; void Terminate() { std::cerr << "Type exception: " << Reason << std::endl; abort(); } const std::string& GetReason() const { return Reason; } }; class Type { }; class Type_Range { }; class Type_Int : public Type { private: unsigned int Value; public: unsigned int Get_Value() const { return Value; } Type_Int() { Value = 0; } Type_Int(unsigned int i) { Value = i; } Type_Int(const std::string &Integer) { Value = std::atoi(Integer.c_str()); } }; #define TYPE_RANGE_INT_VALIDCHARS "01234567890-!" class Type_Range_Int : public Type_Range { private: bool MinValid, MaxValid; bool Negated; unsigned int Min, Max; public: Type_Range_Int() { MinValid = false; MaxValid = false; Negated = false; } Type_Range_Int(Type_Int SingleTime) { MinValid = true; Min = SingleTime.Get_Value(); MaxValid = true; Max = SingleTime.Get_Value(); Negated = false; } Type_Range_Int(unsigned int From, bool FromValid, unsigned int To, bool ToValid, bool Negated) { MinValid = FromValid; Min = From; MaxValid = ToValid; Max = To; this->Negated = Negated; } Type_Range_Int(const std::string &Integer) { if (Integer.length() == 0) { MinValid = false; MaxValid = false; Negated = false; return; } if (Integer.find_first_not_of(TYPE_RANGE_INT_VALIDCHARS) != std::string::npos) { TYPEEXCEPTION("Illegal character for integer range at position " << (Integer.find_first_not_of(TYPE_RANGE_INT_VALIDCHARS) + 1)); } std::string Copy; Negated = (Integer.at(0) == '!'); if (Negated) { Copy = Integer.substr(1); } else { Copy = Integer; } if (Copy.find('-') == std::string::npos) { /* No range, a single integer */ MinValid = true; MaxValid = true; Min = std::atoi(Copy.c_str()); Max = std::atoi(Copy.c_str()); } else { std::size_t Pos = Copy.find('-'); MinValid = true; MaxValid = true; Min = std::atoi(Copy.substr(0, Pos).c_str()); Max = std::atoi(Copy.substr(Pos + 1).c_str()); } } bool Is_Satisfied(const Type_Int &SingleVal) const { bool Satisfied = true; if (MinValid) Satisfied = Satisfied && (SingleVal.Get_Value() >= Min); if (MaxValid) Satisfied = Satisfied && (SingleVal.Get_Value() <= Max); if (Negated) Satisfied = !Satisfied; return Satisfied; } bool Is_Valid() const { return MinValid || MaxValid || Negated; } void Get_Value(unsigned int &From, bool &FromValid, unsigned int &To, bool &ToValid, bool &Negated) const { From = this->Min; FromValid = this->MinValid; To = this->Max; ToValid = this->MaxValid; Negated = this->Negated; } }; class Type_String : public Type { public: bool operator<(const Type_String &Other) const { return Value < Other.Value; } bool operator==(const Type_String &Other) const { return Other.Value == Value; } private: std::string Value; public: const std::string& Get_Value() const { return Value; } Type_String() { } Type_String(const std::string &String) { Value = String; } }; class Type_Range_String : public Type_Range { private: std::set<Type_String> Values; public: Type_Range_String() { } Type_Range_String(const std::string &Strings) { if (Strings.length() == 0) return; std::size_t OldPos = 0; std::size_t Pos; while ((Pos = Strings.find('|', OldPos)) != std::string::npos) { Values.insert(Strings.substr(OldPos, Pos - OldPos)); OldPos = Pos + 1; } Values.insert(Strings.substr(OldPos, Pos - OldPos)); } bool Is_Satisfied(const Type_String &SingleString) const { if (Values.size() == 0) return true; return Values.find(SingleString) != Values.end(); } bool Is_Valid() const { return (Values.size() > 0); } const std::set<Type_String>& Get_Values() const { return Values; } }; class Type_RelTime : public Type { private: Type_Int TimeValue; public: Type_RelTime() { time_t Time; time(&Time); struct tm TimeStruct; localtime_r(&Time, &TimeStruct); TimeValue = (TimeStruct.tm_hour * 60) + TimeStruct.tm_min; } Type_RelTime(const std::string &TimeString) { if ((TimeString.length() != 5) || (TimeString.at(0) < '0') || (TimeString.at(0) > '2') || (TimeString.at(1) < '0') || (TimeString.at(1) > '9') || (TimeString.at(2) != ':') || (TimeString.at(3) < '0') || (TimeString.at(3) > '5') || (TimeString.at(4) < '0') || (TimeString.at(4) > '9') ) TYPEEXCEPTION("A relative time must be of the form hh:mm and contain exactly 5 characters - '" << TimeString << "' doesn't"); TimeValue = (std::atoi(TimeString.substr(0, 2).c_str()) * 60) + (std::atoi(TimeString.substr(3, 2).c_str())); if ((TimeValue.Get_Value() < 0) || (TimeValue.Get_Value() >= 1440)) { TYPEEXCEPTION("A relative time must be of the form hh:mm and be in the range from 00:00 to 23:59 '" << TimeString << "' isn't"); } } const Type_Int& Get_Value() const { return TimeValue; } }; class Type_Range_RelTime : public Type_Range { private: Type_Range_Int TimeRange; public: Type_Range_RelTime() { } Type_Range_RelTime(const std::string &TimeRngString) { if (TimeRngString.length() == 0) return; if (TimeRngString.length() == 5) { /* "hh:mm" */ Type_RelTime SingleTime = Type_RelTime(TimeRngString); TimeRange = Type_Range_Int(SingleTime.Get_Value()); } else if (TimeRngString.length() == 6) { /* "hh:mm-" || "-hh:mm" */ if (TimeRngString.at(0) == '-') { /* "-hh:mm" */ Type_RelTime SingleTime = Type_RelTime(TimeRngString.substr(1, 5)); TimeRange = Type_Range_Int(0, false, SingleTime.Get_Value().Get_Value(), true, false); } else if (TimeRngString.at(5) == '-') { /* "hh:mm-" */ Type_RelTime SingleTime = Type_RelTime(TimeRngString.substr(0, 5)); TimeRange = Type_Range_Int(SingleTime.Get_Value().Get_Value(), true, 0, false, false); } else { TYPEEXCEPTION("A realative time range must be of the form hh:mm, -hh:mm, hh:mm- or hh:mm-hh:mm and contain exactly 5, 6 or 11 characters - '" << TimeRngString << "' doesn't"); } } else if (TimeRngString.length() == 11) { /* "hh:mm-hh:mm" */ if (TimeRngString.at(5) == '-') { Type_RelTime StartTime = Type_RelTime(TimeRngString.substr(0, 5)); Type_RelTime EndTime = Type_RelTime(TimeRngString.substr(6, 5)); TimeRange = Type_Range_Int(StartTime.Get_Value().Get_Value(), true, EndTime.Get_Value().Get_Value(), true, false); } else { TYPEEXCEPTION("A realative time range must be of the form hh:mm, -hh:mm, hh:mm- or hh:mm-hh:mm and contain exactly 5, 6 or 11 characters - '" << TimeRngString << "' doesn't"); } } else { TYPEEXCEPTION("A realative time range must be of the form hh:mm, -hh:mm, hh:mm- or hh:mm-hh:mm and contain exactly 5, 6 or 11 characters - '" << TimeRngString << "' doesn't"); } } const Type_Range_Int& Get_Value() const { return TimeRange; } bool Is_Valid() const { return TimeRange.Is_Valid(); } bool Is_Satisfied(const Type_RelTime &Time) const { return TimeRange.Is_Satisfied(Time.Get_Value()); } }; #define TYPE_RANGE_IP_VALIDCHARS "01234567890." class Type_IPAddress : public Type { private: Type_Int IPValue; public: Type_IPAddress() { IPValue = (127 * 256 * 256 * 256) + (0 * 256 * 256) + (0 * 256) + 0; } Type_IPAddress(const std::string &IPString) { if (IPString.find_first_not_of(TYPE_RANGE_IP_VALIDCHARS) != std::string::npos) { TYPEEXCEPTION("Illegal character for IP address at position " << (IPString.find_first_not_of(TYPE_RANGE_IP_VALIDCHARS) + 1) << " in '" << IPString << "'"); } unsigned int IP = 0; std::size_t OldPos = 0; std::size_t Pos; for (int i = 1; i <= 4; i++) { Pos = IPString.find('.', OldPos); if ((Pos == std::string::npos) && (i != 4)) TYPEEXCEPTION(IPString << " is not a valid IP address"); std::string SubIP = IPString.substr(OldPos, Pos - OldPos); unsigned int SubIP_Int = std::atoi(SubIP.c_str()); if (SubIP_Int > 255) TYPEEXCEPTION(IPString << " is not a valid IP address"); IP = (IP * 256) + SubIP_Int; OldPos = Pos + 1; } IPValue = IP; } Type_IPAddress(unsigned int IP) { IPValue = IP; } const Type_Int& Get_Value() const { return IPValue; } }; class Type_Range_IPAddress : public Type_Range { private: Type_Range_Int IPRange; public: Type_Range_IPAddress() { } Type_Range_IPAddress(const std::string &IPRngString) { if (IPRngString.length() == 0) return; std::string Copy; bool Negated; Negated = IPRngString.at(0) == '!'; if (Negated) { Copy = IPRngString.substr(1); } else { Copy = IPRngString; } std::size_t Pos = Copy.find('-'); if (Pos == std::string::npos) { /* No range, single IP */ if (Copy.find_first_of("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ") == std::string::npos) { IPRange = Type_Range_Int(Type_IPAddress(Copy).Get_Value().Get_Value(), true, Type_IPAddress(Copy).Get_Value().Get_Value(), true, Negated); } else { /* Resolve DNS */ struct hostent *Hostname = gethostbyname(Copy.c_str()); if (!Hostname) { TYPEEXCEPTION("Failure in DNS resolution for hostname '" << Copy << "'."); } if (Hostname->h_length != 4) { TYPEEXCEPTION("DNS resolution for hostname '" << Copy << "' yielded non-IPv4-address of length " << Hostname->h_length << "."); } uint32_t IPValue; IPValue = ntohl(*((uint32_t*)Hostname->h_addr)); IPRange = Type_Range_Int(IPValue, true, IPValue, true, Negated); } } else { std::string From, To; From = Copy.substr(0, Pos); To = Copy.substr(Pos + 1); IPRange = Type_Range_Int(Type_IPAddress(From).Get_Value().Get_Value(), true, Type_IPAddress(To).Get_Value().Get_Value(), true, Negated); } } bool Is_Valid() const { return IPRange.Is_Valid(); } const Type_Range_Int& Get_Value() const { return IPRange; } bool Is_Satisfied(const Type_IPAddress &IP) const { return IPRange.Is_Satisfied(IP.Get_Value()); } }; class Type_BigInt { private: static const int size = 16; unsigned char chunks[size]; public: Type_BigInt() { for(int i = 0; i < size; ++i) this->chunks[i] = 0; } Type_BigInt(unsigned char* chunks, int count) { if(size != count) TYPEEXCEPTION("Failed to create Type_BigInt due to mismatch in size."); for(int i = count-1; i >= 0; --i) this->chunks[size-count+i] = chunks[i]; for(int i = 0; i < size - count; ++i) this->chunks[i] = 0; } Type_BigInt& operator=(const Type_BigInt& that) { if(size != that.size) TYPEEXCEPTION("Assignment of Type_BigInt failed due to mismatch in size."); for(int i = 0; i < size; ++i) chunks[i] = that.chunks[i]; return *this; } bool operator<(const Type_BigInt &Other) const { if(size != Other.size) TYPEEXCEPTION("Failed to compare Type_BigInts due to mismatch in size."); for(int i = 0; i < size; ++i) { if(chunks[i] > Other.chunks[i]) return false; else if(chunks[i] < Other.chunks[i]) return true; } // equal return false; } bool operator>(const Type_BigInt &Other) const { if(size != Other.size) TYPEEXCEPTION("Failed to compare Type_BigInts due to mismatch in size."); for(int i = 0; i < size; ++i) { if(chunks[i] > Other.chunks[i]) return true; else if(chunks[i] < Other.chunks[i]) return false; } // equal return false; } bool operator==(const Type_BigInt &Other) const { if(size != Other.size) return false; for(int i = 0; i < size; ++i) if(chunks[i] != Other.chunks[i]) return false; return true; } friend std::ostream& operator<<(std::ostream &Strm, const Type_BigInt &bigInt); }; class Type_IP6Address { private: Type_BigInt IP6Value; public: Type_IP6Address() { } Type_IP6Address(Type_BigInt bigInt) { IP6Value = bigInt; } Type_IP6Address(const std::string &IP6String) { struct in6_addr addr; if(!inet_pton(AF_INET6, IP6String.c_str(), &addr)) TYPEEXCEPTION(IP6String << " is not a valid IP6 address"); IP6Value = Type_BigInt((unsigned char*)&addr.in6_u, 16); } Type_IP6Address(const ipv6_addr_t& IP6Addr) { IP6Value = Type_BigInt((unsigned char*)&IP6Addr.u8, 16); } Type_IP6Address& operator=(const Type_IP6Address& that) { IP6Value = that.IP6Value; return *this; } bool operator<(const Type_IP6Address &Other) const { return IP6Value < Other.IP6Value; } bool operator<=(const Type_IP6Address &Other) const { return !(IP6Value > Other.IP6Value); } bool operator>(const Type_IP6Address &Other) const { return IP6Value > Other.IP6Value; } bool operator>=(const Type_IP6Address &Other) const { return !(IP6Value < Other.IP6Value); } bool operator==(const Type_IP6Address &Other) const { return IP6Value == Other.IP6Value; } const Type_BigInt Get_Value() const { return IP6Value; } }; #define TYPE_RANGE_IP6ADDRESS_VALIDCHARS "01234567890abcdefABCDEF-!:" class Type_Range_IP6Address : public Type_Range { private: bool MinValid, MaxValid; bool Negated; Type_IP6Address Min, Max; public: Type_Range_IP6Address() { } Type_Range_IP6Address(const std::string &IP6RngString) { if (IP6RngString.length() == 0) { MinValid = false; MaxValid = false; Negated = false; return; } if (IP6RngString.find_first_not_of(TYPE_RANGE_IP6ADDRESS_VALIDCHARS) != std::string::npos) { TYPEEXCEPTION("Illegal character for IPv6 range at position " << (IP6RngString.find_first_not_of(TYPE_RANGE_IP6ADDRESS_VALIDCHARS) + 1)); } std::string Copy; Negated = (IP6RngString.at(0) == '!'); if (Negated) { Copy = IP6RngString.substr(1); } else { Copy = IP6RngString; } if (IP6RngString.find('-') == std::string::npos) { /* No range, a single integer */ MinValid = true; MaxValid = true; Min = Type_IP6Address(Copy); Max = Type_IP6Address(Copy); } else { std::size_t Pos = Copy.find('-'); MinValid = true; MaxValid = true; Min = Type_IP6Address(Copy.substr(0, Pos).c_str()); Max = Type_IP6Address(Copy.substr(Pos + 1).c_str()); } } Type_Range_IP6Address(const Type_IP6Address& IP6Addr) { MinValid = true; Min = Type_IP6Address(IP6Addr); Max = Type_IP6Address(IP6Addr); MaxValid = true; Negated = false; } Type_Range_IP6Address(const ipv6_addr_t& IP6Addr) { MinValid = true; Min = Type_IP6Address(IP6Addr); Max = Type_IP6Address(IP6Addr); MaxValid = true; Negated = false; } Type_Range_IP6Address(const Type_IP6Address& From, bool FromValid, const Type_IP6Address& To, bool ToValid, bool Negated) { MinValid = FromValid; Min = From; MaxValid = ToValid; Max = To; this->Negated = Negated; } bool Is_Satisfied(const Type_IP6Address &SingleVal) const { bool Satisfied = true; if (MinValid) Satisfied = Satisfied && (SingleVal >= Min); if (MaxValid) Satisfied = Satisfied && (SingleVal <= Max); if (Negated) Satisfied = !Satisfied; return Satisfied; } bool Is_Valid() const { return MinValid || MaxValid || Negated; } void Get_Value(Type_IP6Address& From, bool& FromValid, Type_IP6Address& To, bool& ToValid, bool& Negated) const { From = this->Min; FromValid = this->MinValid; To = this->Max; ToValid = this->MaxValid; Negated = this->Negated; } }; #endif
28.043783
180
0.644351
johndoe31415
0ac54c15e2e407a7ee4fe78aee89483657780673
7,513
cpp
C++
src/tests/manual_tests/particle_system_solver3_tests.cpp
PavelBlend/fluid-engine-dev
45b4bdbdb4c6d8c0beebc682180469198203b0ef
[ "MIT" ]
1,355
2016-05-08T07:29:22.000Z
2022-03-30T13:59:35.000Z
src/tests/manual_tests/particle_system_solver3_tests.cpp
Taiyuan-Zhang/fluid-engine-dev
45b4bdbdb4c6d8c0beebc682180469198203b0ef
[ "MIT" ]
208
2016-05-25T19:47:27.000Z
2022-01-17T04:18:29.000Z
src/tests/manual_tests/particle_system_solver3_tests.cpp
Taiyuan-Zhang/fluid-engine-dev
45b4bdbdb4c6d8c0beebc682180469198203b0ef
[ "MIT" ]
218
2016-08-23T16:51:10.000Z
2022-03-31T03:55:48.000Z
// Copyright (c) 2018 Doyub Kim // // I am making my contributions/submissions to this project solely in my // personal capacity and am not conveying any rights to any intellectual // property of any third parties. #include <manual_tests.h> #include <jet/rigid_body_collider3.h> #include <jet/constant_vector_field3.h> #include <jet/particle_system_solver3.h> #include <jet/plane3.h> #include <jet/point_particle_emitter3.h> using namespace jet; JET_TESTS(ParticleSystemSolver3); JET_BEGIN_TEST_F(ParticleSystemSolver3, PerfectBounce) { Plane3Ptr plane = std::make_shared<Plane3>(Vector3D(0, 1, 0), Vector3D()); RigidBodyCollider3Ptr collider = std::make_shared<RigidBodyCollider3>(plane); ParticleSystemSolver3 solver; solver.setCollider(collider); solver.setDragCoefficient(0.0); solver.setRestitutionCoefficient(1.0); ParticleSystemData3Ptr particles = solver.particleSystemData(); particles->addParticle({0.0, 3.0, 0.0}, {1.0, 0.0, 0.0}); Array1<double> x(1000); Array1<double> y(1000); char filename[256]; snprintf(filename, sizeof(filename), "data.#line2,0000,x.npy"); saveData(x.constAccessor(), 0, filename); snprintf(filename, sizeof(filename), "data.#line2,0000,y.npy"); saveData(y.constAccessor(), 0, filename); Frame frame; frame.timeIntervalInSeconds = 1.0 / 300.0; for (; frame.index < 1000; frame.advance()) { solver.update(frame); x[frame.index] = particles->positions()[0].x; y[frame.index] = particles->positions()[0].y; snprintf( filename, sizeof(filename), "data.#line2,%04d,x.npy", frame.index); saveData(x.constAccessor(), frame.index, filename); snprintf( filename, sizeof(filename), "data.#line2,%04d,y.npy", frame.index); saveData(y.constAccessor(), frame.index, filename); } } JET_END_TEST_F JET_BEGIN_TEST_F(ParticleSystemSolver3, HalfBounce) { Plane3Ptr plane = std::make_shared<Plane3>(Vector3D(0, 1, 0), Vector3D()); RigidBodyCollider3Ptr collider = std::make_shared<RigidBodyCollider3>(plane); ParticleSystemSolver3 solver; solver.setCollider(collider); solver.setDragCoefficient(0.0); solver.setRestitutionCoefficient(0.5); ParticleSystemData3Ptr particles = solver.particleSystemData(); particles->addParticle({0.0, 3.0, 0.0}, {1.0, 0.0, 0.0}); Array1<double> x(1000); Array1<double> y(1000); char filename[256]; snprintf(filename, sizeof(filename), "data.#line2,0000,x.npy"); saveData(x.constAccessor(), 0, filename); snprintf(filename, sizeof(filename), "data.#line2,0000,y.npy"); saveData(y.constAccessor(), 0, filename); Frame frame; frame.timeIntervalInSeconds = 1.0 / 300.0; for (; frame.index < 1000; frame.advance()) { solver.update(frame); x[frame.index] = particles->positions()[0].x; y[frame.index] = particles->positions()[0].y; snprintf( filename, sizeof(filename), "data.#line2,%04d,x.npy", frame.index); saveData(x.constAccessor(), frame.index, filename); snprintf( filename, sizeof(filename), "data.#line2,%04d,y.npy", frame.index); saveData(y.constAccessor(), frame.index, filename); } } JET_END_TEST_F JET_BEGIN_TEST_F(ParticleSystemSolver3, HalfBounceWithFriction) { Plane3Ptr plane = std::make_shared<Plane3>(Vector3D(0, 1, 0), Vector3D()); RigidBodyCollider3Ptr collider = std::make_shared<RigidBodyCollider3>(plane); collider->setFrictionCoefficient(0.04); ParticleSystemSolver3 solver; solver.setCollider(collider); solver.setDragCoefficient(0.0); solver.setRestitutionCoefficient(0.5); ParticleSystemData3Ptr particles = solver.particleSystemData(); particles->addParticle({0.0, 3.0, 0.0}, {1.0, 0.0, 0.0}); Array1<double> x(1000); Array1<double> y(1000); char filename[256]; snprintf(filename, sizeof(filename), "data.#line2,0000,x.npy"); saveData(x.constAccessor(), 0, filename); snprintf(filename, sizeof(filename), "data.#line2,0000,y.npy"); saveData(y.constAccessor(), 0, filename); Frame frame; frame.timeIntervalInSeconds = 1.0 / 300.0; for (; frame.index < 1000; frame.advance()) { solver.update(frame); x[frame.index] = particles->positions()[0].x; y[frame.index] = particles->positions()[0].y; snprintf( filename, sizeof(filename), "data.#line2,%04d,x.npy", frame.index); saveData(x.constAccessor(), frame.index, filename); snprintf( filename, sizeof(filename), "data.#line2,%04d,y.npy", frame.index); saveData(y.constAccessor(), frame.index, filename); } } JET_END_TEST_F JET_BEGIN_TEST_F(ParticleSystemSolver3, NoBounce) { Plane3Ptr plane = std::make_shared<Plane3>(Vector3D(0, 1, 0), Vector3D()); RigidBodyCollider3Ptr collider = std::make_shared<RigidBodyCollider3>(plane); ParticleSystemSolver3 solver; solver.setCollider(collider); solver.setDragCoefficient(0.0); solver.setRestitutionCoefficient(0.0); ParticleSystemData3Ptr particles = solver.particleSystemData(); particles->addParticle({0.0, 3.0, 0.0}, {1.0, 0.0, 0.0}); Array1<double> x(1000); Array1<double> y(1000); char filename[256]; snprintf(filename, sizeof(filename), "data.#line2,0000,x.npy"); saveData(x.constAccessor(), 0, filename); snprintf(filename, sizeof(filename), "data.#line2,0000,y.npy"); saveData(y.constAccessor(), 0, filename); Frame frame; frame.timeIntervalInSeconds = 1.0 / 300.0; for (; frame.index < 1000; frame.advance()) { solver.update(frame); x[frame.index] = particles->positions()[0].x; y[frame.index] = particles->positions()[0].y; snprintf( filename, sizeof(filename), "data.#line2,%04d,x.npy", frame.index); saveData(x.constAccessor(), frame.index, filename); snprintf( filename, sizeof(filename), "data.#line2,%04d,y.npy", frame.index); saveData(y.constAccessor(), frame.index, filename); } } JET_END_TEST_F JET_BEGIN_TEST_F(ParticleSystemSolver3, Update) { auto plane = Plane3::builder() .withNormal({0, 1, 0}) .withPoint({0, 0, 0}) .makeShared(); auto collider = RigidBodyCollider3::builder() .withSurface(plane) .makeShared(); auto wind = ConstantVectorField3::builder() .withValue({1, 0, 0}) .makeShared(); auto emitter = PointParticleEmitter3::builder() .withOrigin({0, 3, 0}) .withDirection({0, 1, 0}) .withSpeed(5) .withSpreadAngleInDegrees(45.0) .withMaxNumberOfNewParticlesPerSecond(300) .makeShared(); auto solver = ParticleSystemSolver3::builder().makeShared(); solver->setCollider(collider); solver->setEmitter(emitter); solver->setWind(wind); solver->setDragCoefficient(0.0); solver->setRestitutionCoefficient(0.5); for (Frame frame(0, 1.0 / 60.0); frame.index < 360; ++frame) { solver->update(frame); saveParticleDataXy(solver->particleSystemData(), frame.index); } } JET_END_TEST_F
32.383621
78
0.637828
PavelBlend
0ac6d9dc3aa983684e889f76a0f91751dfd1e04d
2,160
cc
C++
test/exprtest.cc
larskuhtz/MoCS
8ea4aafb4a2036807af147efeac915876cf7390b
[ "BSD-3-Clause" ]
1
2020-07-16T18:23:55.000Z
2020-07-16T18:23:55.000Z
test/exprtest.cc
larskuhtz/MoCS
8ea4aafb4a2036807af147efeac915876cf7390b
[ "BSD-3-Clause" ]
null
null
null
test/exprtest.cc
larskuhtz/MoCS
8ea4aafb4a2036807af147efeac915876cf7390b
[ "BSD-3-Clause" ]
null
null
null
/* *** MOCS-COPYRIGHT-NOTICE-BEGIN *** * * This copyright notice is auto-generated by ./add-copyright-notice. * Additional copyright notices must be added below the last line of this notice. * * MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/): "test/exprtest.cc". * The content of this file is copyright of Saarland University - * Copyright (C) 2009 Saarland University, Reactive Systems Group, Lars Kuhtz. * * This file is part of MoCS (https://lewis.cs.uni-saarland.de/tools/mocs/). * * License: three-clause BSD style license. * The license text can be found in the file LICENSE. * * *** MOCS-COPYRIGHT-NOTICE-END *** */ #include <fstream> #include "expr.hh" prop_t prop(int i) { return prop_t(1,i); } int main(int argsc, char ** args) { efac_ptr c = efac::newEfac(); expr_t p0 = c->mkProp(prop(0)); expr_t p1 = c->mkProp(prop(1)); expr_t p2 = c->mkProp(prop(2)); std::cerr << "check: " << "3 == " << c->size() << std::endl; expr_t p0_ = c->mkProp(prop(0)); expr_t p1_ = c->mkProp(prop(1)); expr_t p2_ = c->mkProp(prop(2)); //p0.impl()->debug(); //p0_.impl()->debug(); std::cerr << "check: " << "3 == " << c->size() << std::endl; expr_t ct = c->mkConst(true); expr_t cf = c->mkConst(false); std::cerr << "check: " << "5 == " << c->size() << std::endl; expr_t ct_ = c->mkConst(true); expr_t cf_ = c->mkConst(false); std::cerr << "check: " << "5 == " << c->size() << std::endl; expr_t np0 = c->mkNProp(prop(0)); expr_t np1 = c->mkNProp(prop(1)); expr_t np2 = c->mkNProp(prop(2)); std::cerr << "check: " << "8 == " << c->size() << std::endl; expr_t np0_ = c->mkNProp(prop(0)); expr_t np1_ = c->mkNProp(prop(1)); expr_t np2_ = c->mkNProp(prop(2)); std::cerr << "check: " << "8 == " << c->size() << std::endl; expr_t p0_and_p0 = p0 && p0; std::cerr << "check: " << "8 == " << c->size() << std::endl; expr_t a0 = p0 && p1; std::cerr << "check: " << "9 == " << c->size() << std::endl; expr_t a1 = p0 && p1 && p2; std::cerr << "check: " << "10 == " << c->size() << std::endl; return 0; }
27
81
0.554167
larskuhtz
0ac9c4f0420b16d1baa9218e8922bf8853a8b3a1
6,212
hpp
C++
RobWork/src/rw/proximity/rwstrategy/SAPFilterStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
1
2021-12-29T14:16:27.000Z
2021-12-29T14:16:27.000Z
RobWork/src/rw/proximity/rwstrategy/SAPFilterStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
RobWork/src/rw/proximity/rwstrategy/SAPFilterStrategy.hpp
ZLW07/RobWork
e713881f809d866b9a0749eeb15f6763e64044b3
[ "Apache-2.0" ]
null
null
null
/******************************************************************************** * Copyright 2009 The Robotics Group, The Maersk Mc-Kinney Moller Institute, * Faculty of Engineering, University of Southern Denmark * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. ********************************************************************************/ #ifndef RW_PROXIMITY_SAPFilterStrategy_HPP_ #define RW_PROXIMITY_SAPFilterStrategy_HPP_ #if !defined(SWIG) #include "ProximityFilterStrategy.hpp" #include "ProximitySetup.hpp" #endif namespace rw { namespace models { class WorkCell; }} // namespace rw::models namespace rw { namespace proximity { /** * @brief This is a Sweep-And-Prune based filter strategy (broadphase strategy). * */ class SAPFilterStrategy : public ProximityFilterStrategy { public: //! @brief smart pointer type to this class typedef rw::core::Ptr< SAPFilterStrategy > Ptr; private: /** * @brief the proximity cache of the basic filter */ struct Cache : public ProximityCache { public: Cache (void* owner) : ProximityCache (owner){}; size_t size () const { return 0; }; void clear (){}; }; struct Filter : public ProximityFilter { public: Filter (kinematics::FramePairSet::iterator front, kinematics::FramePairSet::iterator end) : _front (front), _end (end) {} void pop () { ++_front; }; kinematics::FramePair frontAndPop () { kinematics::FramePair res = *_front; pop (); return (res); } rw::kinematics::FramePair front () { return *_front; }; bool isEmpty () { return _front == _end; }; private: kinematics::FramePairSet::iterator _front, _end; }; public: /** * @brief constructor - the ProximitySetup will be extracted from * the workcell description if possible. * * @param workcell [in] the workcell. */ SAPFilterStrategy (rw::core::Ptr< rw::models::WorkCell > workcell); /** * @brief constructor - constructs frame pairs based on the \b setup * @param workcell [in] the workcell * @param setup [in] the ProximitySetup describing exclude/include relations */ SAPFilterStrategy (rw::core::Ptr< rw::models::WorkCell > workcell, const ProximitySetup& setup); //! @brief destructor virtual ~SAPFilterStrategy (){}; //////// interface inherited from BroadPhaseStrategy //! @copydoc ProximityFilterStrategy::reset virtual void reset (const rw::kinematics::State& state); //! @copydoc ProximityFilterStrategy::createProximityCache virtual rw::core::Ptr<rw::proximity::ProximityCache> createProximityCache () { return rw::core::ownedPtr (new Cache (this)); } //! @copydoc ProximityFilterStrategy::update virtual rw::core::Ptr<rw::proximity::ProximityFilter> update (const rw::kinematics::State& state); //! @copydoc ProximityFilterStrategy::createProximityCache virtual rw::core::Ptr<rw::proximity::ProximityFilter> update (const rw::kinematics::State& state, rw::core::Ptr<rw::proximity::ProximityCache> data); /** * @copydoc ProximityFilterStrategy::getProximitySetup */ ProximitySetup& getProximitySetup (); /** * @brief Adds geometry associated to frame * @param frame [in] Frame which has the geometry associated */ virtual void addGeometry (rw::kinematics::Frame* frame, const rw::geometry::Geometry::Ptr); /** * @brief Removes the geometric model with name \b rw::geometry::Geometry::Ptr and which is * associated with \b frame. * * @param frame [in] Frame which has the geometry associated */ virtual void removeGeometry (rw::kinematics::Frame* frame, const rw::geometry::Geometry::Ptr); /** * @brief Removes the geometric model with name \b geometryId and which is associated with * \b frame. * * @param frame [in] Frame which has the geometry associated * @param geometryId [in] Name of geometry */ virtual void removeGeometry (rw::kinematics::Frame* frame, const std::string& geometryId); /** * @copydoc ProximityFilterStrategy::addRule */ virtual void addRule (const ProximitySetupRule& rule); /** * @copydoc ProximityFilterStrategy::removeRule */ virtual void removeRule (const ProximitySetupRule& rule); private: rw::core::Ptr< rw::models::WorkCell > _workcell; ProximitySetup _psetup; kinematics::FramePairSet _collisionPairs; kinematics::FrameMap< std::vector< std::string > > _frameToGeoIdMap; void applyRule (const ProximitySetupRule& rule, rw::core::Ptr< rw::models::WorkCell > workcell, rw::kinematics::FramePairSet& result); void initialize (); void initializeCollisionFramePairs (const rw::kinematics::State& state); }; #ifdef RW_USE_DEPREACTED typedef rw::core::Ptr< SAPFilterStrategy > SAPFilterStrategyPtr; #endif }} // namespace rw::proximity #endif /* SAPFilterStrategy_HPP_ */
35.295455
106
0.590148
ZLW07
0ace65782b9a26fa77a5395599ce45034270e3e5
1,462
cpp
C++
cpp/src/exercise/e0100/e0004.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0100/e0004.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
cpp/src/exercise/e0100/e0004.cpp
ajz34/LeetCodeLearn
70ff8a3c17199a100819b356735cd9b13ff166a7
[ "MIT" ]
null
null
null
#include "extern.h" using namespace std; class Solution { public: double findMedianSortedArrays_slow(vector<int>& nums1, vector<int>& nums2) { auto v = vector<int>(); v.insert(v.end(), nums1.cbegin(), nums1.cend()); v.insert(v.end(), nums2.cbegin(), nums2.cend()); sort(v.begin(), v.end()); if (v.size() % 2 == 1) return v[v.size() / 2]; else return double(v[(v.size() + 1) / 2] + v[(v.size() - 1) / 2]) / 2; } double findMedianSortedArrays(vector<int>& nums1, vector<int>& nums2) { size_t s = nums1.size() + nums2.size(); auto v = vector<int>(s, 0); auto p1 = nums1.cbegin(); auto p2 = nums2.cbegin(); auto pt = v.begin(); size_t t = 0; while (p1 != nums1.cend() && p2 != nums2.cend()) { if (*p1 > *p2) { *pt = *p2; ++p2; } else { *pt = *p1; ++p1; } ++pt; } while (p1 != nums1.cend()) { *pt = *p1; ++p1; ++pt; } while (p2 != nums2.cend()) { *pt = *p2; ++p2; ++pt; } if (s % 2 == 1) return v[s / 2]; else return double(v[(s + 1) / 2] + v[(s - 1) / 2]) / 2; } }; TEST(e0100, e0004) { vector<int> n1{}, n2{}; n1 = str_to_vec<int>("[1, 3]"); n2 = str_to_vec<int>("[2]"); ASSERT_EQ(Solution().findMedianSortedArrays(n1, n2), 2); n1 = str_to_vec<int>("[1, 2]"); n2 = str_to_vec<int>("[3, 4]"); ASSERT_EQ(Solution().findMedianSortedArrays(n1, n2), 2.5); }
34.809524
80
0.497948
ajz34
0ad0ed983b04fc8ec8b01da72acf293b22b292e9
679
hpp
C++
include/cjdb/iterator/reference.hpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
4
2019-03-02T01:09:07.000Z
2019-10-16T15:46:21.000Z
include/cjdb/iterator/reference.hpp
cjdb/cjdb-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
5
2019-11-29T12:23:55.000Z
2019-12-14T13:03:00.000Z
include/cjdb/iterator/reference.hpp
cjdb/clang-concepts-ranges
7019754e97c8f3863035db74de62004ae3814954
[ "Apache-2.0" ]
3
2020-06-08T18:27:28.000Z
2021-03-27T17:49:46.000Z
// Copyright (c) Christopher Di Bella. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // #ifndef CJDB_ITERATOR_REFERENCE_HPP #define CJDB_ITERATOR_REFERENCE_HPP #include "cjdb/detail/iterator/reference.hpp" #include "cjdb/detail/iterator/iter_move.hpp" #include "cjdb/type_traits/type_traits.hpp" #include <utility> namespace cjdb { template<detail_iterator_reference::dereferenceable T> using iter_reference_t = decltype(*std::declval<T&>()); template<typename T> requires detail_iter_move::iter_move_can_reference<T> using iter_rvalue_reference_t = decltype(ranges::iter_move(std::declval<T&>())); } // namespace cjdb #endif // CJDB_ITERATOR_REFERENCE_HPP
30.863636
81
0.792342
cjdb
bd598bc53274c46a279871c521f740e1329f5819
16,118
cpp
C++
flir_lepton_sensor/src/flir_lepton_hw_iface.cpp
angetria/flir_lepton_rpi2
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
15
2015-11-10T10:39:53.000Z
2022-03-29T07:07:53.000Z
flir_lepton_sensor/src/flir_lepton_hw_iface.cpp
angetria/flir_lepton
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
6
2015-10-23T12:18:45.000Z
2019-07-02T09:55:46.000Z
flir_lepton_sensor/src/flir_lepton_hw_iface.cpp
angetria/flir_lepton_rpi2
46b1de815e2bfb752954fb2c3648d416f56e6c93
[ "BSD-3-Clause" ]
6
2017-04-13T12:28:38.000Z
2019-07-03T21:58:51.000Z
/********************************************************************* * * * * Software License Agreement (BSD License) * * * * Copyright (c) 2015, P.A.N.D.O.R.A. Team. * * All rights reserved. * * * * Redistribution and use in source and binary forms, with or without * * modification, are permitted provided that the following conditions * * are met: * * * * * Redistributions of source code must retain the above copyright * * notice, this list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above * * copyright notice, this list of conditions and the following * * disclaimer in the documentation and/or other materials provided * * with the distribution. * * * Neither the name of the P.A.N.D.O.R.A. Team nor the names of its * * contributors may be used to endorse or promote products derived * * from this software without specific prior written permission. * * * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS * * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT * * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS * * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN * * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * * POSSIBILITY OF SUCH DAMAGE. * * * * Author: Konstantinos Panayiotou, Angelos Triantafyllidis, * * Tsirigotis Christos * * Maintainer: Konstantinos Panayiotou * * Email: klpanagi@gmail.com * * * *********************************************************************/ #include "flir_lepton_hw_iface.h" #include "flir_lepton_utils.h" /* ---< SPI interface related >--- */ #include <fcntl.h> #include <sys/ioctl.h> #include <unistd.h> #include <linux/types.h> #include <linux/spi/spidev.h> #include <ros/package.h> /* ------------------------------- */ namespace flir_lepton { namespace flir_lepton_sensor { FlirLeptonHWIface::FlirLeptonHWIface(const std::string& ns): nh_(ns), vospiFps_(25) { loadParameters(); calibMap_ = Utils::loadThermalCalibMap(calibFileUri_); flirSpi_.configSpiParams(nh_); openDevice(); /* ----------------------- Publishers --------------------------------- */ temperPublisher_ = nh_.advertise<flir_lepton_msgs::TemperaturesMsg>( temperTopic_, 1); if(pubGray_) { grayPublisher_ = nh_.advertise<sensor_msgs::Image>(grayTopic_, 1); } if(pubRgb_) { rgbPublisher_ = nh_.advertise<sensor_msgs::Image>(rgbTopic_, 1); rgbImage_.header.frame_id = frameId_; rgbImage_.height = IMAGE_HEIGHT; rgbImage_.width = IMAGE_WIDTH; rgbImage_.encoding = "rgb8"; rgbImage_.is_bigendian = 0; rgbImage_.step = IMAGE_WIDTH * sizeof(uint8_t) * 3; } batchPublisher_ = nh_.advertise<flir_lepton_msgs::FlirLeptonBatchMsg>( batchTopic_, 1); /* -------------------------------------------------------------------- */ flirDataFrame_.allocateBuffers(); allocateFrameData(); grayImage_.header.frame_id = frameId_; grayImage_.height = IMAGE_HEIGHT; grayImage_.width = IMAGE_WIDTH; grayImage_.encoding = "mono8"; grayImage_.is_bigendian = 0; grayImage_.step = IMAGE_WIDTH * sizeof(uint8_t); temperMsg_.header.frame_id = frameId_; temperMsg_.values.layout.dim.push_back(std_msgs::MultiArrayDimension()); temperMsg_.values.layout.dim[0].size = IMAGE_HEIGHT; temperMsg_.values.layout.dim.push_back(std_msgs::MultiArrayDimension()); temperMsg_.values.layout.dim[1].size = IMAGE_WIDTH; batchMsg_.header.frame_id = frameId_; initThreadedIO(); /* -------------------------------------------------------------------- */ } FlirLeptonHWIface::~FlirLeptonHWIface() { closeDevice(); ioThread_.interrupt(); ioThread_.join(); } void FlirLeptonHWIface::loadParameters(void) { int param; std::string calibFileName; /* ----------- Load Parameters ------------ */ // Load calibration dataset file name. Datasets are stored under the // flir_lepton_auxiliary package, into the datasets directory. // (flir_lepton_auxiliary/datasets) nh_.param<std::string>("dataset_file_name", calibFileName, "dataset_spline"); // Search for flir_lepton_auxiliary package absolute path, using rospack. std::string datasetPath = ros::package::getPath("flir_lepton_auxiliary") + "/datasets/"; calibFileUri_ = datasetPath + calibFileName; ROS_INFO("Temperature calibration dataset file: [%s]", calibFileUri_.c_str()); nh_.param<std::string>("flir_urdf/camera_optical_frame", frameId_, "/flir_optical_frame"); nh_.param<std::string>("published_topics/flir_gray_image_topic", grayTopic_, "/flir_lepton/image/gray"); nh_.param<std::string>("published_topics/flir_rgb_image_topic", rgbTopic_, "/flir_lepton/image/rgb"); nh_.param<std::string>("published_topics/flir_temper_topic", temperTopic_, "flir_lepton/temperatures"); nh_.param<std::string>("published_topics/flir_batch_topic", batchTopic_, "flir_lepton/batch"); nh_.param<bool>("gray_image", pubGray_, true); nh_.param<bool>("rgb_image", pubRgb_, true); /* ----------------------------------------- */ nh_.param<int32_t>("iface/packet_size", param, 164); flirDataFrame_.packetSize = param; flirDataFrame_.packetSize16 = param / 2; nh_.param<int32_t>("iface/packets_per_frame", param, 60); flirDataFrame_.packetsPerFrame = param; } void FlirLeptonHWIface::FlirSpi::configSpiParams( const ros::NodeHandle& nh) { int param; mode = SPI_MODE_3; nh.param<int32_t>("iface/bits", param, 8); bits = param; nh.param<int32_t>("iface/speed", param, 16000000); speed = param; nh.param<int32_t>("iface/delay", param, 0); delay = param; nh.param<std::string>("iface/device_port", devicePort, "/dev/spidev0.0"); } void FlirLeptonHWIface::initThreadedIO(void) { ioThread_ = boost::thread(&FlirLeptonHWIface::readFrame, this); } void FlirLeptonHWIface::FlirDataFrame::allocateBuffers(void) { frameBuffer = new uint8_t[packetSize * packetsPerFrame]; cleanDataBuffer = new uint16_t[IMAGE_HEIGHT * IMAGE_WIDTH]; frameData = new uint16_t[IMAGE_HEIGHT * IMAGE_WIDTH]; } void FlirLeptonHWIface::allocateFrameData(void) { lastFrame_ = new uint16_t[IMAGE_HEIGHT * IMAGE_WIDTH]; } void FlirLeptonHWIface::run(void) { //readFrame();; //ROS_INFO("[Flir-Lepton]: VoSPI average fps: %f", vospiFps_); now_ = ros::Time::now(); processFrame(); //Batch msg creation fillBatchMsg(); /* --------< Publish Messages >-------- */ if(pubGray_) { grayPublisher_.publish(grayImage_); } if(pubRgb_) { rgbPublisher_.publish(rgbImage_); } temperPublisher_.publish(temperMsg_); batchPublisher_.publish(batchMsg_); /* ------------------------------------ */ } void FlirLeptonHWIface::readFrame(void) { int packetNumber = -1; int resets = 0; int restarts = 0; // Pointer to FlirDataFrame struct member buffer. uint8_t* rawBuffer = flirDataFrame_.frameBuffer; uint16_t* cleanData = flirDataFrame_.cleanDataBuffer; uint16_t* frameData = flirDataFrame_.frameData; uint16_t packetSize = flirDataFrame_.packetSize; uint16_t packetsPerFrame = flirDataFrame_.packetsPerFrame; uint16_t packetSize16 = packetSize / 2; uint16_t frameSize16 = packetSize16 * packetsPerFrame; uint16_t maxVal, minVal; uint16_t value, temp; boost::posix_time::ptime begin, end; /* ------------------ Read raw frame data from spi -------------------- */ while(1) { begin = boost::posix_time::microsec_clock::local_time(); try { restarts = 0; for (uint16_t i = 0; i < packetsPerFrame; i++) { read(flirSpi_.handler, &rawBuffer[packetSize * i], sizeof(uint8_t) * packetSize); // flir sends discard packets that we need to resolve packetNumber = rawBuffer[i * packetSize + 1]; if (packetNumber != i) { // if it is a drop packet, reset i i = -1; resets += 1; // sleep for 1ms ros::Duration(0.01).sleep(); // If resets reach this value, we assume an error on communication with // flir-lepton sensor. Perform communication restart if (resets == MAX_RESETS_ERROR) //Reach 750 sometimes { restarts ++; ROS_ERROR("[Flir-Lepton]: VoSPI packages are corrupted"); ROS_WARN("[Flir-Lepton]: SPI communication restarting..."); closeDevice(); boost::this_thread::sleep(boost::posix_time::milliseconds(25)); openDevice(); resets = 0; } // If true we assume an exit status.. Kill process and exit if (restarts > MAX_RESTART_ATTEMPS_EXIT) { ROS_FATAL("[Flir-Lepton]: Sensor does not respond. Exiting..."); ros::shutdown(); exit(1); } } } /* -------------------------------------------------------------------- */ // Cast to uint16_t in (2 bytes). uint16_t* rawBuffer16 = (uint16_t*) rawBuffer; uint16_t cleanDataCount = 0; maxVal = 0; minVal = -1; // Process this acquired from spi port, frame and create the data vector for (int i = 0; i < frameSize16; i++) { //Discard the first 4 bytes. it is the header. if (i % packetSize16 < 2) continue; temp = rawBuffer[i * 2]; rawBuffer[i * 2] = rawBuffer[i * 2 + 1]; rawBuffer[i * 2 + 1] = temp; value = rawBuffer16[i]; cleanData[cleanDataCount] = value; cleanDataCount++; if (value > maxVal) {maxVal = value;} if (value < minVal) {minVal = value;} } mtxLock_.lock(); // Copy cleanData to class frameData buffer memcpy(frameData, cleanData, IMAGE_HEIGHT * IMAGE_WIDTH * sizeof(uint16_t)); flirDataFrame_.minVal = minVal; flirDataFrame_.maxVal = maxVal; mtxLock_.unlock(); } catch (boost::thread_interrupted&) {return;} end = boost::posix_time::microsec_clock::local_time(); calcVoSPIfps(begin, end); } } float FlirLeptonHWIface::calcVoSPIfps( boost::posix_time::ptime& start, boost::posix_time::ptime& stop) { boost::posix_time::time_duration elapsedDur = stop - start; vospiFps_ = (vospiFps_ + static_cast<float>( 1000.0 / elapsedDur.total_milliseconds())) / 2; return vospiFps_; } /*! * @brief Process the last obtained from flir lepton VoSPI frame. * * @return Void. */ void FlirLeptonHWIface::processFrame(void) { uint8_t imageVal; uint16_t temp; float temperVal; float temperSum = 0; uint16_t minVal, maxVal; uint8_t red = 0, green = 0, blue = 0; /* -------------------------------------------------------------------- */ mtxLock_.lock(); memcpy(lastFrame_, flirDataFrame_.frameData, IMAGE_HEIGHT * IMAGE_WIDTH * sizeof(uint16_t)); minVal = flirDataFrame_.minVal; maxVal = flirDataFrame_.maxVal; mtxLock_.unlock(); /* -------------------------------------------------------------------- */ // Clear previous acquired frame temperature values temperMsg_.values.data.clear(); grayImage_.data.clear(); if(pubRgb_) {rgbImage_.data.clear();} for (int i = 0; i < IMAGE_WIDTH; i++) { for (int j = 0; j < IMAGE_HEIGHT; j++) { // Thermal image creation imageVal = Utils::signalToImageValue( lastFrame_[i * IMAGE_HEIGHT + j], minVal, maxVal); grayImage_.data.push_back(imageVal); if(pubRgb_) { Utils::toColormap(imageVal, red, green, blue); rgbImage_.data.push_back(red); rgbImage_.data.push_back(green); rgbImage_.data.push_back(blue); } // Scene frame Temperatures vector creation. temperVal = Utils::signalToTemperature( lastFrame_[i * IMAGE_HEIGHT + j], calibMap_); temperMsg_.values.data.push_back(temperVal); temperSum += temperVal; } } grayImage_.header.stamp = now_; rgbImage_.header.stamp = now_; temperMsg_.header.stamp = now_; frameAvgTemper_ = temperSum / (IMAGE_HEIGHT * IMAGE_WIDTH); } /*! * @brief Fills batch topic msg. * * @return Void. */ void FlirLeptonHWIface::fillBatchMsg(void) { batchMsg_.header.stamp = now_; batchMsg_.temperatures = temperMsg_; batchMsg_.thermalImage = grayImage_; } void FlirLeptonHWIface::openDevice(void) { int statusVal; flirSpi_.handler = open(flirSpi_.devicePort.c_str(), O_RDWR); if (flirSpi_.handler < 0) { ROS_FATAL("[Flir-Lepton]: Can't open SPI device port --> %s", flirSpi_.devicePort.c_str()); exit(1); } statusVal = ioctl(flirSpi_.handler, SPI_IOC_WR_MODE, &flirSpi_.mode); if (statusVal < 0) { ROS_FATAL("[Flir-Lepton]: Can't set SPI-mode (WR)...ioctl failed"); exit(1); } statusVal = ioctl(flirSpi_.handler, SPI_IOC_RD_MODE, &flirSpi_.mode); if (statusVal < 0) { ROS_FATAL("[Flir-Lepton]: Can't set SPI-mode (RD)...ioctl failed"); exit(1); } statusVal = ioctl(flirSpi_.handler, SPI_IOC_WR_BITS_PER_WORD, &flirSpi_.bits); if (statusVal < 0) { ROS_FATAL("[Flir-Lepton]: Can't set SPI bitsperWord (WD)...ioctl failed"); exit(1); } statusVal = ioctl(flirSpi_.handler, SPI_IOC_RD_BITS_PER_WORD, &flirSpi_.bits); if (statusVal < 0) { ROS_FATAL("[Flir-Lepton]: Can't set SPI bitsperWord (RD)...ioctl failed"); exit(1); } statusVal = ioctl(flirSpi_.handler, SPI_IOC_WR_MAX_SPEED_HZ, &flirSpi_.speed); if (statusVal < 0) { ROS_FATAL("[Flir-Lepton]: Can't set SPI speed (WD)...ioctl failed"); exit(1); } statusVal = ioctl(flirSpi_.handler, SPI_IOC_RD_MAX_SPEED_HZ, &flirSpi_.speed); if (statusVal < 0) { ROS_FATAL("[Flir-Lepton]: Can't set SPI speed (RD)...ioctl failed"); exit(1); } ROS_INFO("[Flir-Lepton]: Device SPI Port open."); //ROS_INFO("[SPI Device information]:"); //std::cout << " * Device Port: " << flirSpi_.devicePort << std::endl; } void FlirLeptonHWIface::closeDevice(void) { int statusVal; statusVal = close(flirSpi_.handler); if (statusVal < 0) { ROS_FATAL("[Flir-Lepton]: Error while trying to close SPI device port"); exit(1); } ROS_INFO("[Flir-Lepton]: Closing device SPI Port"); } } // namespace flir_lepton_sensor } // namespace flir_lepton_rpi2
33.509356
86
0.585122
angetria
bd59e41984d0a6dcac40ad7e6ba9f4efe616a2b2
878
hpp
C++
src/gui/sprites/simple_world_sprite.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
7
2015-01-28T09:17:08.000Z
2020-04-21T13:51:16.000Z
src/gui/sprites/simple_world_sprite.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
null
null
null
src/gui/sprites/simple_world_sprite.hpp
louiz/batajelo
4d8edce8da9d3b17dbad68eb4881d7f6fee2f76e
[ "BSL-1.0", "BSD-2-Clause", "Zlib", "MIT" ]
1
2020-07-11T09:20:25.000Z
2020-07-11T09:20:25.000Z
#ifndef SIMPLE_WORLD_SPRITE_HPP_INCLUDED #define SIMPLE_WORLD_SPRITE_HPP_INCLUDED #include <gui/sprites/world_sprite.hpp> class SimpleWorldSprite: public WorldSprite { public: SimpleWorldSprite(const Position& position, const sf::Sprite& sprite): position(position), sprite(sprite) {} ~SimpleWorldSprite() = default; Position get_world_pos() const { return this->position; } void draw(sf::RenderTarget& surface, const sf::RenderStates& states) const { surface.draw(this->sprite, states); } private: const Position position; const sf::Sprite& sprite; SimpleWorldSprite(const SimpleWorldSprite&) = delete; SimpleWorldSprite(SimpleWorldSprite&&) = delete; SimpleWorldSprite& operator=(const SimpleWorldSprite&) = delete; SimpleWorldSprite& operator=(SimpleWorldSprite&&) = delete; }; #endif /* SIMPLE_WORLD_SPRITE_HPP_INCLUDED */
25.823529
76
0.753986
louiz
bd5f5932011fc7c727ea9ee43bb978feb3799a6c
1,215
cc
C++
tools/type_whisperer/api_type_db.cc
Yannic/envoy
3156229006a5340b65c773329070737f67e81826
[ "Apache-2.0" ]
null
null
null
tools/type_whisperer/api_type_db.cc
Yannic/envoy
3156229006a5340b65c773329070737f67e81826
[ "Apache-2.0" ]
null
null
null
tools/type_whisperer/api_type_db.cc
Yannic/envoy
3156229006a5340b65c773329070737f67e81826
[ "Apache-2.0" ]
null
null
null
#include "tools/type_whisperer/api_type_db.h" #include "common/protobuf/protobuf.h" #include "tools/type_whisperer/api_type_db.pb.h" namespace Envoy { namespace Tools { namespace TypeWhisperer { extern const char* ApiTypeDbPbText; namespace { tools::type_whisperer::TypeDb* loadApiTypeDb() { tools::type_whisperer::TypeDb* api_type_db = new tools::type_whisperer::TypeDb; if (Protobuf::TextFormat::ParseFromString(ApiTypeDbPbText, api_type_db)) { return api_type_db; } return nullptr; } const tools::type_whisperer::TypeDb& getApiTypeDb() { static tools::type_whisperer::TypeDb* api_type_db = loadApiTypeDb(); return *api_type_db; } } // namespace absl::optional<TypeInformation> ApiTypeDb::getLatestTypeInformation(const std::string& type_name) { absl::optional<TypeInformation> result; std::string current_type_name = type_name; while (true) { auto it = getApiTypeDb().types().find(current_type_name); if (it == getApiTypeDb().types().end()) { return result; } result.emplace(current_type_name, it->second.proto_path()); current_type_name = it->second.next_version_type_name(); } } } // namespace TypeWhisperer } // namespace Tools } // namespace Envoy
26.413043
99
0.739095
Yannic
bd6105d0de0f2fc8b97c96312456888daa4a4a46
171,483
cxx
C++
osprey/be/cg/orc_intel/if_conv.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/orc_intel/if_conv.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
osprey/be/cg/orc_intel/if_conv.cxx
sharugupta/OpenUH
daddd76858a53035f5d713f648d13373c22506e8
[ "BSD-2-Clause" ]
null
null
null
/* Copyright (C) 2000-2003, Intel Corporation All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of the owner 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 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. */ //-*-c++-*- //***************************************************************************** // // Module: if_conv.cxx // $Date: 2005/10/21 19:00:00 $ // $Author: marcel $ // $Source: /proj/osprey/CVS/open64/osprey1.0/be/cg/orc_intel/if_conv.cxx,v $ // // // // Description: Implementation of Ipfec if-conversion. // See if-conv.h for the description. // //***************************************************************************** #include <vector> #include <set> #include <stdlib.h> #include <stdio.h> #include "bb.h" #include "defs.h" #include "mempool.h" #include "error.h" #include "bb_set.h" #include "region.h" #include "cgtarget.h" #include "if_conv.h" #include "timing.h" #include "tracing.h" #include "cg.h" #include "profile_util.h" #include "region_bb_util.h" #include "ti_res_count.h" #include "ti_latency.h" #include "ipfec_defs.h" #include "cg_dep_graph.h" #include "dominate.h" #include "vt_region.h" #include "recovery.h" #include <math.h> #include "whirl2ops.h" #include "tlog.h" #include "glob.h" #include "ipfec_options.h" #include "be_util.h" #include "freq.h" #include "op.h" #define MAX_NUM_PARA_CMP 2 #define COMP_TOP_NUM 32 #define PARA_COMP_TYPE_NUM 6 void fPrint_TN ( FILE *f, char *fmt, TN *tn); BOOL CGTARG_Unconditional_Compare(OP *, TOP *); void BB_SET_Calculate_Dominators(BB_SET *, BOOL, BOOL); void Calculate_Dominators(void); void Free_Dominators_Memory(void); void Exp_True_False_Preds_For_Block(BB *, TN *&, TN *&); void Exp_Pred_Set(TN *dest, TN *cdest, INT val, OPS *ops); void Exp_Generic_Pred_Calc(TN*,TN *, COMPARE_TYPE, TN *, OPS*); void draw_classic_BB_dependence_graph(BB *bb); void Predicate_Block(BB* bb, TN *pred_tn, BB_SET*); void Print_BB (BB *); void Print_OPS(ops const *); void Print_OP_No_SrcLine(const OP *op); void GRA_LIVE_Compute_Liveness_For_BB(BB *bb); BOOL FREQ_Match(float f1, float f2); BOOL Is_In_Abnormal_Loop(REGION* r); COMPARE_TYPE Compare_Type(TOP opcode); hTN_MAPf frequency_of_predicates = 0; TN_INFO_MEM info_mem; hTN_MAP init_op_info = 0; BOOL Is_Para_Comp_May_Def(OP *op) { COMPARE_TYPE comp_type = Compare_Type(OP_code(op)); return ((comp_type != COMPARE_TYPE_unc) && (comp_type != COMPARE_TYPE_normal) && (comp_type != (COMPARE_TYPE)-1)); } BOOL Is_In_Infinite_Loop(REGION* region) { REGION* reg = region; while (reg) { if ( reg -> Region_Type() == LOOP && reg ->Exits().empty()) return TRUE; reg = reg -> Parent(); } return FALSE; } //***************************************************************************** // Function: Is_Abnormal_Loop // Input : region // Output : // a boolean value which indicates if the region is an abnormal loop. // Here, an abnormal loop is a loop like : // 1 <------| // / \ | // / \ | // 2 3 | // / \ / | // / \ / | // exit 4 --------| // in such a loop, 1 dom 2 and 2 pdom 1, as a result, 1 and 2 are put into // one control-equivalent-class. So some wrong results are caused in // if-conversion and predicate analysis. // Description : // the conditions in which we judge if a region is an abnormal loop is : // 1) region is a loop region; // 2) the source of the back-edge is not an exit -node of the loop; // 3) the exit is not the entry of the loop //***************************************************************************** BOOL Is_Abnormal_Loop(REGION* region) { if ( region -> Region_Type() != LOOP) return FALSE; // find out the source node of back-edge REGIONAL_CFG_NODE* loop_tail = NULL; for (TOPOLOGICAL_REGIONAL_CFG_ITER iter( region -> Regional_Cfg()); iter!=0; ++iter) { REGIONAL_CFG_NODE *node = *iter; if ( node -> Succ_Num() == 0) { if(loop_tail || (node -> Is_Region() && node->Region_Node()->Exits().size() >1 ) ) return TRUE; loop_tail = node; } } NODE_VECTOR exits = region -> Exits(); for (NODE_VECTOR_ITER iter1 = exits.begin(); iter1 != exits.end(); iter1++) { if ((*iter1) == loop_tail) { return FALSE; } } if ( region -> Entries().size() != 1) { DevWarn("MEME region is illegal in Is_Abnormal_Loop!\n"); return FALSE; } if ( region -> Exits().size() == 1) { REGIONAL_CFG_NODE* entry = *(region -> Entries().begin()); REGIONAL_CFG_NODE* exit = *(region -> Exits().begin()); if (!entry->Is_Region() && entry == exit) return FALSE; } return TRUE; } /* ==================================================================== * * TN_Defined_At_Op * * This functions lookes for the definition of a given TN for * a given OP. * * If the definition is conditional and garded by the same * predicate as the given OP, then the pointer to this OP is returned. * If this is not the case, then the pointer to this function is put * into the OP list(ops) and it continues the search until it finds a * definition which is not conditional or the predicates are the * same. * i.e The given values are tn=TN1, op=OP3, ops=<some valid pointer> * TN1 TN2 OP1 * TN1 TN2 OP2 (TN3) cond. * OP3 (TN1) cond. * * The function would in this case return the pointer to OP1, because * this is the first OP which definitely defines TN1. In the OP list * would be the pointers to OP2 and OP1. * * ==================================================================== */ OP * TN_Defined_At_Op (TN *tn, OP *op, std::vector<OP *> *ops) { OP *value_op; if (ops==NULL) { FmtAssert(0, ("Parameter ops is NULL pointer!")); } if (TN_register(tn) != REGISTER_UNDEFINED) { return NULL; } for (value_op=OP_prev(op); value_op!=NULL; value_op=OP_prev(value_op)) { if (OP_Defs_TN(value_op, tn)) { ops->push_back(value_op); if (Is_OP_Cond(value_op)) { if (OP_has_predicate(value_op) && OP_has_predicate(op)) { TN *p1 = OP_opnd((OP*) value_op, OP_PREDICATE_OPND); TN *p2 = OP_opnd((OP*) op, OP_PREDICATE_OPND); if (p1 == p2) { return value_op; } } } else { return value_op; } } } return NULL; } //***************************************************************************** // Function : Find_BB_Predicates // Input : // - bb : the bb contains branch and compare // - first_pred: the first target of compare // - second_pred: the second target of compare // Output : // < none > // Description : // if a bb has a conditional branch, and the guarding predicate of the // branch is defined by a compare instructin , the function is to find out // the first and the second predicate register of the compare instruction. //***************************************************************************** void Find_BB_Predicates(BB* bb, TN*& first_pred,TN*& second_pred) { vector<OP *>::iterator op; vector<OP *> ops; OP *br = BB_branch_op(bb); first_pred = NULL; second_pred = NULL; TN *pred_1; TN *pred_2; if (BB_succs_len(bb) != 2 || !br) { return; } pred_1 = OP_opnd(br, OP_PREDICATE_OPND); Is_True(pred_1, ("conditional branch has no guarded predicate!\n")); OP *compare_op = TN_Defined_At_Op(pred_1, br, &ops); if(!compare_op) { return; } Is_True(compare_op, (" the predicate of br has reaching definition!\n")); Is_True(OP_results(compare_op), (" compare_op must has result.\n")); first_pred = OP_result(compare_op,0); if (OP_results(compare_op) > 1) { second_pred = OP_result(compare_op,1); } // If we have more then one OP which defines the branch predicate, // we have to check if all predicate pairs are the same. // i.e // TN1 TN2 op1 // TN2 TN1 op2 BOOL create_neg_of_br_pred = FALSE; if (ops.size() < 2) { return; } for (op = ops.begin(); op != ops.end(); op++) { if (OP_results(*op) > 1) { if ( !( (first_pred == OP_result(*op,0)) && (second_pred == OP_result(*op,1)) ) && !( (first_pred == OP_result(*op,1)) && (second_pred == OP_result(*op,0)) ) ) { // predicate pair is different // we have to create and insert a predicate which is a // negation of our branch predicate create_neg_of_br_pred = TRUE; break; } } else { // only one predicate // we have to create and insert a predicate which is a // negation of our branch predicate create_neg_of_br_pred = TRUE; break; } } if (create_neg_of_br_pred) { OP *neg_op; // Lets check if we already have insert the negation op in a previous // function call of Find_BB_Predictae() neg_op = OP_prev(br); if ( (OP_code(neg_op)==TOP_cmp_ne_unc) && (OP_Refs_TN(neg_op, pred_1)) && (OP_Refs_TN(neg_op, Zero_TN)) && (OP_Defs_TN(neg_op, True_TN)) ) { pred_2 = OP_result(neg_op, 1); } else { pred_2 = Gen_Predicate_TN(); neg_op = Mk_OP(TOP_cmp_ne_unc, True_TN, pred_2, True_TN, pred_1, Zero_TN); OP_srcpos(neg_op) = OP_srcpos(br); BB_Insert_Op(bb, br, neg_op, TRUE); } first_pred = pred_1; second_pred = pred_2; } return; } //============================================================================= // Part 1: implementation of the classes defined in this phase //============================================================================= //***************************************************************************** // implementation for class IF_CONV_AREA //***************************************************************************** IF_CONV_AREA::IF_CONV_AREA(BB *bb, IF_CONVERTOR *convertor): _included_blocks(BB_CONTAINER(&(convertor -> _m))), _predecessors(IF_CONV_ALLOC(&(convertor -> _m))), _successors(IF_CONV_ALLOC(&(convertor -> _m))) { _head = bb; // add the present bb in _included_blocks _included_blocks.push_back(bb); // if the present basic block is not suitable for if-conversion, // we set the mark // if it is suitable, we compute the length of its critical path AREA_TYPE type = convertor -> Suitable_For_If_Conv(bb); _if_suitable = type; _need_if_convert = NO_IF_CONV; if (type != UNSUITABLE) { _cycled_critical_length = convertor -> Compute_Critical_Path_Len(bb, true); _critical_length = convertor -> Compute_Critical_Path_Len(bb,false); } else { _cycled_critical_length = 0; _critical_length = 0; } _control_deps = 0; _pred_assign_info = 0; } void IF_CONV_AREA::Combine_Blocks_With(IF_CONV_AREA *area, MEM_POOL *mem_pool) { BB_CONTAINER& set = area -> Blocks(); BB_CONTAINER::iterator iter; for (iter = set.begin(); iter != set.end(); iter++) { _included_blocks.push_back(*iter); } } void IF_CONV_AREA::Init_Conversion_Info(MEM_POOL *mem_pool) { _control_deps = CXX_NEW( CNTL_DEP(_head, _included_blocks, mem_pool), mem_pool); _pred_assign_info = BB_MAP_Create(); BB_CONTAINER::iterator iter; for (iter = _included_blocks.begin(); iter != _included_blocks.end(); iter++) { BB_PREDICATE_INFO* info = CXX_NEW(BB_PREDICATE_INFO(mem_pool), mem_pool); BB_MAP_Set(_pred_assign_info, *iter, info); } } void IF_CONV_AREA::Remove_BB(BB* bb) { BB_CONTAINER::iterator iter; for (iter = _included_blocks.begin(); iter != _included_blocks.end(); iter++) { if ( *iter == bb) { _included_blocks.erase(iter); return; } } } EXIT_TARGET_INFO* IF_CONV_AREA::Exit_Target(BB* bb) { EXIT_CONTAINER::iterator iter; for (iter = _exit_targets.begin(); iter != _exit_targets.end(); iter++) { if ( (*iter) -> Target() == bb) { return *iter; } } return NULL; } void IF_CONV_AREA::Add_Exit_Target(BB* target, TN* predicate, MEM_POOL* mem_pool) { EXIT_TARGET_INFO* info = CXX_NEW(EXIT_TARGET_INFO(target, mem_pool), mem_pool); info -> Add_Main_Predicate(predicate); _exit_targets.push_back(info); } BOOL EXIT_TARGET_INFO::Is_Main_Predicate(TN* tn) { TN_CONTAINER::iterator iter; for (iter = _main_predicates.begin(); iter != _main_predicates.end(); iter++) { if ( *iter == tn) return true; } return false; } void EXIT_TARGET_INFO::Assign_Aux_Predicates(BB* bb, OP *br) { OPS ops = OPS_EMPTY; if ( _aux_predicates.size() == 0 || _main_predicates.size() ==0 ) return; Is_True(_main_predicates.size() == 1, ("Wrong number of main predicates!\n")); TN *main_tn = *(_main_predicates.begin()); TN_CONTAINER::iterator iter; for (iter = _aux_predicates.begin(); iter != _aux_predicates.end(); iter++) { Is_True(*iter, ("NULL predicate.\n")); Build_OP(TOP_cmp_eq, main_tn, True_TN, *iter,Zero_TN, Zero_TN, &ops); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { Print_OPS(&ops); } OP* new_op; FOR_ALL_OPS_OPs_FWD((&ops),new_op){ Set_OP_cond_def_kind(new_op, OP_ALWAYS_COND_DEF); } BB_Insert_Ops_Before (bb, br, &ops); } void EXIT_TARGET_INFO::Del_Main_Predicate(TN* tn){ TN_CONTAINER::iterator iter; for (iter = _main_predicates.begin(); iter != _main_predicates.end(); iter++) { Is_True(*iter, ("NULL predicate.\n")); if (*iter == tn) { _main_predicates.erase(iter); break; } } } void EXIT_TARGET_INFO::Update_Predicate(TN *old_tn, TN* new_tn) { if (old_tn == new_tn) return; TN_CONTAINER::iterator iter; for (iter = _main_predicates.begin(); iter != _main_predicates.end(); iter++) { Is_True(*iter, ("NULL predicate.\n")); if (*iter == old_tn) { _main_predicates.erase(iter); _main_predicates.push_back(new_tn); break; } } for (iter = _aux_predicates.begin(); iter != _aux_predicates.end(); iter++) { Is_True(*iter, ("NULL predicate.\n")); if (*iter == old_tn) { _aux_predicates.erase(iter); _aux_predicates.push_back(new_tn); break; } } return; } //***************************************************************************** // implementation for class CNTL_DEP //***************************************************************************** //***************************************************************************** // Function : CNTL::CNTL_DEP // Input : // - entry : the entry basic block of all BBs in set // - set : a set of basic blocks. To use CNTL_DEP, the set must be: // 1) all BBs in it are connected; // 2) all BBs in it have a unique entry // 3) there is no multiple-successor-bb in it // 4) there is no such a case: a region is a predecessor of one bb // in the set and, in the same time, it is a successor of another // bb in the set // Output : // the control dependent tree of the input bb_set // Description : // it computes the control dependent information of a bb_set // //***************************************************************************** CNTL_DEP::CNTL_DEP(BB *entry, BB_CONTAINER& bbs, MEM_POOL *mem_pool) { _entry = entry; _bb_set = BB_SET_Create_Empty(PU_BB_Count, mem_pool); BB_CONTAINER::iterator bb_iter; BB *bb; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; _bb_set = BB_SET_Union1D(_bb_set, bb, mem_pool); } // Initialize control dependencies bit sets _control_dependences = BB_MAP_Create(); _true_edges = BB_MAP_Create(); FOR_ALL_BB_SET_members(_bb_set, bb) { BB_SET *deps = BB_SET_Create_Empty(PU_BB_Count, mem_pool); BB_SET *trues = BB_SET_Create_Empty(PU_BB_Count, mem_pool); BB_MAP_Set(_control_dependences, bb, deps); BB_MAP_Set(_true_edges, bb, trues); } // Find out the control dependences. Also, in this algorithms it's // easy to set the true edges at the same time. BBLIST *bl; BB_SET *bb_to_add = BB_SET_Create_Empty(PU_BB_Count+2, mem_pool); FOR_ALL_BB_SET_members(_bb_set, bb) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " Computing BB%d:\n", BB_id(bb)); } BB *fall_thru = BB_Fall_Thru_Successor(bb); TN *second_pred = NULL; TN *first_pred = NULL; OP *br = NULL; if ( BB_succs_len(bb) == 2) { br = BB_branch_op(bb); Find_BB_Predicates(bb, first_pred, second_pred); } FOR_ALL_BB_SUCCS(bb, bl) { BB *bb_dep; BB *bb_succ = BBLIST_item(bl); BOOL true_edge = FALSE; if ( br ) { true_edge = (( first_pred == OP_opnd(br, OP_PREDICATE_OPND) && bb_succ != fall_thru) || ( second_pred == OP_opnd(br, OP_PREDICATE_OPND) && bb_succ == fall_thru)); } // // bb_to_add is set to (pdom(bb_succ) - pdom(bb)) & _bb_set. // In other words, it is used to record what is in the bb_set // post-dominates bb_succ (which will include bb_succ) and // is not a post-dominator of bb. These are exactly the BB's which // are control-dependent on bb. If the successor is not in the // bb_set, we are safe to assume that nothing else in the bb_set // post-dominates it, so we can ignore it. Also, if the successor // is the bb_set entry, we have a loop and hence we must not // consider this arc when computing the control dependence. // if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " ===== succ BB%d:", BB_id(bb_succ)); } if (BB_SET_MemberP(_bb_set, bb_succ) && (bb_succ != entry)) { BB_SET_CopyD(bb_to_add, BB_pdom_set(bb_succ), mem_pool); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { BB* bb_tmp; fprintf(TFile, " ** pdoms:"); FOR_ALL_BB_SET_members(bb_to_add, bb_tmp) { fprintf(TFile, " BB%d, ", BB_id(bb_tmp)); } fprintf(TFile, "\n"); } bb_to_add = BB_SET_DifferenceD(bb_to_add, BB_pdom_set(bb)); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { BB* bb_tmp; fprintf(TFile, " ** after -pdoms(bb):"); FOR_ALL_BB_SET_members(bb_to_add, bb_tmp) { fprintf(TFile, " BB%d, ", BB_id(bb_tmp)); } fprintf(TFile, "\n"); } bb_to_add = BB_SET_IntersectionD(bb_to_add, _bb_set); FOR_ALL_BB_SET_members(bb_to_add, bb_dep) { BB_SET *deps, *trues, *new_deps, *new_trues; deps = (BB_SET*)BB_MAP_Get(_control_dependences, bb_dep); Is_True(deps != NULL, ("Can't find cntl deps for BB%d.\n", BB_id(bb_dep))); trues = (BB_SET*)BB_MAP_Get(_true_edges, bb_dep); Is_True(trues != NULL, ("Can't find true edges for BB%d.\n", BB_id(bb_dep))); new_deps = BB_SET_Union1D(deps, bb, mem_pool); if ( deps != new_deps) { BB_MAP_Set(_control_dependences, bb_dep, new_deps); } if (true_edge) { new_trues = BB_SET_Union1D(trues, bb, mem_pool); if ( trues != new_trues ) { BB_MAP_Set( _true_edges, bb_dep, mem_pool); } } } } } } } BOOL CNTL_DEP::Is_Cntl_Dep(BB *bb1, BB *bb2) { BB *bb; if (bb1 == bb2) return true; BB_SET *set = Cntl_Dep_Parents(bb2); Is_True(set != NULL, (" Can not find control dependent parents for BB%d", BB_id(bb2))); FOR_ALL_BB_SET_members(set, bb) { if (Is_Cntl_Dep(bb1, bb)) return true; } return false; } void CNTL_DEP::Cntl_Dep_Children(BB_SET*& result, BB *bb, MEM_POOL *mem_pool) { BB *block; FOR_ALL_BB_SET_members(_bb_set, block) { BB_SET *cds = (BB_SET*)BB_MAP_Get(_control_dependences, block); Is_True(cds != NULL, (" Can not find control dependent parents for BB%d", BB_id(block))); if (BB_SET_MemberP(cds, bb)) { result = BB_SET_Union1D( result, block, mem_pool); } } } void CNTL_DEP::_Post_Order_Helper(BB_CONTAINER& result, BB *bb, IF_CONVERTOR* convertor) { BB *child; BB_SET *child_set; if (convertor -> Is_BB_Container_Member(result, bb)) return; child_set = BB_SET_Create_Empty(PU_BB_Count, &(convertor -> _m)); Cntl_Dep_Children(child_set, bb, &(convertor -> _m)); FOR_ALL_BB_SET_members(child_set, child) { _Post_Order_Helper(result, child, convertor); } result.push_back(bb); } void CNTL_DEP::Get_Post_Order(BB_CONTAINER& result, IF_CONVERTOR* convertor) { BB *block; FOR_ALL_BB_SET_members(_bb_set, block) { _Post_Order_Helper(result, block, convertor); } } //============================================================================= // Part2: some tool functions for IF_CONVERTOR //============================================================================= //***************************************************************************** // Function : Suitable_For_If_Conv // Input : // - bb : a basic block // Output : // it indicate if it is legal to if_convert the bb // Description : // Determine if the block has some characteristics that make it // undesirable or even illegal to be if-converted. // //***************************************************************************** AREA_TYPE IF_CONVERTOR::Suitable_For_If_Conv(BB *bb) { // except the basic block consisting of vargoto if (BB_kind(bb) == BBKIND_VARGOTO || BB_kind(bb) == BBKIND_INDGOTO) { return UNSUITABLE; } if (BB_call(bb)) return UNSUITABLE; // The bb with exception label can not be if-converted if (BB_Has_Exc_Label(bb)) { return UNSUITABLE; } // Blocks which have labels marked as address-taken cannot be if-converted. if (BB_Has_Addr_Taken_Label(bb)) { return UNSUITABLE; } AREA_TYPE ty = SUITABLE_FOR_IF_CONV; OP* op; FOR_ALL_BB_OPs_FWD(bb, op) { // if an op doesn't have qualifying predicate operands, it may be // unsafe to employ predication. Exclude OP_xfer OPs as they // will be eliminated as a by-product of doing if-conversion, so need // to check for those OPs. if (!OP_has_predicate(op) && !OP_xfer(op)) { ty = (AREA_TYPE)((INT)ty & UPWARD_UNSUITABLE); } // For now, we do not plan to deal with blocks containing predicated // instructions created by previous phases. if (OP_has_predicate(op) && !TN_is_true_pred(OP_opnd(op, OP_PREDICATE_OPND))) { TN *pred_tn = OP_opnd(op, OP_PREDICATE_OPND); if (TN_is_global_reg(pred_tn)) { return UNSUITABLE; } vector<OP *> ops; OP *def_op = TN_Defined_At_Op(pred_tn, op, &ops); // If it's not defined in the block, we will give up. if (!def_op) { DevWarn("Predicated instruction with no reaching def in BB%d " "in Suitable_For_If_Conv.", BB_id(bb)); return UNSUITABLE; } // If its reaching defination is not in the bb, we will // give up because it is very complicated. if (OP_bb(def_op)!= bb) { DevWarn("An up-exposed predicate use stops if-converter BB%d " "in Suitable_For_If_Conv.",BB_id(bb)); return UNSUITABLE; } } // the following part is to protect the following case from being // if-converted: // p1, p2 = cmp a, b // (p2) br // / | // / | // p1, p2 = cmp a, b | // \ | // \ | // (p2) br // / \ // / \ // note: the 'cmp' is normal-type (non-unconditional) // for the case, // before if-convertion, if the condition of compare is false, // both the two branches will all be taken; after if-convertion, it is // changed to : // p1, p2 = cmp a, b // (p1) p1, p2 = cmp.unc a, b // (p2) br // note: the second cmp is changed to unconditional type. As a result, // if the condition is false, the brance will not be taken. // So, here, we skip the case. COMPARE_TYPE ty = Compare_Type(OP_code(op)); if ( ty != (COMPARE_TYPE)-1) { // compare type Is_True(OP_results(op) <=2, ("too many results!\n")); TN *pred_tn = OP_result(op, 0); if (Is_Partial_Redundant_Def(bb, op, pred_tn)) { return UNSUITABLE; } pred_tn = OP_result(op, 1); if (Is_Partial_Redundant_Def(bb, op, pred_tn)) { return UNSUITABLE; } } } return ty; } BOOL IF_CONVERTOR::Is_Partial_Redundant_Def(BB* bb, OP* op, TN* tn) { // check all bb's ancestor in the region to see // if tn is defined previously. OP *def_op = NULL; OP *def_bb = NULL; vector<OP *> ops; def_op = TN_Defined_At_Op(tn, op, &ops); if (def_op) { BB *def_bb = OP_bb(def_op); if ( def_bb != bb && !BB_SET_MemberP(BB_pdom_set(def_bb), bb)) { return TRUE; } } else { BB_SET* bb_queue = BB_SET_Create_Empty(PU_BB_Count, &_m); bb_queue = BB_SET_Union1D(bb_queue, bb, &_m); BB_SET* bb_processed = BB_SET_Create_Empty(PU_BB_Count, &_m); while ( BB_SET_Size(bb_queue) ) { BB* bb1 = BB_SET_Choose(bb_queue); BS_Difference1D(bb_queue, BB_id(bb1)); BB_SET_Union1D(bb_processed, bb1, &_m); REGIONAL_CFG_NODE* node = Regional_Cfg_Node(bb1); for (CFG_PRED_NODE_ITER pred_iter(node); pred_iter!=0; ++pred_iter) { REGIONAL_CFG_NODE *pred = *pred_iter; if (pred -> Is_Region()) continue; BB* pred_bb = pred -> BB_Node(); if ( GTN_SET_MemberP(BB_live_in(pred_bb),tn) && !BB_SET_MemberP(BB_pdom_set(pred_bb), bb)) { return TRUE; } else if (!BB_SET_MemberP(bb_processed, pred_bb)){ bb_queue = BB_SET_Union1D(bb_queue, pred_bb, &_m); } } } } return FALSE; } //***************************************************************************** // Function : Compute_Min_Cycle // Input : // - set : a set of basic blocks // Output : // a number to indicate the mininal executive time of the input bb // Description : // To compute the mininal execution cycle of the input BB_SET by only // considering the resource usage. //***************************************************************************** void IF_CONVERTOR::Compute_Min_Cycle(INT32& base, BB_CONTAINER& set) { TI_RES_COUNT *counter = TI_RES_COUNT_Alloc(&_m); BB_CONTAINER::iterator iter; for (iter = set.begin(); iter != set.end(); iter++) { OP *op; FOR_ALL_BB_OPs_FWD(*iter, op) { TI_RES_COUNT_Add_Op_Resources(counter, OP_code(op)); } } base += (INT32)ceil(TI_RES_COUNT_Min_Cycles(counter)); } //***************************************************************************** // Function : Prob_Of_Area // Description : // To find out the probablity of two IF_CONV_AREAs according to the // probablity of BBs. //***************************************************************************** float IF_CONVERTOR::Prob_Of_Area(IF_CONV_AREA *area1, IF_CONV_AREA *area2) { float freq = 0.0; BB *head = area2 -> Entry_BB(); BB *bb; BBLIST *bl; FOR_ALL_BB_PREDS(head, bl) { BB *bb_pred = BBLIST_item(bl); BB_CONTAINER& bbs = area1 -> Blocks(); if (Is_BB_Container_Member(bbs, bb_pred)) { freq += Prob_Local(bb_pred, head) * BB_freq(bb_pred); } } float result = BB_freq(area1 -> Entry_BB()) ? freq / BB_freq(area1 -> Entry_BB()):0; return result <1.0 ||FREQ_Match(result, 1.0) ? result: 1.0; } //***************************************************************************** // Function : Compute_Critical_Path_Len // Input : // - bb : a basic block for which the function will figure out the length // of its critical path // - cycled : it indicates if we need consider the latency of ops. if it // is false, we will look all ops as one-cycle-latency ops. // Output : // an INT value indicating the length of the critical path of the input // Description : // To compute the length of the critical path of the given basic block //***************************************************************************** INT32 IF_CONVERTOR::Compute_Critical_Path_Len(BB *bb, BOOL cycled) { // to record the earliest start time of all ops BB_OP_MAP earliest_time_table = BB_OP_MAP32_Create(bb, &_m); INT32 critical_path_cycle = 0; // build dag for current bb if (CG_DEP_Has_Graph(bb)) { CG_DEP_Delete_Graph(bb); } CG_DEP_Compute_Graph ( bb, INCLUDE_ASSIGNED_REG_DEPS, NON_CYCLIC, NO_MEMREAD_ARCS, INCLUDE_MEMIN_ARCS, INCLUDE_CONTROL_ARCS, NULL); // search all ops of the bb and compute the earliest-start-time for them OP *op; FOR_ALL_BB_OPs_FWD(bb,op) { if ( OP_xfer(op)) break; INT32 earliest_start_time = 0; INT32 latency; // the predecessors of an op are the ops, from which there are // dependence edges pointing to the op;after the following loop, // we can compute the earliest-start-time of an op; for (ARC_LIST* arcs = OP_preds(op); arcs != NULL; arcs = ARC_LIST_rest(arcs)) { ARC* arc = ARC_LIST_first(arcs); OP* pred = ARC_pred(arc); if (OP_bb(pred) != bb) continue; INT32 start_time; start_time = BB_OP_MAP32_Get(earliest_time_table, pred); latency = cycled ? ARC_latency(arc):1; start_time += latency; if ( start_time > earliest_start_time) earliest_start_time = start_time; } // in the following, we update the length of the longest path // - critical_path_cycle BB_OP_MAP32_Set(earliest_time_table, op, earliest_start_time); latency = cycled ? TI_LATENCY_Result_Available_Cycle(OP_code(op),0):1; INT32 path_time = earliest_start_time + latency; if (critical_path_cycle < path_time) { critical_path_cycle = path_time; } } CG_DEP_Delete_Graph(bb); return critical_path_cycle; } //***************************************************************************** // Function : Find_Area // Description : // Find out the position of an given IF_CONV_AREA from an AREA_CONTAINER //***************************************************************************** AREA_CONTAINER::iterator IF_CONVERTOR::Find_Area(AREA_CONTAINER& areas, IF_CONV_AREA* area) { AREA_CONTAINER::iterator iter; for (iter = areas.begin(); iter!= areas.end(); iter++) { if ( area == *iter) { return iter; } } return iter; } inline void IF_CONVERTOR::Add_Edge(IF_CONV_AREA *area1, IF_CONV_AREA *area2) { area1 -> Add_Succ(area2, this); area2 -> Add_Pred(area1, this); } BOOL IF_CONVERTOR::Is_BB_Container_Member(BB_CONTAINER& bbs, BB* bb) { BB *block; BB_CONTAINER::iterator iter; for (iter = bbs.begin(); iter != bbs.end(); iter++) { block = *iter; if (block == bb) return true; } return false; } //============================================================================= // Part 3: functions for if-conversion //============================================================================= //***************************************************************************** // Function : If_Conversion_Init // Input : // - region: a regino to be if-converted // - area_list : it is the result of the function. In area_list, there // are several IF_CONV_AREAs, which are the candidates to // be if-converted. After this function, there is only one // block in each IF_CONV_AREA. Some properties of those // IF_CONV_AREAs are fingured out. // Output: // < none> // Description : // The module will do something to initialize the data structure for // if-conversion. The main steps of the module are shown as follows: // 1) Construct an IF_CONV_AREA for each basis block in the input // region. // 2) Check if it is legal to if-convert each bb. // 3) Compute some properties for each IF_CONV_AREA, such as critical // path length and resource usage. Th step 2) and 3) are // implemented in the constructor of the class IF_CONV_AREA. // 4) Sort all IF_CONV_AREAs according to the post-DFS order. // //***************************************************************************** void IF_CONVERTOR::If_Conversion_Init(REGION *region, AREA_CONTAINER& area_list) { // create an IF_CONV_AREA for each basic block // area_table is used to record the map between basic blocks // and IF_CONV_AREAs BB_MAP area_table = BB_MAP_Create(); for (TOPOLOGICAL_REGIONAL_CFG_ITER iter( region -> Regional_Cfg()); iter!=0; ++iter) { REGIONAL_CFG_NODE *node = *iter; BB *pred_bb; IF_CONV_AREA *pred_area; if (node -> Is_Region()) { // if one area has a region successor, we do not // if-convert it for (CFG_PRED_NODE_ITER pred_iter(node); pred_iter!=0; ++pred_iter) { REGIONAL_CFG_NODE *pred = *pred_iter; if (pred -> Is_Region()) continue; pred_bb = pred -> BB_Node(); pred_area = (IF_CONV_AREA*)BB_MAP_Get(area_table, pred_bb); Is_True(pred_area != NULL, ("Can't find corresponding area for BB%d.\n", BB_id(pred_bb))); pred_area -> Area_Type(DOWNWARD_UNSUITABLE); } continue; } BB *bb = node -> BB_Node(); IF_CONV_AREA *area; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " -- solving BB%d: \n", BB_id(bb)); } // we do not generate IF_CONV_AREA for recovery block . // instead, we add those blocks in the IF_CONV_AREA of their // predecessors if ( BB_recovery(bb)) { Is_True(node -> Pred_Num() == 1, ("the basic block can only have one predecessor")); REGIONAL_CFG_NODE *pred = node -> First_Pred() -> Src(); if (!pred -> Is_Region()) { area = (IF_CONV_AREA*)BB_MAP_Get(area_table, pred -> BB_Node()); Is_True(pred_area != NULL, ("Can't find corresponding area for BB%d.\n", BB_id(pred_bb))); area -> Blocks().push_back(bb); BB_MAP_Set(area_table, bb, area); continue; } } // create an IF_CONV_AREA for the bb and add it into area_list area = CXX_NEW(IF_CONV_AREA(bb, this), &_m); area_list.push_back(area); //record the relation of bb and area into area_table; BB_MAP_Set(area_table, bb, area); // add edge between IF_CONV_AREAs for (CFG_PRED_NODE_ITER pred_iter(node); pred_iter!=0; ++pred_iter) { REGIONAL_CFG_NODE *pred = *pred_iter; if ( pred -> Is_Region()) { area -> Area_Type(UPWARD_UNSUITABLE); continue; } pred_bb = pred -> BB_Node(); pred_area = (IF_CONV_AREA*)BB_MAP_Get( area_table, pred_bb); Is_True(pred_area != NULL, ("Can't find corresponding area for BB%d.\n", BB_id(pred_bb))); Add_Edge( pred_area,area ); } if ( node -> Is_Exit()) { area -> Area_Type(DOWNWARD_UNSUITABLE); } } BB_MAP_Delete(area_table); } //***************************************************************************** // Function : Detect_Type // Input : // - area : the head area // - cand_list : a container of IF_CONV_AREAs. In fact, it is a part of the // result. If the control flow pattern of the head area // and its successors are suitable to be if-converted, the // function will return the proper type of it, and add // related IF_CONV_AREAs into cand_list. // Here, for each CFLOW_TYPE, the order of areas in // cand_list is fixed. It is: // SERIAL_TYPE: area1 -- area; // IF_THEN_TYPE: head -- then -- tail // IF_THEN_ELSE_TYPE: head - then - else - tail // or head - else - then - tail // - forced : default is FALSE // If TRUE a more aggresive pattern matching is used. // This should be only used during forced/relaxed if conversion // Output : // the type of the control flow pattern of the head area and its successors // Description : // The function will look for the candidate areas, in which the control // flow can be removed by if-converting them. Here, we only convert // three kinds of control flow patterns. They are: serial type, if-then // type, and if-then-else. The detail of those types is shown in if-conv.h. // //***************************************************************************** CFLOW_TYPE IF_CONVERTOR::Detect_Type(IF_CONV_AREA* area, AREA_CONTAINER& cand_list, BOOL forced) { if (area -> Area_Type() == UNSUITABLE || area -> Area_Type() == DOWNWARD_UNSUITABLE) return NO_TYPE; AREA_CONTAINER succs = area -> Succ_Set(); AREA_CONTAINER::iterator iter; // check all its successor IF_CONV_AREAs for ( iter = succs.begin(); iter != succs.end(); iter++) { IF_CONV_AREA *succ = *iter; if (succ -> Area_Type() == UNSUITABLE || succ -> Area_Type() == UPWARD_UNSUITABLE) return NO_TYPE; } // decide if it belongs to SERIAL_TYPE if (area -> Succ_Num() == 1 ) { IF_CONV_AREA *succ = *(succs.begin()); if (succ -> Pred_Num() == 1) { cand_list.push_back(area); cand_list.push_back(succ); return SERIAL_TYPE; } } if ( area -> Succ_Num() == 2 ) { IF_CONV_AREA *succ1, *succ2; iter = succs.begin(); succ1 = *iter; iter ++; succ2 = *iter; // decide if it is IF_THEN_TYPE if (succ1 -> Pred_Num() == 1 && Find_Area( succ1 -> Succ_Set(), succ2) != succ1->Succ_Set().end()) { cand_list.push_back(area); cand_list.push_back(succ1); cand_list.push_back(succ2); return IF_THEN_TYPE; } if (succ2 -> Pred_Num() == 1 && Find_Area( succ2 -> Succ_Set(), succ1) != succ2->Succ_Set().end()) { cand_list.push_back(area); cand_list.push_back(succ2); cand_list.push_back(succ1); return IF_THEN_TYPE; } // decide if it is IF_THEN_ELSE_TYPE if ( succ1 -> Pred_Num() == 1 && succ2 -> Pred_Num() == 1) { IF_CONV_AREA* common_succ = NULL; for ( iter = succ1 -> Succ_Set().begin(); iter != succ1 -> Succ_Set().end(); iter++) { IF_CONV_AREA* succ_of_succ1 = *iter; if ( Find_Area( succ2 -> Succ_Set(), succ_of_succ1) != succ2 -> Succ_Set().end()) { common_succ = succ_of_succ1; break; } } if ( common_succ) { cand_list.push_back(area); cand_list.push_back(succ2); cand_list.push_back(succ1); cand_list.push_back(common_succ); return IF_THEN_ELSE_TYPE; } } } if (forced && area -> Succ_Num() == 3) { IF_CONV_AREA *area1, *area2, *area3; IF_CONV_AREA *succ1, *succ2, *common_succ; iter = succs.begin(); area1 = *iter; iter++; area2 = *iter; iter++; area3 = *iter; if ( area1->Pred_Num() >= 3 && area2->Pred_Num() == 1 && area3->Pred_Num() == 1) { // area1 might be common successor common_succ = area1; succ1 = area2; succ2 = area3; } else if ( area1->Pred_Num() == 1 && area2->Pred_Num() >= 3 && area3->Pred_Num() == 1) { // area2 might be common successor common_succ = area2; succ1 = area1; succ2 = area3; } else if ( area1->Pred_Num() == 1 && area2->Pred_Num() == 1 && area3->Pred_Num() >= 3) { // area3 might be common successor common_succ = area3; succ1 = area1; succ2 = area2; } else { return NO_TYPE; } if (Find_Area (succ1->Succ_Set(), common_succ) == succ1->Succ_Set().end()) { return NO_TYPE; } if (Find_Area (succ2->Succ_Set(), common_succ) == succ2->Succ_Set().end()) { return NO_TYPE; } cand_list.push_back(area); cand_list.push_back(succ1); cand_list.push_back(succ2); cand_list.push_back(common_succ); return IF_THEN_ELSE_TYPE; } return NO_TYPE; } //***************************************************************************** // Function : Worth_If_Convert // Input : // - cand_list : a list of candidate areas, which are candidates to be // reduced to one bigger area if they can pass the // test of this function // - type : the type of the comming bigger area // Output : // a boolean value which indicates if the candidates have pass the test // Description : // The function will decide whether the recognized area is worth being // if-converted. The criteria used here are mainly about: the length of // critical path, the resource usage, the miss rate of branch predict, // the miss-penalty of branch predict, the number of instructions. //***************************************************************************** BOOL IF_CONVERTOR::Worth_If_Convert (AREA_CONTAINER& cand_list, CFLOW_TYPE type, BOOL forced) { if ( Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " \nConsider profitablity:"); } // take out the head area and its successors AREA_CONTAINER::iterator iter = cand_list.begin(); IF_CONV_AREA *head = *iter; Is_True(head != NULL, (" All if-conv types have a head-BB.\n ")); iter++; IF_CONV_AREA *succ1 = *iter; IF_CONV_AREA *succ2 = NULL; Is_True(succ1 != NULL, (" All if-conv types have at least one successor.\n ")); if ( type == IF_THEN_ELSE_TYPE ) { iter++; succ2 = *iter; } // evaluate the execution time for unpredicated code // here, we assume the latency of a call instruction is a big value INT32 time = 0; float exe_time = 0.0; INT32 min_cycle_1 = 0; Compute_Min_Cycle(min_cycle_1, succ1 -> Blocks()); INT32 min_cycle_2 = 0; if ( succ2 ) Compute_Min_Cycle(min_cycle_2, succ2 -> Blocks()); if (succ1 -> Cycled_Critical_Len() > min_cycle_1) { time = succ1 -> Cycled_Critical_Len(); } else { time = min_cycle_1; } float taken_rate_1 = Prob_Of_Area(head, succ1); float taken_rate_2 = 1 - taken_rate_1; exe_time += taken_rate_1 * time; if (succ2) { if (succ2 -> Cycled_Critical_Len() > min_cycle_2) { time = succ2 -> Cycled_Critical_Len(); } else { time = min_cycle_2; } exe_time += taken_rate_2 * time; } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " \n Prob : Area_%d ==> Area_%d: %f\n", head -> Area_Label(), succ1 -> Area_Label(), taken_rate_1); if ( succ2 ) { fprintf(TFile, " Prob : Area_%d ==> Area_%d: %f\n", head -> Area_Label(), succ2 -> Area_Label(), taken_rate_2); } fprintf(TFile, " min_cycle_1 : %d, min_cycle_2 : %d \n", min_cycle_1, min_cycle_2); fprintf(TFile, " critical_cycle_1 : %d ", succ1 -> Cycled_Critical_Len()); if ( succ2 ) { fprintf(TFile, ", critical_cycle_2 : %d \n", succ2 -> Cycled_Critical_Len()); } else { fprintf(TFile, "\n"); } } float branch_predict_miss_rate; if ( taken_rate_1 > taken_rate_2) { branch_predict_miss_rate = taken_rate_2; } else { branch_predict_miss_rate = taken_rate_1; } INT32 branch_predict_miss_panelty, fixed, brtaken; double factor; CGTARG_Compute_Branch_Parameters(&branch_predict_miss_panelty, &fixed, &brtaken, &factor); float unpredicated_time; unpredicated_time = exe_time + branch_predict_miss_rate * branch_predict_miss_panelty; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " unpredicated %f cycles vs", unpredicated_time); } // evaluate the execution time for predicated code INT32 max_res_height = 0; exe_time= 0.0; if ( succ2 ) { // compute execution time if (succ1 -> Cycled_Critical_Len() > succ2 -> Critical_Len()) { time = succ1 -> Cycled_Critical_Len(); } else { time = succ2 -> Critical_Len(); } exe_time += taken_rate_1* time; if (succ2 -> Cycled_Critical_Len() > succ1 -> Critical_Len()) { time = succ2 -> Cycled_Critical_Len(); } else { time = succ1 -> Critical_Len(); } exe_time += taken_rate_2* time; // compute the minimal cycle only considering the resource usage Compute_Min_Cycle(max_res_height, succ1 -> Blocks()); Compute_Min_Cycle(max_res_height, succ2 -> Blocks()); } else { exe_time += succ1 -> Cycled_Critical_Len(); Compute_Min_Cycle(max_res_height, succ1 -> Blocks()); } float predicated_time; predicated_time = exe_time > max_res_height ? exe_time : max_res_height; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " predicated %f cycles\n", predicated_time); } // decide if it is worth if-convertion // here, if the execution time of predicated code is less then the // execution time of unpredicated code, we think it should be if-converted if (unpredicated_time > predicated_time) { return TRUE; } else if (forced && ((predicated_time*100) < (_loop_length*IF_CONV_BIASE_THRESHOLD))) { return TRUE; } else { return FALSE; } } //***************************************************************************** // Function : Reduce_By_Type // Input : // -cand_list : a list of IF_CONV_AREAs, which are going to be reduced in // one IF_CONV_AREA. And such a IF_CONV_AREA is a candidate // area for if-conversion. // -type : the type of the result IF_CONV_AREA. // -area_list: the total IF_CONV_AREA list of the present region. // Output : // <none> // Description : // The function will reduce the selected areas into one IF_CONV_AREA. // It mainly consists of three steps: // 1) add all blocks in cand_list into the first area; // 2) delete all areas except the first area from the area list; // 3) maintain the predecessor and successor of the first area; // 4) maintain the related properties of the first area, // such as critical_path_length; // //***************************************************************************** void IF_CONVERTOR::Reduce_By_Type(AREA_CONTAINER& cand_list, CFLOW_TYPE type, AREA_CONTAINER& area_list) { AREA_CONTAINER::iterator iter= cand_list.begin(); IF_CONV_AREA *head = *iter; Is_True(head != NULL, (" All if-conv types have head-BB.\n ")); iter++; INT32 max_length1 = 0; INT32 max_length2 = 0; IF_CONV_AREA *succ1 = NULL; IF_CONV_AREA *succ2 = NULL; IF_CONV_AREA *tail = NULL; succ1 = *iter; iter++; Is_True(succ1 != NULL, (" All if-conv types have at least one successor.\n ")); if (type == IF_THEN_ELSE_TYPE) { succ2 = *iter; iter++; Is_True(succ2 != NULL, (" IF_THEN_ELSE_TYPE have at least two successor.\n ")); } if (iter != cand_list.end()) { tail = *iter; } // maintain the if-conversion type if (type == SERIAL_TYPE) { if (head -> Conv_Type() == FULLY_IF_CONV || succ1 -> Conv_Type() == FULLY_IF_CONV) { head -> Conv_Type(FULLY_IF_CONV); } } else { head -> Conv_Type(FULLY_IF_CONV); } if ( succ1 -> Area_Type() == DOWNWARD_UNSUITABLE || ( succ2 && succ2 -> Area_Type() == DOWNWARD_UNSUITABLE)) { if ( head -> Area_Type() == UPWARD_UNSUITABLE) { head -> Area_Type(UNSUITABLE); } else { head -> Area_Type(DOWNWARD_UNSUITABLE); } } // combine the included blocks into head head -> Combine_Blocks_With(succ1, &_m); if ( type == IF_THEN_ELSE_TYPE ) { head -> Combine_Blocks_With(succ2, &_m); } // maintain the edges AREA_CONTAINER successors = succ1 -> Succ_Set(); for (iter = successors.begin(); iter != successors.end(); iter++) { IF_CONV_AREA *succ_of_succ1 = *iter; if (tail && succ_of_succ1 == tail) continue; head -> Add_Succ(succ_of_succ1, this); succ_of_succ1 -> Add_Pred(head, this); succ_of_succ1 -> Del_Pred(succ1, this); } if (type == SERIAL_TYPE) { head -> Del_Succ(succ1, this); } if (type == IF_THEN_TYPE) { head -> Del_Succ(succ1, this); tail -> Del_Pred(succ1, this); } if (type == IF_THEN_ELSE_TYPE) { AREA_CONTAINER successors = succ2 -> Succ_Set(); for (iter = successors.begin(); iter != successors.end(); iter++) { IF_CONV_AREA* succ_of_succ2 = *iter; if (tail && succ_of_succ2 == tail) continue; head -> Add_Succ(succ_of_succ2, this); succ_of_succ2 -> Add_Pred(head, this); succ_of_succ2 -> Del_Pred(succ2, this); } head -> Del_Succ(succ1, this); head -> Del_Succ(succ2, this); head -> Add_Succ(tail, this); tail -> Del_Pred(succ1, this); tail -> Del_Pred(succ2, this); tail -> Add_Pred(head, this); } // maintain some properties of head if (type == IF_THEN_ELSE_TYPE) { max_length1 = succ1 -> Cycled_Critical_Len() > succ2 -> Cycled_Critical_Len()? succ1 -> Cycled_Critical_Len():succ2 -> Cycled_Critical_Len(); max_length2 = succ1 -> Critical_Len() > succ2 -> Critical_Len()? succ1 -> Critical_Len():succ2 -> Critical_Len(); } else { max_length1 = succ1 -> Cycled_Critical_Len(); max_length2 = succ1 -> Critical_Len() ; } head -> Cycled_Critical_Len(head-> Cycled_Critical_Len() + max_length1); head -> Critical_Len(head -> Critical_Len() + max_length2); // delete unnecessary areas area_list.erase(Find_Area(area_list, succ1)); CXX_DELETE(succ1, &_m); if (type == IF_THEN_ELSE_TYPE) { area_list.erase( Find_Area(area_list, succ2)); CXX_DELETE(succ2, &_m); } } //***************************************************************************** // Function : Select_Candidates // Input : // - area_list : a list of IF_CONV_AREAs // Output : // <none> // Description: // The function is to find the candidates for if-conversion. // Generally, the function will recognize the IF_CONV_AREAs which can not // be if-converted and combine the IF_CONV_AREAs, which are suitable to be // if converted, into larger ones. Before combination, we mainly do // profitablity checking. The legality checking has been done in the // process of initialization. // Here, the partial if-conversion will be delayed to the second release. // The function -- Worth_Partial_If_Convert will always return false. // //***************************************************************************** void IF_CONVERTOR::Select_Candidates (AREA_CONTAINER& area_list, BOOL forced) { IF_CONV_ALLOC temp_alloc(&_m); AREA_CONTAINER cand_list(temp_alloc); AREA_CONTAINER::iterator iter; BOOL reduced = TRUE; INT time = 0; while (reduced) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)){ fprintf(TFile," **** iteration %d ****\n", time); } reduced = FALSE; for (iter = area_list.begin(); iter!= area_list.end(); iter++) { IF_CONV_AREA *area = *iter; cand_list.clear(); if ( Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " -- solving AREA%d: \n", area -> Area_Label()); } // first, we try to find out an if-conversion area, whose head is // the head of area, according to the control flow CFLOW_TYPE type = Detect_Type (area, cand_list, forced); if (type == NO_TYPE) continue; if ( Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " Selected areas:"); AREA_CONTAINER::iterator it; for (it = cand_list.begin(); it != cand_list.end(); it++) { fprintf(TFile, "%d ", (*it)->Area_Label()); } fprintf(TFile,"\n"); } // profitability checking if (type == SERIAL_TYPE || Worth_If_Convert (cand_list, type, forced)) { reduced = TRUE; } else { continue; } Reduce_By_Type(cand_list, type, area_list); } time++; } } //***************************************************************************** // Function : Find_Start_Node // Input : // - area : a candidate IF_CONV_AREA // - bb : the bb for which we will find starting node // Output : // <none> // Description : // To find starting-nodes for a bb. // // Here, If we decide to generate parallel compare for one node, the // 'starting nodes' of it are the earliest nodes with which we can start to // generate parallel compare. // For example: // 1 // / \ // 2 // / \ // 3 // / \ // 4 // if we decide to generate parallel compare for BB_4. The control condition // of it can be (cond_2 && cond3) or (cond1 && cond2 && cond3) <cond_x mean // the compare condition of BB_x>. Here, if we take (cond2 && cond3), we call // start node of BB_4 is BB_2 and if we take (cond1 && cond2 && cond3), we // call BB_1 the start_node. // // For multiple cntl-dep-parent node, we will look for multiple start-nodes // for it corresponds to its all cntl-dep-parent. // // If there is no obstacle in BB2 and BB3 to block us to move generated // parallel compare instruction up to BB1, we can move them to the start node // and all generated parallel compare instruction can be guarded by the // predicates of starting nodes. In such conditions, we call BB2 and BB3 // is transitional. That is : // 'transitional' means a bb will not block generated parallel compare in the // BB to be moved up. //***************************************************************************** void IF_CONVERTOR::Find_Start_Node(IF_CONV_AREA* area, BB* bb) { BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb); Is_True( info != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb))); CNTL_DEP *cntl_info = area -> Cntl_Dep_Info(); BB_SET *cds = cntl_info -> Cntl_Dep_Parents(bb); // we do not generate parallel compare for the transitional node whose // compare instruction will be deleted. Because that means there will // be no instruction to be guarded by the qualifying predicates of it. if (!IPFEC_Force_Para_Comp_Gen) { if (info -> Transitional() && BB_SET_Size(cds) == 1) { return; } } BB *cd; //look for the starting nodes from bottom to up FOR_ALL_BB_SET_members(cds, cd) { BB *sn = cd; if (!IPFEC_Force_Para_Comp_Gen && info -> Transitional()) { // as above, for transitional node, we do not want to generate // parallel compare for it. But for or-type node, we must // generate parallel compare, so here, we just set the immediate // cntl_dep_parents as its starting node. info -> Start_Node(sn, cd); continue; } INT n = 0; while (n < MAX_NUM_PARA_CMP) { BB_PREDICATE_INFO *f = area -> Pred_Assign_Info(sn); Is_True( f != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(sn))); // a un-transitional node can stop us to go further to // look for the starting node if (!f -> Transitional()) break; // the following conditions are to keep us from introducing // too complicated conditions for parallel compare candidates BB_SET *cds_of_sn = cntl_info -> Cntl_Dep_Parents(sn); Is_True( cds_of_sn != NULL, ("Can't find cntl deps for BB%d.\n", BB_id(sn))); // a multiple-cntl-dep-parent node can stop us to go further // to look for the starting node if (BB_SET_Size(cds_of_sn) != 1) break; // when the present sn is not cntl-dep-parent of bb, the sn // will stop us go further // for example : // 1 // / \ // 2 // / \ // 3 // / \ // / 4 // \ / \ // 5 // when we look for the starting node for 5, if we find 3 is // start-node. the condition of 5 is cond3 || cond4. Then, we can // generate parallel compare for it. But, if we find that 2 is // the start-node corresponding to 3, the condition is // ( cond2 && cond3) || cond4 // the condition is too complex to generate parallel compare. if (BB_SET_Size(cds) > 1 && !BB_SET_MemberP(cds, BB_SET_Choose(cds_of_sn)) ) break; sn = BB_SET_Choose(cds_of_sn); n ++; } info -> Start_Node(sn, cd); } } BOOL IF_CONVERTOR::Check_If_Gen_Useless_Predicate( BB_PREDICATE_INFO* info) { // check if there is any useful predicate generated here if ( info -> True_TN() || info -> False_TN()) return false; TN_CONTAINER set; set = info -> Or_TNs(); if (!set.empty()) return false; set = info -> And_TNs(); if (!set.empty()) return false; set = info -> Orcm_TNs(); if (!set.empty()) return false; set = info -> Andcm_TNs(); if (!set.empty()) return false; return true; } //***************************************************************************** // Function : Record_Para_Comp_Info // Input : // - area : the candidate IF_CONV_AREA // - bb : the basic block to be solved // Output : // <none> // Description : // The following function will record some information for the predicate // of the basic block. The information includes: in a basic block, how many // predicate assignment instructions should be inserted into, what the type // they are, what are their target predicates and so on. //***************************************************************************** void IF_CONVERTOR::Record_Para_Comp_Info(IF_CONV_AREA *area, BB *bb) { CNTL_DEP *cntl_info = area -> Cntl_Dep_Info(); BB_PREDICATE_INFO *pred_info = area -> Pred_Assign_Info(bb); Is_True(pred_info != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb))); TN *p = pred_info -> Predicate(); BB *entry = area -> Entry_BB(); BB_SET *cds = cntl_info -> Cntl_Dep_Parents(bb); BB_SET *true_edges = cntl_info -> True_Cntl_Dep_Parents(bb); // solve the non-parallel-compare-candidates if (!pred_info -> Has_Start_Node()) { Is_True(BB_SET_Size(cds) <=1,("non-parallel-comparea-candidate " "can only has one control dependentor!\n")); if (BB_SET_Size(cds) == 0) return; TN *true_tn = NULL; TN *false_tn = NULL; BB *bb_cd = BB_SET_Choose(cds); BB_PREDICATE_INFO *pred_info_of_cd = area -> Pred_Assign_Info(bb_cd); Is_True(pred_info != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb_cd))); if (BB_SET_MemberP(true_edges, bb_cd)) { pred_info_of_cd -> True_TN(p); } else { pred_info_of_cd -> False_TN(p); } return; } if (Get_Trace(TP_PTRACE1, TP_PTRACE1_CG)) { char tmp_string[6]=""; sprintf(tmp_string, "%d", BB_id(bb)); Generate_Tlog("AIC", "parallel_compare_generation", (SRCPOS)0, tmp_string, "", "", ""); } //solve the parallel compare candidates if ( BB_SET_Size(cds) > 1) { // for or/orcm type // insert an initialization instruction for the or-type predicate OPS ops = OPS_EMPTY; Exp_Pred_Set(p, True_TN, 0, &ops); hTN_MAP_Set(init_op_info, p, ops.first); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { Print_OPS(&ops); } // Insert the predicate initialization code just before the branch // (if it exists) or append it to the Entry block. OP *xfer_op; if (xfer_op = BB_xfer_op(entry)) { BB_Insert_Ops_Before (entry, xfer_op, &ops); } else { BB_Append_Ops (entry, &ops); } // record the information about the predicates assignments in the // corresponding start node BB *cd; FOR_ALL_BB_SET_members(cds, cd) { BB_PREDICATE_INFO* info_of_cd = area -> Pred_Assign_Info(cd); Is_True(info_of_cd != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(cd))); if (BB_SET_MemberP(true_edges, cd)) { info_of_cd -> Add_Or_TNs(p); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, "add or %s ", p); fprintf(TFile, " into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb)); } } else { info_of_cd -> Add_Orcm_TNs(p); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, "add orcm %s ", p); fprintf(TFile, " into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb)); } } } } else { Is_True( BB_SET_Size(cds) == 1, (" and-type node can only have one cd.\n")); // for and/andcm type // assign a new predicate for the and/andcm-type candidate p = Gen_Predicate_TN(); pred_info -> Orig_Pred(pred_info -> Predicate()); pred_info -> Predicate(p); BB *cd = BB_SET_Choose(cds); // insert an initialization instruction for the or-type predicate OPS ops = OPS_EMPTY; Exp_Pred_Set(p, True_TN, 1, &ops); hTN_MAP_Set(init_op_info, p, ops.first); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { Print_OPS(&ops); } BB* start_node = pred_info -> Start_Node(cd); OP *xfer_op; if (xfer_op = BB_xfer_op(start_node)) { BB_Insert_Ops_Before (start_node, xfer_op, &ops); } else { BB_Append_Ops (start_node, &ops); } BB *sn = pred_info -> Start_Node(cd); BB_PREDICATE_INFO *info_of_cd; Is_True(info_of_cd != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(cd))); BOOL is_start = false; while (!is_start) { is_start = (cd == sn); info_of_cd = area -> Pred_Assign_Info(cd); if (BB_SET_MemberP(true_edges, cd)) { info_of_cd -> Add_And_TNs(p); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, "add and %s ", p); fprintf(TFile, " into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb)); } } else { info_of_cd -> Add_Andcm_TNs(p); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, "add andcm %s ", p); fprintf(TFile, " into BB%d when solving BB%d\n", BB_id(cd), BB_id(bb)); } } true_edges = cntl_info -> True_Cntl_Dep_Parents(cd); cds = cntl_info -> Cntl_Dep_Parents(cd); cd = BB_SET_Choose(cds); } } } //***************************************************************************** // Function : Detect_Para_Comp // Input : // - area : a candidate IF_CONV_AREA // Output : // <none> // Description : // In the following two cases, we need to generate parallel compare: // 1) when a basic block has multiple parents in the control dependent tree, // we need to generate parallel compare for the basic block. In the case, // the condition to invoke the basic block is the result of or-operation // of all conditions of its control-dependence parents. So, we must // generate parallel compare to predicate the block. // 2) generating parallel compare can shorten the dependent height of a // serial of compares. In the case, we generate parallel compare for // optimizing code. // The function is used to select the chance to generate parallel compare. // 'Parallel compare candidates' indicate those basic blocks, whose // qualifying predicate of which we decide to generate parallel compare. // Besides, we call the instructions to assign to the predicate as related // predicated assignments. // // In detail, the function will // 1) select the parallel compare candidates; // 2) compute the starting node for each parallel compare candidates. // As a result, the starting node is saved in one member of // BB_PREDICATE_INFO -- start_nodes. If its start_nodes is NULL, we will // not generate parallel compare for the predicate of the node. // Start_nodes is a BB_MAP. In the BB_MAP, we record the starting node // for each control dependencer of the basic block. // The conception of 'starting-node' is in the description of function // 'Find_Start_Node'. // //***************************************************************************** void IF_CONVERTOR::Detect_Para_Comp(IF_CONV_AREA* area) { BB_CONTAINER& bbs = area -> Blocks(); CNTL_DEP *cntl_info = area -> Cntl_Dep_Info(); // // step1: mark transitional nodes // // Here, we should generate parallel compare only when // the action can lead performance improvement. So we need a cost model // to select parallel compare candidates. In the first release, the cost // model will be very simple. If there is not a downward-exposed definition // in one basic block, we remark it and call it as a transitional node. // That means, there is no obstacle for us to move the related predicate // assignments up to the control dependent parent of it. If several // predicate assignments can be moved to one place, they can run in // one cycle and the performance will be better. // if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " Start to decide transitional!\n"); } BB_CONTAINER::iterator bb_iter; BB *bb; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " -- solving BB%d:", BB_id(bb)); } if (BB_recovery(bb)) continue; OP *br_op = BB_branch_op(bb); OP *cmp_op = NULL; if (br_op && OP_has_predicate(br_op)) { TN *pred_tn = OP_opnd(br_op, OP_PREDICATE_OPND); vector<OP *> ops; cmp_op = TN_Defined_At_Op(pred_tn, br_op, &ops); } OP *op; BOOL is_transitional = TRUE; BB_SET* cd_children = BB_SET_Create_Empty(PU_BB_Count, &_m); cntl_info -> Cntl_Dep_Children(cd_children, bb, &_m); if (BB_SET_Size(cntl_info -> Cntl_Dep_Parents(bb)) ==0 || BB_SET_Size(cd_children) == 0) { is_transitional = FALSE; } else if ( cmp_op && !Has_Para_Comp_Top(cmp_op)) { is_transitional =FALSE; } else { if ( !br_op || !cmp_op ) { is_transitional = FALSE; } else { FOR_ALL_BB_OPs_FWD(bb, op) { if ( op != br_op && op != cmp_op ) { is_transitional = FALSE; break; } } } } if (IPFEC_Force_Para_Comp_Gen || (is_transitional && IPFEC_Para_Comp_Gen)) { BB_PREDICATE_INFO *pred_info = area -> Pred_Assign_Info(bb); Is_True(pred_info != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb))); pred_info -> Set_Transitional(); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " transitional \n"); } } else { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " not transitional \n"); } } } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " Start to find starting node and collect info of pred! \n"); } //step2: compute starting-nodes and collect information of predicates BB_CONTAINER result; cntl_info -> Get_Post_Order(result, this); for (bb_iter = result.begin(); bb_iter != result.end(); bb_iter++) { bb = *bb_iter; BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb); Is_True(info != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb))); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " -- solving BB%d:\n", BB_id(bb)); } // we will ignore the recovery nodes during predicating if ( BB_recovery(bb)) continue; if (!info -> Eqv_Class_Head()) { BB_PREDICATE_INFO *head_info = area -> Pred_Assign_Info(info -> Eqv_Class_Head_BB()); info -> Orig_Pred( info -> Predicate() ); info -> Predicate(head_info -> Predicate()); continue; } // compute starting-nodes for parallel compare candidates BB_SET* cds = cntl_info -> Cntl_Dep_Parents(bb); Is_True( cds != NULL, ("Can't find cntl deps for BB%d.\n", BB_id(bb))); BOOL cd_is_transitional = false; if (BB_SET_Size(cds) == 1) { BB* cd = BB_SET_Choose(cds); BB_PREDICATE_INFO *info_of_cd = area -> Pred_Assign_Info(cd); cd_is_transitional = info_of_cd -> Transitional(); } if ( BB_SET_Size(cds) >1 || cd_is_transitional) Find_Start_Node(area,bb); // collect the information of all predicates and their related // assignments Record_Para_Comp_Info(area, bb); } } //***************************************************************************** // Function : Gen_Para_Comp // Input : // - area : the candidate IF_CONV_AREA // Output : // <none> // Description : // In this function, we will generate the parallel compare for each basic // block. Here, we will try to generate the instructions as few as possible. // For example, we have an 'or' TN -- p and an 'andcm' TN - q, we will // generate 'p,q = cmp. or. andcm cond (qp)' instead of // 'p = cmp.or cond (qp) ; q = cmp.andcm cond (qp)'. // Even though, after this phase, some useless predicate assignments will // appear. In the first release, we depend on the dead-code- elimination // to eliminate those assignments. //***************************************************************************** void IF_CONVERTOR::Gen_Para_Comp (IF_CONV_AREA *area) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { area -> Print(TFile); } BB_CONTAINER& bbs = area -> Blocks(); BB_CONTAINER::iterator bb_iter; BB *bb; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " -- solving BB%d:\n", BB_id(bb)); } BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb); Is_True( info != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb))); if (BB_recovery(bb)) continue; // in the following steps, we try to combine the predicate assignments // which fit the following conditions: // 1) their qualifying predicates are identical; Here, the compare // instructions to be inserted into one basic block will use the // qualifying predicate of the basic block. So their guarding // predicates are surely identical. // 2) their types are compatible; // here the compatible types are: // and/and, or/or, andcm/andcm, orcm/orcm/, or/andcm, and/orcm // OPS op_list = OPS_EMPTY; if (Check_If_Gen_Useless_Predicate(info)) continue; OP *br_op = BB_branch_op(bb); OP *cmp_op = NULL; if (br_op && OP_has_predicate(br_op)) { TN *pred_tn = OP_opnd(br_op, OP_PREDICATE_OPND); vector<OP *> ops; cmp_op = TN_Defined_At_Op(pred_tn, br_op, &ops); } // // For example, if there is a compare instruction in the bb, such as: // p, q = cmp_type, a>b (qp) // now, we want to add assignment for two predicates: p1, q2, and they // are or-type and they have the same quaulifing predicate // -- qp_of_start. now , we have two approaches: // Approach1: p, q = cmp_type a>b (qp) // p1, q2 = cmp_or 0!=0 (p) // Approach2: p , q = cmp_type a>b (qp) // p1, q1 = cmp_or a>b (qp_of_start) // here, we adopt approach2 if it is legal. // TN *p1, *p2, *start_qp; TOP pred_top; TN *qp; COMPARE_TYPE type; while (Get_2_Pred_And_Erase(p1, p2, type, bb, info)) { TN *qp1 = Get_Start_Node_Pred(p1, bb, area); TN* qp2 = NULL; if (p2 != True_TN) { qp2 = Get_Start_Node_Pred(p2, bb, area); } if (p2 == True_TN || qp1 == qp2) { pred_top = Get_Para_Comp_Top(cmp_op, type); qp = qp1; } else { pred_top = TOP_UNDEFINED; } if (pred_top == TOP_UNDEFINED) { TN *true_tn = NULL; TN *false_tn = NULL; Find_BB_Predicates(bb, true_tn, false_tn); if (type == COMPARE_TYPE_or || type == COMPARE_TYPE_andcm || type == COMPARE_TYPE_or_andcm) { qp = true_tn ? true_tn : True_TN; } else if (type == COMPARE_TYPE_orcm || type == COMPARE_TYPE_and || type == COMPARE_TYPE_and_orcm) { qp = false_tn ? false_tn: True_TN; } else { Is_True(0, ("wrong compare type!\n")); } } Gen_Predicate_Assign(p1,p2, cmp_op, type, pred_top, qp, &op_list); } OP* new_op; FOR_ALL_OPS_OPs_FWD((&op_list),new_op){ Set_OP_cond_def_kind(new_op, OP_ALWAYS_COND_DEF); } // Insert these just before the ending branch if (OPS_first(&op_list)) { Is_True(br_op, ("parallel compare can only added into split bb.\n")); BB_Insert_Ops(bb, br_op, &op_list, true); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { Print_OPS(&op_list); } } } } TOP cmp_top_index[COMP_TOP_NUM] = { TOP_cmp_ne, TOP_cmp_ne_unc, TOP_cmp4_ne, TOP_cmp4_ne_unc, TOP_cmp_i_ne, TOP_cmp_i_ne_unc, TOP_cmp4_i_ne, TOP_cmp4_i_ne_unc, TOP_cmp4_ge, TOP_cmp4_ge_unc, TOP_cmp4_gt, TOP_cmp4_gt_unc, TOP_cmp4_le, TOP_cmp4_le_unc, TOP_cmp4_lt, TOP_cmp4_lt_unc, TOP_cmp_ge, TOP_cmp_ge_unc, TOP_cmp_gt, TOP_cmp_gt_unc, TOP_cmp_le, TOP_cmp_le_unc, TOP_cmp_lt, TOP_cmp_lt_unc, TOP_cmp4_i_eq, TOP_cmp4_i_eq_unc, TOP_cmp4_eq, TOP_cmp4_eq_unc, TOP_cmp_i_eq, TOP_cmp_i_eq_unc, TOP_cmp_eq, TOP_cmp_eq_unc }; TOP para_comp_top[COMP_TOP_NUM][PARA_COMP_TYPE_NUM] = { { TOP_cmp_ne_or, TOP_cmp_ne_orcm , TOP_cmp_ne_and, TOP_cmp_ne_andcm, TOP_cmp_ne_or_andcm, TOP_cmp_ne_and_orcm }, // cmp_ne { TOP_cmp_ne_or, TOP_cmp_ne_orcm , TOP_cmp_ne_and, TOP_cmp_ne_andcm, TOP_cmp_ne_or_andcm, TOP_cmp_ne_and_orcm }, // cmp_ne_unc { TOP_cmp4_ne_or, TOP_cmp4_ne_orcm, TOP_cmp4_ne_and, TOP_cmp4_ne_andcm, TOP_cmp4_ne_or_andcm, TOP_cmp4_ne_and_orcm }, // cmp4_ne { TOP_cmp4_ne_or, TOP_cmp4_ne_orcm, TOP_cmp4_ne_and, TOP_cmp4_ne_andcm, TOP_cmp4_ne_or_andcm, TOP_cmp4_ne_and_orcm }, // cmp4_ne_unc { TOP_cmp_i_ne_or, TOP_cmp_i_ne_orcm, TOP_cmp_i_ne_and, TOP_cmp_i_ne_andcm, TOP_cmp_i_ne_or_andcm, TOP_cmp_i_ne_and_orcm }, // cmp_i_ne { TOP_cmp_i_ne_or, TOP_cmp_i_ne_orcm, TOP_cmp_i_ne_and, TOP_cmp_i_ne_andcm, TOP_cmp_i_ne_or_andcm, TOP_cmp_i_ne_and_orcm }, // cmp_i_ne_unc { TOP_cmp4_i_ne_or, TOP_cmp4_i_ne_orcm, TOP_cmp4_i_ne_and, TOP_cmp4_i_ne_andcm, TOP_cmp4_i_ne_or_andcm, TOP_cmp4_i_ne_and_orcm }, //cmp4_i_ne: { TOP_cmp4_i_ne_or, TOP_cmp4_i_ne_orcm, TOP_cmp4_i_ne_and, TOP_cmp4_i_ne_andcm, TOP_cmp4_i_ne_or_andcm, TOP_cmp4_i_ne_and_orcm }, //cmp4_i_ne_unc { TOP_cmp4_ge_or, TOP_cmp4_ge_orcm, TOP_cmp4_ge_and, TOP_cmp4_ge_andcm, TOP_cmp4_ge_or_andcm, TOP_cmp4_ge_and_orcm }, //cmp4_ge { TOP_cmp4_ge_or, TOP_cmp4_ge_orcm, TOP_cmp4_ge_and, TOP_cmp4_ge_andcm, TOP_cmp4_ge_or_andcm, TOP_cmp4_ge_and_orcm }, //cmp4_ge_unc { TOP_cmp4_gt_or, TOP_cmp4_gt_orcm, TOP_cmp4_gt_and, TOP_cmp4_gt_andcm, TOP_cmp4_gt_or_andcm, TOP_cmp4_gt_and_orcm }, //cmp4_gt { TOP_cmp4_gt_or, TOP_cmp4_gt_orcm, TOP_cmp4_gt_and, TOP_cmp4_gt_andcm, TOP_cmp4_gt_or_andcm, TOP_cmp4_gt_and_orcm }, //cmp4_gt_unc { TOP_cmp4_le_or, TOP_cmp4_le_orcm, TOP_cmp4_le_and, TOP_cmp4_le_andcm, TOP_cmp4_le_or_andcm, TOP_cmp4_le_and_orcm }, //cmp4_le { TOP_cmp4_le_or, TOP_cmp4_le_orcm, TOP_cmp4_le_and, TOP_cmp4_le_andcm, TOP_cmp4_le_or_andcm, TOP_cmp4_le_and_orcm }, //cmp4_le_unc { TOP_cmp4_lt_or, TOP_cmp4_lt_orcm, TOP_cmp4_lt_and, TOP_cmp4_lt_andcm, TOP_cmp4_lt_or_andcm, TOP_cmp4_lt_and_orcm }, //cmp4_lt { TOP_cmp4_lt_or, TOP_cmp4_lt_orcm, TOP_cmp4_lt_and, TOP_cmp4_lt_andcm, TOP_cmp4_lt_or_andcm, TOP_cmp4_lt_and_orcm }, //cmp4_lt_unc { TOP_cmp_ge_or, TOP_cmp_ge_orcm, TOP_cmp_ge_and, TOP_cmp_ge_andcm, TOP_cmp_ge_or_andcm, TOP_cmp_ge_and_orcm }, //cmp_ge { TOP_cmp_ge_or, TOP_cmp_ge_orcm, TOP_cmp_ge_and, TOP_cmp_ge_andcm, TOP_cmp_ge_or_andcm, TOP_cmp_ge_and_orcm }, //cmp_ge_unc { TOP_cmp_gt_or, TOP_cmp_gt_orcm, TOP_cmp_gt_and, TOP_cmp_gt_andcm, TOP_cmp_gt_or_andcm, TOP_cmp_gt_and_orcm }, //cmp_gt { TOP_cmp_gt_or, TOP_cmp_gt_orcm, TOP_cmp_gt_and, TOP_cmp_gt_andcm, TOP_cmp_gt_or_andcm, TOP_cmp_gt_and_orcm }, //cmp_gt_unc { TOP_cmp_le_or, TOP_cmp_le_orcm, TOP_cmp_le_and, TOP_cmp_le_andcm, TOP_cmp_le_or_andcm, TOP_cmp_le_and_orcm }, //cmp_le { TOP_cmp_le_or, TOP_cmp_le_orcm, TOP_cmp_le_and, TOP_cmp_le_andcm, TOP_cmp_le_or_andcm, TOP_cmp_le_and_orcm }, //cmp_le_unc { TOP_cmp_lt_or, TOP_cmp_lt_orcm, TOP_cmp_lt_and, TOP_cmp_lt_andcm, TOP_cmp_lt_or_andcm, TOP_cmp_lt_and_orcm }, //cmp_lt: { TOP_cmp_lt_or, TOP_cmp_lt_orcm, TOP_cmp_lt_and, TOP_cmp_lt_andcm, TOP_cmp_lt_or_andcm, TOP_cmp_lt_and_orcm }, //cmp_lt_unc { TOP_cmp4_i_eq_or, TOP_cmp4_i_eq_orcm, TOP_cmp4_i_eq_and, TOP_cmp4_i_eq_andcm, TOP_cmp4_i_eq_or_andcm, TOP_cmp4_i_eq_and_orcm }, //cmp4_i_eq { TOP_cmp4_i_eq_or, TOP_cmp4_i_eq_orcm, TOP_cmp4_i_eq_and, TOP_cmp4_i_eq_andcm, TOP_cmp4_i_eq_or_andcm, TOP_cmp4_i_eq_and_orcm }, //cmp4_i_eq_unc { TOP_cmp4_eq_or, TOP_cmp4_eq_orcm, TOP_cmp4_eq_and, TOP_cmp4_eq_andcm, TOP_cmp4_eq_or_andcm, TOP_cmp4_eq_and_orcm }, //cmp4_eq { TOP_cmp4_eq_or, TOP_cmp4_eq_orcm, TOP_cmp4_eq_and, TOP_cmp4_eq_andcm, TOP_cmp4_eq_or_andcm, TOP_cmp4_eq_and_orcm }, //cmp4_eq_unc { TOP_cmp_i_eq_or, TOP_cmp_i_eq_orcm, TOP_cmp_i_eq_and, TOP_cmp_i_eq_andcm, TOP_cmp_i_eq_or_andcm, TOP_cmp_i_eq_and_orcm }, //cmp_i_eq: { TOP_cmp_i_eq_or, TOP_cmp_i_eq_orcm, TOP_cmp_i_eq_and, TOP_cmp_i_eq_andcm, TOP_cmp_i_eq_or_andcm, TOP_cmp_i_eq_and_orcm }, //cmp_i_eq_unc: { TOP_cmp_eq_or, TOP_cmp_eq_orcm, TOP_cmp_eq_and, TOP_cmp_eq_andcm, TOP_cmp_eq_or_andcm, TOP_cmp_eq_and_orcm }, //cmp_eq { TOP_cmp_eq_or, TOP_cmp_eq_orcm, TOP_cmp_eq_and, TOP_cmp_eq_andcm, TOP_cmp_eq_or_andcm, TOP_cmp_eq_and_orcm } //cmp_eq_unc }; BOOL IF_CONVERTOR::Has_Para_Comp_Top(OP* cmp_op) { if (OP_flop(cmp_op)) { return false; } TOP cmp_top = OP_code(cmp_op); if (OP_opnd(cmp_op, 1) != Zero_TN && OP_opnd(cmp_op, 2) != Zero_TN) { switch (cmp_top) { case TOP_cmp_ne: case TOP_cmp4_ne: case TOP_cmp_i_ne: case TOP_cmp4_i_ne: case TOP_cmp4_i_eq: case TOP_cmp4_eq: case TOP_cmp_i_eq: case TOP_cmp_eq: case TOP_cmp_ne_unc: case TOP_cmp4_ne_unc: case TOP_cmp_i_ne_unc: case TOP_cmp4_i_ne_unc: case TOP_cmp4_i_eq_unc: case TOP_cmp4_eq_unc: case TOP_cmp_i_eq_unc: case TOP_cmp_eq_unc: break; default: return false; } } return false; } TOP IF_CONVERTOR::Get_Para_Comp_Top(OP* cmp_op, COMPARE_TYPE ctype) { if ( !Has_Para_Comp_Top(cmp_op) ) return TOP_UNDEFINED; TOP cmp_top = OP_code(cmp_op); INT index = 0; while (index < COMP_TOP_NUM) { if ( cmp_top == cmp_top_index[index]) break; index++; } if (index >= COMP_TOP_NUM) return TOP_UNDEFINED; INT id = (int)ctype; Is_True( id>=1 && id <= PARA_COMP_TYPE_NUM, ("no such a ctype!")); return para_comp_top[index][id-1]; } TN* IF_CONVERTOR::Get_1_Pred_And_Erase(TN_CONTAINER& tn_set) { TN_CONTAINER::iterator iter; TN *p1; iter = tn_set.begin(); p1 = *iter; tn_set.erase(iter); return p1; } BOOL IF_CONVERTOR::Get_2_Pred_And_Erase(TN*& p1, TN*& p2, COMPARE_TYPE& type, BB* bb, BB_PREDICATE_INFO *info) { // solve 'and_tns' and 'orcm_tns' TN_CONTAINER& tn_set1 = info -> And_TNs(); TN_CONTAINER& tn_set2 = info -> Orcm_TNs(); if (tn_set1.size() >=2) { p1 = Get_1_Pred_And_Erase(tn_set1); p2 = Get_1_Pred_And_Erase(tn_set1); type = COMPARE_TYPE_and; return true; } if ( tn_set1.size()) { p1 = Get_1_Pred_And_Erase(tn_set1); if (tn_set2.size()) { p2 = Get_1_Pred_And_Erase(tn_set2); type = COMPARE_TYPE_and_orcm; return true; } else { p2 = True_TN; type = COMPARE_TYPE_and; return true; } } if (tn_set2.size() >=1) { p1 = Get_1_Pred_And_Erase(tn_set2); if (tn_set2.size()) { p2 = Get_1_Pred_And_Erase(tn_set2); } else { p2 = True_TN; } type = COMPARE_TYPE_orcm; return true; } // solve 'or_tns' and 'andcm_tns' TN_CONTAINER& tn_set3 = info -> Or_TNs(); TN_CONTAINER& tn_set4 = info -> Andcm_TNs(); if (tn_set3.size() >=2) { p1 = Get_1_Pred_And_Erase(tn_set3); p2 = Get_1_Pred_And_Erase(tn_set3); type = COMPARE_TYPE_or; return true; } if ( tn_set3.size()) { p1 = Get_1_Pred_And_Erase(tn_set3); if (tn_set4.size()) { p2 = Get_1_Pred_And_Erase(tn_set4); type = COMPARE_TYPE_or_andcm; return true; } else { p2 = True_TN; type = COMPARE_TYPE_or; return true; } } if ( tn_set4.size() >=1) { p1 = Get_1_Pred_And_Erase(tn_set4); if ( tn_set4.size()) { p2 = Get_1_Pred_And_Erase(tn_set4); } else { p2 = True_TN; } type = COMPARE_TYPE_andcm; return true; } return false; } TN* IF_CONVERTOR:: Get_Start_Node_Pred(TN *pred, BB *present_solving_bb, IF_CONV_AREA *area) { BB *bb_of_pred; BB_PREDICATE_INFO *info = NULL; BB_CONTAINER& bbs = area -> Blocks(); BB_CONTAINER::iterator bb_iter; BB *bb; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; info = area -> Pred_Assign_Info(bb); if ( pred == info -> Predicate()) { bb_of_pred = bb; break; } } Is_True( info, (" Generate useless predicate assignment.\n")); TN *result = NULL; CNTL_DEP *cd_info = area -> Cntl_Dep_Info(); BB_SET *cds = cd_info -> Cntl_Dep_Parents(bb_of_pred); if (BB_SET_Size(cds) == 1) { BB* cd = BB_SET_Choose(cds); BB* start_node = info -> Start_Node(cd); result = area -> Pred_Assign_Info(start_node) -> Predicate(); } else { Is_True(BB_SET_MemberP(cds, present_solving_bb), ("predicate assign holder must in cds")); BB* start_node = info -> Start_Node(present_solving_bb); result = area -> Pred_Assign_Info(start_node) -> Predicate(); } if ( !result ) result = True_TN; return result; } void IF_CONVERTOR::Gen_Predicate_Assign(TN* result1, TN *result2, OP* cmp_op, COMPARE_TYPE ctype, TOP pred_top, TN *qual_pred, OPS* ops) { if ( pred_top != TOP_UNDEFINED) { Build_OP(pred_top, result1, result2, qual_pred, OP_opnd(cmp_op, OP_PREDICATE_OPND+1), OP_opnd(cmp_op, OP_PREDICATE_OPND+2), ops); } else { TOP top; switch (ctype) { case COMPARE_TYPE_or: top = TOP_cmp_eq_or; break; case COMPARE_TYPE_andcm: top = TOP_cmp_eq_andcm; break; case COMPARE_TYPE_or_andcm: top = TOP_cmp_eq_or_andcm; break; case COMPARE_TYPE_and: top = TOP_cmp_ne_and; break; case COMPARE_TYPE_orcm: top = TOP_cmp_ne_orcm; break; case COMPARE_TYPE_and_orcm: top = TOP_cmp_ne_and_orcm; break; default: Is_True(0,("Illegal Compare Type.\n")); } Build_OP(top, result1, result2, qual_pred, Zero_TN, Zero_TN, ops); } } TN* Predicate_Of_Succ(BB *bb, BB * succ, BB *fall_thru, BB_PREDICATE_INFO *info) { TN *pp = NULL; if ( BB_succs_len(bb) == 1 ) { pp = info -> Predicate(); } else if (BB_succs_len(bb) == 2) { TN *first_pred = NULL; TN *second_pred = NULL; Find_BB_Predicates(bb, first_pred, second_pred); Is_True(first_pred && second_pred, (" lack of a predicate!\n")); OP *br = BB_branch_op(bb); Is_True(br, (" two-successor bb must have br\n")); if (( first_pred == OP_opnd(br, OP_PREDICATE_OPND) && succ != fall_thru) || ( second_pred == OP_opnd(br, OP_PREDICATE_OPND) && succ == fall_thru)) { pp = first_pred; } else { pp = second_pred; } } return pp; } //***************************************************************************** // Function : Insert_Predicate // Input : // - area : the candidate // Output : // < none > // Description : // change the selected candidates to predicated code //***************************************************************************** BOOL IF_CONVERTOR::Insert_Predicate(IF_CONV_AREA *area) { // // step1: compute the equivalence classes and assign predicates for each // equivalent class // here, we use a BB_SET to represent equivalence class // each bb in it represents a class of bbs who have the same control // dependence // if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, "\n Start to assign predicates!\n"); } // we record the found information into BB_PREDICATE_INFO of each // bb BB_SET *equal_classes = BB_SET_Create_Empty(PU_BB_Count, &_m); CNTL_DEP *cd_info = area -> Cntl_Dep_Info(); BB_CONTAINER& bbs = area -> Blocks(); BB_CONTAINER::iterator bb_iter; BB *bb; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " -- solving BB%d: ", BB_id(bb)); } if ( BB_recovery(bb)) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " it is a recovery bb.\n"); } continue; } BB_PREDICATE_INFO *pred_info = area ->Pred_Assign_Info(bb); BB_SET *cds_of_bb = cd_info -> Cntl_Dep_Parents(bb); BB_SET *te_of_bb = cd_info -> True_Cntl_Dep_Parents(bb); // // Find out the equivalence class for bb. If there is no existing // equivalent class, create a new one and insert bb into it. // BOOL find_ec = false; BB *ec; FOR_ALL_BB_SET_members(equal_classes, ec) { BB_SET *cds_of_ec = cd_info -> Cntl_Dep_Parents(ec); Is_True( cds_of_ec != NULL, ("Can't find cntl deps for BB%d.\n", BB_id(ec))); BB_SET *te_of_ec = cd_info -> True_Cntl_Dep_Parents(ec); Is_True( te_of_ec != NULL, ("Can't find true edges for BB%d.\n", BB_id(ec))); if (BB_SET_EqualP(cds_of_bb, cds_of_ec) &&BB_SET_EqualP(te_of_bb, te_of_ec)) { BB_PREDICATE_INFO *pred_of_ec = area ->Pred_Assign_Info (ec); Is_True(pred_of_ec != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb))); pred_info -> Predicate(pred_of_ec -> Predicate()); pred_info -> Eqv_Class_Head_BB(ec); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, " got(share): %s", pred_of_ec -> Predicate()); } find_ec = true; break; } } if (!find_ec) { equal_classes = BB_SET_Union1D(equal_classes, bb, &_m); pred_info -> Set_Eqv_Class_Head(); // set predicate TN for them INT num_deps = BB_SET_Size(cds_of_bb); if (num_deps == 1) { // if bb has single dependence, set up the TRUE // and FALSE tns for the block. TN *true_tn = NULL; TN *false_tn = NULL; BB *bb_cd = BB_SET_Choose(cds_of_bb); Find_BB_Predicates(bb_cd, true_tn, false_tn); // set the predicate for the equivalance class if (BB_SET_MemberP(te_of_bb, bb_cd)) { pred_info ->Predicate(true_tn); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, " got: %s\n", true_tn); } } else { pred_info ->Predicate(false_tn); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, " got: %s\n", false_tn); } } } else if (num_deps > 1) { // multiple dependencies. create a new predicate TN for them TN *pred_tn; pred_tn = Gen_Predicate_TN(); pred_info -> Predicate(pred_tn); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fPrint_TN(TFile, " got: %s\n", pred_tn); } } } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n"); } } // the following is to collect information of exits, including: // 1. how many exits in the area // 2. how many branches in the area // 3. the information of the targets of all exits for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; BB* fall_thru = BB_Fall_Thru_Successor(bb); BBLIST *succ_bl; FOR_ALL_BB_SUCCS(bb, succ_bl) { BB* succ = BBLIST_item(succ_bl); if (!Is_BB_Container_Member(bbs, succ) || Regional_Cfg_Node(bb) -> First_Succ() == NULL) { // record its information EXIT_TARGET_INFO *tgt = area -> Exit_Target(succ); BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb); TN *pp = Predicate_Of_Succ(bb, succ, fall_thru, info); if ( tgt != NULL) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " BB%d target: BB%d ", BB_id(bb), BB_id(succ)); fPrint_TN(TFile, " %s => main \n", pp); } if ( IPFEC_Combine_Exit ) { Is_True(tgt -> Main_Predicate().size() == 1, ("Wrong number of main predicate!\n")); TN *old_main = *(tgt -> Main_Predicate().begin()); tgt -> Add_Aux_Predicate(old_main); tgt -> Del_Main_Predicate(old_main); } tgt -> Add_Main_Predicate(pp); } else { area -> Add_Exit_Target(succ, pp, &_m); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " BB%d target(new): BB%d ", BB_id(bb), BB_id(succ)); fPrint_TN(TFile, " %s => main \n", pp); } } } } } // check whether if-conversion can really reduce the number of // branches. // if exit_num <= inner_br_num , the answer is yes. INT exit_num = 0; INT inner_br_num = 0; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; BOOL all_targets_hidden = TRUE; BOOL has_inner_succ = FALSE; BB* fall_thru = BB_Fall_Thru_Successor(bb); BBLIST *succ_bl; FOR_ALL_BB_SUCCS(bb, succ_bl) { BB* succ = BBLIST_item(succ_bl); if (!Is_BB_Container_Member(bbs, succ) || Regional_Cfg_Node(bb) -> First_Succ() == NULL) { // record its information EXIT_TARGET_INFO *tgt = area -> Exit_Target(succ); BB_PREDICATE_INFO *info = area -> Pred_Assign_Info(bb); TN *pp = Predicate_Of_Succ(bb, succ, fall_thru, info); Is_True(tgt, ("exit must have exit info.!\n")); if ( tgt -> Is_Main_Predicate(pp)) { all_targets_hidden = FALSE; } } else { has_inner_succ = TRUE; } } if (! all_targets_hidden) exit_num ++; if ( has_inner_succ && BB_succs_len(bb) > 1 ) { inner_br_num++; } } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n Area_%d: exit_num : %d vs. br_num : %d\n", area -> Area_Label(), exit_num, inner_br_num); } if ( (exit_num > inner_br_num) && !IPFEC_Force_If_Conv) return FALSE; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, "\n Start to detect parallel compare!\n"); } //step2: find candidates for parallel compares Detect_Para_Comp(area); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, "\n Start to generate parallel compare!\n"); } //step3: generate predicate assignment, including parallel compare Gen_Para_Comp(area); return TRUE; } //***************************************************************************** // Function : Merge_area // Input : // - area : the candicate IF_CONV_AREA // Output : // <none> // Description : // The function is to delete unnecessary branches and merge // the one-exit-one-entry block pair into one basic block. //***************************************************************************** void IF_CONVERTOR::Merge_Area(IF_CONV_AREA *area) { BB_SET *hold_bbs = BB_SET_Create_Empty(PU_BB_Count, &_m); BB_SET *area_bb_set = BB_SET_Create_Empty(PU_BB_Count, &_m); // // Next, we will do the following jobs: // 1. delete all unnecessary branches // 2. add some necessary goto // 3. maintain the profiling information // 4. predicate all blocks in the area // 5. merge blocks // BB_CONTAINER& bbs = area -> Blocks(); BB_CONTAINER::iterator bb_iter; BB *bb; BB *last_bb = NULL; INT exit_num = 0; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; area_bb_set = BB_SET_Union1D(area_bb_set, bb, &_m); BBLIST *succ_bl; FOR_ALL_BB_SUCCS(bb, succ_bl) { BB* succ = BBLIST_item(succ_bl); if (!Is_BB_Container_Member(bbs, succ)) { exit_num++; break; } } last_bb =bb; } INT last_bb_type = 0; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile," -- solving BB%d:\n", BB_id(bb)); } if ( BB_recovery(bb)) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " (recovery bb)"); } continue; } CNTL_DEP *cntl_info = area -> Cntl_Dep_Info(); BB_SET *set = cntl_info -> Cntl_Dep_Parents(bb); Is_True( cntl_info != NULL, ("Can't find cntl_info for BB%d.\n", BB_id(bb))); BB_PREDICATE_INFO *pred_info = area -> Pred_Assign_Info (bb); Is_True( pred_info != NULL, ("Can't find BB_PREDICATE_INFO for BB%d.\n", BB_id(bb))); TN *pred = pred_info -> Predicate(); TN *orig_pred = pred_info -> Orig_Pred()?pred_info -> Orig_Pred():pred; if (IPFEC_Disable_Merge_BB) { Predicate_Block(bb, pred, area_bb_set); continue; } // record the frequency of bb in its corresponding predicate TN if (pred) { float f = BB_freq(bb); hTN_MAPf_Set(frequency_of_predicates, pred, f); } BB_MERGE_TYPE bb_type = Classify_BB(bb, area); BBLIST *bl; BB *pred_bb = NULL; if (bb == area -> Entry_BB()) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " (entry) "); } } else { BOOL has_recovery_pred = false; BBLIST *pred_bl; FOR_ALL_BB_PREDS(bb, pred_bl) { if (BB_recovery(BBLIST_item(pred_bl))) { has_recovery_pred = true; break; } } // get out its predeccessor if ( !has_recovery_pred) { Is_True(BB_preds_len(bb) == 1, ("one bb only has one predecessor during merging!\n")); bl = BB_preds(bb); pred_bb = BBLIST_item(bl); } else { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " => it is successor of recovery bb.\n"); } } } // when a block is solved, it and its predecessor will become straight // line code; but the other successors of its predecessor have // not been solved, so record them in the set 'bb_to_solve' BB_SET* bb_to_solve = BB_SET_Create_Empty(PU_BB_Count, &_m); BB *succ_bb_of_pred; if (pred_bb && BB_succs_len(pred_bb) > 1) { FOR_ALL_BB_SUCCS(pred_bb, bl) { succ_bb_of_pred = BBLIST_item(bl); if (succ_bb_of_pred != bb ) { if (Is_BB_Container_Member(bbs, succ_bb_of_pred)) { bb_to_solve = BB_SET_Union1D(bb_to_solve, succ_bb_of_pred, &_m); } } } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { BB* bb_tmp; fprintf(TFile, " (pred_bb:%d) ", BB_id(pred_bb)); fprintf(TFile, " (bb_to_solve:"); FOR_ALL_BB_SET_members(bb_to_solve, bb_tmp) { fprintf(TFile, " BB%d, ", BB_id(bb_tmp)); } fprintf(TFile, ") "); } } BOOL can_be_merged_into = FALSE; BB *fall_thru = BB_Fall_Thru_Successor(bb); BB *fall_thru_goto = NULL; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { Print_BB_Merge_Type(bb_type, TFile); } switch ( bb_type) { case CASE_ALL_IN_AREA: { // Remove all the branches at the end of the block BB_Remove_Branch(bb); if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb)) { hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m); } can_be_merged_into = TRUE; break; } case CASE_CALL_IN: { break; } case CASE_CALL_OUT: { Is_True(BB_succs_len(bb) == 1, ("here call-inst can only have one succ!\n")); bl = BB_succs(bb); BB* exit_target = BBLIST_item(bl); EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(exit_target); BOOL is_main_exit = tgt_info -> Is_Main_Predicate(orig_pred); tgt_info -> Update_Predicate(orig_pred, pred); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { if ( is_main_exit ) { fprintf(TFile, "\n exit-target(main): BB%d ", BB_id(exit_target)); } else { fprintf(TFile, "\n exit-target(aux): BB%d ", BB_id(exit_target)); } } // there are two situations in which a full_thru_goto need to // be added: // 1) it is a main exit and there are some BBs to be appended // after it // 2) it is a main exit and there are some auxiliary predicates // need to be assigned there if ( is_main_exit && (BB_SET_Size(bb_to_solve) || tgt_info -> Aux_Predicates().size())) { // add a new basic block and insert a goto into it REGIONAL_CFG* cfg = Home_Region(bb) -> Regional_Cfg(); fall_thru = exit_target; fall_thru_goto = RGN_Gen_And_Insert_BB(bb, fall_thru, cfg); Add_Goto_Op(fall_thru_goto, fall_thru); // update the prob of bb and its successors Set_Prob(bb, fall_thru_goto, 1.0); BB_freq(fall_thru_goto) = BB_freq(bb); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " fall-thru-succ: BB%d\n", BB_id(fall_thru)); fprintf(TFile, " gen fall-thru-goto: BB%d.\n", BB_id(fall_thru_goto)); } Make_Branch_Conditional(fall_thru_goto); Predicate_Block(fall_thru_goto, pred, area_bb_set); Move_BB(fall_thru_goto, bb); GRA_LIVE_Compute_Liveness_For_BB(fall_thru_goto); if (tgt_info -> Aux_Predicates().size()){ OP *br = BB_branch_op(fall_thru_goto); // assign auxiliary predicates tgt_info -> Assign_Aux_Predicates(fall_thru_goto, br); } } if (!is_main_exit) { RGN_Unlink_Pred_Succ(bb, exit_target); } break; } case CASE_UNCOND_BR: { Is_True(BB_succs_len(bb) == 1, ("here uncond-br can only have one succ!\n")); bl = BB_succs(bb); BB* exit_target = BBLIST_item(bl); EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(exit_target); BOOL is_main_exit = tgt_info -> Is_Main_Predicate(orig_pred); tgt_info -> Update_Predicate(orig_pred, pred); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { if ( is_main_exit ) { fprintf(TFile, "\n exit-target(main): BB%d ", BB_id(exit_target)); } else { fprintf(TFile, "\n exit-target(aux): BB%d ", BB_id(exit_target)); } } if (BB_SET_Size(set)) { Make_Branch_Conditional(bb); } if ( is_main_exit) { OP* br = BB_branch_op(bb); Is_True(br, ("uncond-br must has a br-op!\n")); tgt_info -> Assign_Aux_Predicates(bb, br); } else { BB_Remove_Branch(bb); if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb)) { hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m); } can_be_merged_into = TRUE; RGN_Unlink_Pred_Succ(bb, exit_target); } break; } case CASE_FALL_OUT: { Is_True(fall_thru, ("fall_thru can not be empty!\n")); EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(fall_thru); BOOL is_main_exit = tgt_info -> Is_Main_Predicate(orig_pred); tgt_info -> Update_Predicate(orig_pred, pred); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { if ( is_main_exit ) { fprintf(TFile, "\n exit-target(main): BB%d \n", BB_id(fall_thru)); } else { fprintf(TFile, "\n exit-target(aux): BB%d \n", BB_id(fall_thru)); } } if ( is_main_exit) { if (tgt_info -> Aux_Predicates().size()) { Add_Goto_Op(bb, fall_thru); Make_Branch_Conditional(bb); OP* br = BB_branch_op(bb); tgt_info -> Assign_Aux_Predicates(bb, br); // update the prob of bb and its fall-thru-succ float pb1 = 1.0; if (pred_bb) { BB *other_succ = NULL; BBLIST *bl; FOR_ALL_BB_SUCCS(bb, bl) { BB *tmp_bb = BBLIST_item(bl); if (tmp_bb != bb) { other_succ = tmp_bb; break; } } if ( other_succ) pb1 = 1.0 - Prob_Local(pred_bb,other_succ); } Set_Prob(bb, fall_thru, pb1); } else { if ( bb != last_bb) { Add_Goto_Op(bb, fall_thru); Make_Branch_Conditional(bb); } } } else { if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb)) { hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m); } can_be_merged_into = TRUE; RGN_Unlink_Pred_Succ(bb, fall_thru); } break; } case CASE_IF_FALL_OUT: { Is_True(fall_thru, ("fall_thru can not be empty!\n")); TN *first_pred = NULL; TN *second_pred = NULL; Find_BB_Predicates(bb, first_pred, second_pred); Is_True(first_pred && second_pred, (" lack of a predicate!\n")); EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(fall_thru); BOOL is_main_exit; OP *br = BB_branch_op(bb); Is_True(br, (" two-successor bb must have br\n")); if (first_pred == OP_opnd(br, OP_PREDICATE_OPND)) { is_main_exit = tgt_info -> Is_Main_Predicate(second_pred); } else { Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND), ("conditional br must have a predicate.\n")); is_main_exit = tgt_info -> Is_Main_Predicate(first_pred); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { if ( is_main_exit ) { fprintf(TFile, "\n exit-target(main): BB%d \n", BB_id(fall_thru)); } else { fprintf(TFile, "\n exit-target(aux): BB%d \n", BB_id(fall_thru)); } } // Invert the branch to make the fall through the one //in the area BB_Remove_Branch(bb); if (is_main_exit) { // add a new goto into it Add_Goto_Op(bb, fall_thru); RGN_Link_Pred_Succ_With_Prob(bb, fall_thru, 1.0); Make_Branch_Conditional(bb); OP* br = BB_branch_op(bb); // update the prob of bb and its fall-thru-succ float pb1 = pred_bb ? Prob_Local(pred_bb, bb):1; float pb2 = Prob_Local(bb, fall_thru); Set_Prob(bb, fall_thru, pb1 * pb2); tgt_info -> Assign_Aux_Predicates(bb, br); } else { if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb)) { hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m); } can_be_merged_into = TRUE; BB* other_succ = BB_Other_Successor(bb, fall_thru); RGN_Unlink_Pred_Succ(bb, other_succ); } break; } case CASE_IF_FALL_IN: { Is_True(fall_thru, ("fall_thru can not be empty!\n")); BB* other_succ = BB_Other_Successor(bb, fall_thru); Is_True(other_succ, ("fall_thru can not be empty!\n")); EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(other_succ); TN *first_pred = NULL; TN *second_pred = NULL; Find_BB_Predicates(bb, first_pred, second_pred); Is_True(first_pred && second_pred, (" lack of a predicate!\n")); BOOL is_main_exit; OP *br = BB_branch_op(bb); Is_True(br, (" two-successor bb must have br\n")); if (first_pred == OP_opnd(br, OP_PREDICATE_OPND)) { is_main_exit = tgt_info -> Is_Main_Predicate(first_pred); } else { Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND), ("conditional br must have a predicate.\n")); is_main_exit = tgt_info -> Is_Main_Predicate(second_pred); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n exit-target"); if ( is_main_exit ) { fprintf(TFile, "(main)"); } else { fprintf(TFile, "(aux)"); } fprintf(TFile,": BB%d ", BB_id(other_succ)); } if (is_main_exit) { OP* br = BB_branch_op(bb); tgt_info -> Assign_Aux_Predicates(bb, br); } else { BB_Remove_Branch(bb); if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb)) { hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m); } can_be_merged_into = TRUE; RGN_Unlink_Pred_Succ(bb, other_succ); // Set_Prob(bb, fall_thru, 1.0); } break; } case CASE_IF_OUT: { Is_True(fall_thru, ("fall_thru can not be empty!\n")); TN *first_pred = NULL; TN *second_pred = NULL; Find_BB_Predicates(bb, first_pred, second_pred); Is_True(first_pred && second_pred, (" lack of a predicate!\n")); BOOL is_main_exit; OP *br = BB_branch_op(bb); Is_True(br, (" two-successor bb must have br\n")); // solving target-successor(non-fall-thru successor) TN *fall_thru_pred = NULL; BB* other_succ = BB_Other_Successor(bb, fall_thru); EXIT_TARGET_INFO* tgt_info = area -> Exit_Target(other_succ); if (first_pred == OP_opnd(br, OP_PREDICATE_OPND)) { is_main_exit = tgt_info -> Is_Main_Predicate(first_pred); fall_thru_pred = second_pred; } else { Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND), ("conditional br must have a predicate.\n")); is_main_exit = tgt_info -> Is_Main_Predicate(second_pred); fall_thru_pred = first_pred; } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n exit-target"); if ( is_main_exit ) { fprintf(TFile, "(main)"); } else { fprintf(TFile, "(aux)"); } fprintf(TFile,": BB%d ", BB_id(other_succ)); } BOOL need_add_fall_thru = TRUE; if ( is_main_exit ) { OP* br = BB_branch_op(bb); tgt_info -> Assign_Aux_Predicates(bb, br); } else { BB_Remove_Branch(bb); RGN_Unlink_Pred_Succ(bb, other_succ); need_add_fall_thru = FALSE; } // solving fall through successor tgt_info = area -> Exit_Target(fall_thru); if (first_pred == OP_opnd(br, OP_PREDICATE_OPND)) { is_main_exit = tgt_info -> Is_Main_Predicate(second_pred); } else { Is_True(second_pred == OP_opnd(br, OP_PREDICATE_OPND), ("conditional br must have a predicate.\n")); is_main_exit = tgt_info -> Is_Main_Predicate(first_pred); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n exit-target"); if ( is_main_exit ) { fprintf(TFile, "(main)"); } else { fprintf(TFile, "(aux)"); } fprintf(TFile,": BB%d ", BB_id(fall_thru)); } // Need to insert a fall-through goto, then conditionalize // it with the inverse conditional br = NULL; if ( is_main_exit) { if ( need_add_fall_thru && (tgt_info -> Aux_Predicates().size() || bb != last_bb)) { // add a new basic block and insert a goto into it REGIONAL_CFG* cfg = BB_SET_Size(bb_to_solve) ? Home_Region(bb) -> Regional_Cfg(): NULL; fall_thru_goto = RGN_Gen_And_Insert_BB(bb, fall_thru, cfg); Add_Goto_Op(fall_thru_goto, fall_thru); if (fall_thru_pred && fall_thru_pred != True_TN) { Make_Branch_Conditional(fall_thru_goto); Predicate_Block(fall_thru_goto, fall_thru_pred, area_bb_set); } // assign auxiliary predicates br = BB_branch_op(fall_thru_goto); tgt_info -> Assign_Aux_Predicates(fall_thru_goto, br); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " fall-thru-succ: BB%d\n", BB_id(fall_thru)); fprintf(TFile, " gen fall-thru-goto: BB%d.\n", BB_id(fall_thru_goto)); } Move_BB(fall_thru_goto, bb); GRA_LIVE_Compute_Liveness_For_BB(fall_thru_goto); float pb1 = Prob_Local(pred_bb, bb); float pb2 = Prob_Local(bb, other_succ); Set_Prob(bb, other_succ, pb1 * pb2); Set_Prob(bb, fall_thru_goto, 1 - pb1 * pb2); BB_freq(fall_thru_goto) = BB_freq(pred_bb) * (1 -pb1 * pb2); } else if (bb != last_bb || tgt_info -> Aux_Predicates().size()) { Add_Goto_Op(bb, fall_thru); Make_Branch_Conditional(bb); br = BB_branch_op(bb); if (fall_thru_pred && fall_thru_pred != True_TN) { Set_OP_opnd(br, OP_PREDICATE_OPND, fall_thru_pred); } // assign auxiliary predicates tgt_info -> Assign_Aux_Predicates(bb, br); } } else { RGN_Unlink_Pred_Succ(bb, fall_thru); } if (!need_add_fall_thru && !br) { if(!pred_bb || !BB_SET_MemberP(hold_bbs, pred_bb)) { hold_bbs = BB_SET_Union1D(hold_bbs, bb, &_m); } can_be_merged_into = TRUE; } break; } case CASE_CHECK_IN: case CASE_CHECK_OUT: { break; } default: Is_True(0,("Unknown block classification")); } // predicate the current basic block Predicate_Block(bb, pred, area_bb_set); // merge it into its predecessor // judge if it can be merged into its predecessor if (pred_bb && BB_SET_MemberP(hold_bbs, pred_bb)) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " => merged.\n"); } if (pred) { if (!pred_info -> Eqv_Class_Head() && pred_info -> Eqv_Class_Head_BB() != pred_bb) { Set_TN_is_global_reg(pred); Set_BB_has_globals(bb); Set_BB_has_globals(pred_info -> Eqv_Class_Head_BB()); } else if (pred_info -> Has_Start_Node()) { BB* st_n = pred_info -> Start_Node(BB_SET_Choose(set)); if (st_n != pred_bb) { Set_TN_is_global_reg(pred); Set_BB_has_globals(bb); Set_BB_has_globals(st_n); } } } BB *succ_of_goto = NULL; if (fall_thru_goto) { Is_True(BB_succs_len(fall_thru_goto) == 1, ("here fall-thru-goto can only have one succ!\n")); bl = BB_succs(fall_thru_goto); succ_of_goto = BBLIST_item(bl); } FOR_ALL_BB_SET_members(bb_to_solve, succ_bb_of_pred) { if (fall_thru_goto) { // add succ_bb_of_pred as the fall-thru-successor of // fall_thru_goto float pb = Prob_Local(pred_bb, succ_bb_of_pred); RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred); RGN_Link_Pred_Succ_With_Prob(fall_thru_goto, succ_bb_of_pred, pb); Set_Fall_Thru(fall_thru_goto, succ_bb_of_pred); Set_Prob(fall_thru_goto, succ_of_goto, 1 - pb); } else { // add succ_bb_of_pred as a successor of bb float pb = Prob_Local(pred_bb, succ_bb_of_pred); RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred); RGN_Link_Pred_Succ_With_Prob(bb, succ_bb_of_pred, pb); } } if ( BB_call(bb) ) { BB_Transfer_Callinfo( bb, pred_bb); } Merge_Blocks(pred_bb, bb); if (!can_be_merged_into) { BB_SET_Difference1D(hold_bbs, pred_bb); } }else if (pred_bb){ if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " => appended .\n"); } // maintain localization information of registers if (pred && (!pred_info -> Eqv_Class_Head()|| pred_info -> Has_Start_Node())) { Set_TN_is_global_reg(pred); Set_BB_has_globals(bb); if (!pred_info -> Eqv_Class_Head()) Set_BB_has_globals(pred_info -> Eqv_Class_Head_BB()); } if ( BB_SET_Size(bb_to_solve) ) { BB *succ_of_goto = NULL; if (fall_thru_goto) { Is_True(BB_succs_len(fall_thru_goto) == 1, ("here fall-thru-goto can only have one succ!\n")); bl = BB_succs(fall_thru_goto); succ_of_goto = BBLIST_item(bl); } FOR_ALL_BB_SET_members(bb_to_solve, succ_bb_of_pred) { if (fall_thru_goto) { // add succ_bb_of_pred as the fall-thru-successor of // fall_thru_goto float pb = Prob_Local(pred_bb, succ_bb_of_pred); RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred); RGN_Link_Pred_Succ_With_Prob(fall_thru_goto, succ_bb_of_pred, pb); Set_Fall_Thru(fall_thru_goto, succ_bb_of_pred); Set_Prob(fall_thru_goto, succ_of_goto, 1 - pb); } else { // add succ_bb_of_pred as a successor of bb float pb = Prob_Local(pred_bb, succ_bb_of_pred); RGN_Unlink_Pred_Succ(pred_bb, succ_bb_of_pred); RGN_Link_Pred_Succ_With_Prob(bb, succ_bb_of_pred, pb); } } } if (last_bb_type == CASE_CALL_OUT) { Set_Fall_Thru(pred_bb, bb); } float out_pb = 0.0; // update fall thru successor if (pred_bb && BB_succs_len(pred_bb) > 1) { Is_True(BB_succs_len(pred_bb) == 2, ("a bb can not have more than 2 succs!\n")); // for a bb, one succ is out of the area, the other succ(bb) // should be fall-thru-succ FOR_ALL_BB_SUCCS(pred_bb, bl) { succ_bb_of_pred = BBLIST_item(bl); if (succ_bb_of_pred != bb && !Is_BB_Container_Member(bbs, succ_bb_of_pred)) { out_pb = Prob_Local(pred_bb, succ_bb_of_pred); Set_Fall_Thru(pred_bb, bb); } } } // maintain frequency information BB_freq(bb) = BB_freq(pred_bb) * ( 1- out_pb); Set_Prob(pred_bb, bb, 1.0 - out_pb); } else { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n"); } } last_bb_type = bb_type; } // get rid of useless 'br'. Sometime, after if-conversion, a bb with // a conditional 'br' will only has one successor. In this case, the // 'br' should be deleted. for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; OP *br = BB_branch_op(bb); if ( !br ) continue; if ( OP_cond(br) && BB_succs_len(bb) == 1 ) { BB *fall_thru = BB_Fall_Thru_Successor(bb); if ( fall_thru && fall_thru == BB_next(bb) && OP_bb(br) ) { BB_Remove_Op(bb, br); } else if (!fall_thru ) { //OSP_265 //Here means the branch will always be taken. //Instead of using True_TN as predicate, we just revert br.cond back to br. //CGTARG_Predicate_OP(bb, br, True_TN); TOP new_top; switch (OP_code(br)) { case TOP_br_cond: new_top = TOP_br; break; case TOP_br_r_cond: new_top = TOP_br_r; break; default: FmtAssert(0, ("Weird branch instruction!")); break; } OP* new_br = Mk_OP(new_top, Gen_Enum_TN(ECV_ph_few), Gen_Enum_TN(ECV_dh), OP_opnd(br,4)); OP_srcpos(new_br) = OP_srcpos(br); BB_Insert_Op_After(bb, br, new_br); BB_Remove_Op(bb, br); } } } } BB_MERGE_TYPE IF_CONVERTOR::Classify_BB(BB *bb, IF_CONV_AREA *area) { BB_MERGE_TYPE result; BB *entry = area -> Entry_BB(); BB *fall_thru; BB *other_succ; fall_thru = BB_Fall_Thru_Successor(bb); other_succ = NULL; BBLIST *bl; FOR_ALL_BB_SUCCS(bb, bl) { other_succ = BBLIST_item(bl); if (other_succ != fall_thru) break; } // check for easy case, to see if all succs are in the area BOOL fall_thru_out = false; BOOL other_out = false; BB_CONTAINER& bbs_1 = area -> Blocks(); if (fall_thru && (!Is_BB_Container_Member(bbs_1, fall_thru) ||fall_thru == entry)) { fall_thru_out = TRUE; } if (other_succ && (!Is_BB_Container_Member(bbs_1, other_succ) || other_succ == entry)) { other_out = TRUE; } if (!other_out && !fall_thru_out) { if (BB_exit(bb) || BB_call(bb)) { result = CASE_CALL_IN; } else if (BB_chk_op(bb)) { result = CASE_CHECK_IN; } else { result = CASE_ALL_IN_AREA; } return result; } // In the case, at least one block is out of the area. if (BB_exit(bb) || BB_call(bb)) { result = CASE_CALL_OUT; return result; } if (BB_chk_op(bb)) { result = CASE_CHECK_OUT; return result; } OP *br = BB_branch_op(bb); if (!br) { // No branch, just fall_thru. result = CASE_FALL_OUT; return result; } if (!OP_cond(br)) { // Unconditional branch result = CASE_UNCOND_BR; return result; } if (fall_thru_out && other_out) { result = CASE_IF_OUT; } else if (fall_thru_out && !other_out) { result = CASE_IF_FALL_OUT; } else { result = CASE_IF_FALL_IN; } return result; } void IF_CONVERTOR::Set_Fall_Thru(BB* bb, BB* fall_thru) { BB* before_bb = bb; while (fall_thru) { BB* next = BB_next(fall_thru); // if the target of the branch of 'fall_thru' is the fall_thru_bb // of 'fall_thru', stop iteration. BOOL stop_iter = FALSE; OP *br_op = BB_branch_op(fall_thru); if (next && br_op) { INT tfirst, tcount; CGTARG_Branch_Info(br_op, &tfirst, &tcount); if (tcount != 0) { TN *dest = OP_opnd(br_op, tfirst); Is_True(tcount == 1, ("%d branch targets, expected 1", tcount)); Is_True(TN_is_label(dest), ("expected label")); if (Is_Label_For_BB(TN_label(dest), next)) { stop_iter = TRUE; } } } if (stop_iter || next != BB_Fall_Thru_Successor(fall_thru)) { next = NULL; } Move_BB(fall_thru, before_bb); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n => move BB:%d after BB:%d\n", BB_id(fall_thru), BB_id(before_bb)); } before_bb = fall_thru; fall_thru = next; } } void IF_CONVERTOR::Merge_Blocks(BB *bb_first, BB *bb_second) { // step 0: maintain fall-thrugh-information BOOL need_maintain = TRUE; OP *br_op = BB_branch_op(bb_second); BB* next = BB_next(bb_second); if (next && br_op) { INT tfirst, tcount; CGTARG_Branch_Info(br_op, &tfirst, &tcount); if (tcount != 0) { TN *dest = OP_opnd(br_op, tfirst); Is_True(tcount == 1, ("%d branch targets, expected 1", tcount)); Is_True(TN_is_label(dest), ("expected label")); if (Is_Label_For_BB(TN_label(dest), next)) { need_maintain = FALSE; } } } if ( need_maintain && bb_second != BB_next(bb_first)) { BB* fall_thru = BB_Fall_Thru_Successor(bb_second); Set_Fall_Thru(bb_first, fall_thru); } // step1: Move all ops of bb_second to bb_first. OP *op; OP *op_next; OP *last = BB_last_op(bb_first); for (op = BB_first_op(bb_second); op; op = op_next) { op_next = OP_next(op); if (last) { BB_Move_Op(bb_first, last, bb_second, op, FALSE); } else { BB_Append_Op (bb_first, op); } last = op; } // step2: Clean up the first pred-succ list RGN_Unlink_Pred_Succ(bb_first, bb_second); // step3: move bb_second's successor arcs to bb_first. BB *succ; BBLIST *bl; while (bl = BB_succs(bb_second)) { succ = BBLIST_item(bl); float pb = Prob_Local(bb_second, succ); RGN_Unlink_Pred_Succ(bb_second, succ); RGN_Link_Pred_Succ_With_Prob(bb_first, succ, pb); } //step4: take bb_second out of the list. RGN_Remove_BB_And_Edges(bb_second); // step5: maintain the call and exit infomation // If bb_second is an exit, move the relevant info to the // merged block. if (BB_exit(bb_second)) { BB_Transfer_Exitinfo(bb_second, bb_first); Exit_BB_Head = BB_LIST_Delete(bb_second, Exit_BB_Head); Exit_BB_Head = BB_LIST_Push(bb_first, Exit_BB_Head, &MEM_pu_pool); } // Transfer call info if merged block will now contain a call. if (BB_call(bb_second)) { BB_Copy_Annotations(bb_first, bb_second, ANNOT_CALLINFO); } } //***************************************************************************** // Function : Convert_Candidates // Input : // - areas : a list of IF_CONV_AREAs. On them, there are obvious flags to // indicate if the IF_CONV_AREA should be if-converted. // Output : // <none> // Description : // apply if-conversion on the selected candidates to predicated code. // //***************************************************************************** BOOL IF_CONVERTOR::Convert_Candidates(AREA_CONTAINER& areas) { AREA_CONTAINER:: iterator iter; BOOL converted = FALSE; for ( iter = areas.begin(); iter != areas.end(); iter++) { IF_CONV_AREA* area = *iter; BB_CONTAINER& bbs = area -> Blocks(); if (IPFEC_Query_Skiplist(if_conv_skip_area, area -> Area_Label())) continue; if ( area -> Conv_Type() != FULLY_IF_CONV) continue; converted = TRUE; char if_conversion_key[6] = ""; char input_string[100] = ""; char output_string[60] = ""; if (Get_Trace(TP_PTRACE1, TP_PTRACE1_CG)) { BB_CONTAINER::iterator bb_iter; BB *bb; sprintf(if_conversion_key, "%d", area -> Area_Label()); for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; char tmp_string[6]; sprintf(tmp_string, "%d", BB_id(bb)); strcat(input_string, tmp_string); strcat(input_string, "||"); } } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, "\n IF_CONV_AREA %d:\n", area -> Area_Label()); } // caculate control dependence and initialize the predicate info area -> Init_Conversion_Info(&_m); if ( !Insert_Predicate(area)) { if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n too many exits, give up!!\n"); } continue; } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, "\n Start to merge basic blocks!\n"); } Merge_Area(area); if (Get_Trace(TP_PTRACE1, TP_PTRACE1_CG)) { BB_CONTAINER& bbs = area -> Blocks(); BB_CONTAINER::iterator bb_iter; BB *bb; sprintf(if_conversion_key, "%d", area -> Area_Label()); for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb = *bb_iter; if (Regional_Cfg_Node(bb)) { char tmp_string[6]; sprintf(tmp_string, "%d", BB_id(bb)); strcat(output_string, tmp_string); strcat(output_string, "||"); } } Generate_Tlog("AIC", "if_conversion", (SRCPOS)0, if_conversion_key, input_string, output_string, ""); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, "\n after merging basic blocks:\n"); area -> Print_IR(TFile); } } return converted; } //***************************************************************************** // Function : If_Conversion // Input : // - region_tree : a region tree // Output : // < none > // Description : // the driver of if-conversion phase //***************************************************************************** IF_CONVERTOR::IF_CONVERTOR(REGION_TREE *region_tree) { Start_Timer(T_Ipfec_If_Conv_CU); //trace before IF_CONV if (Get_Trace(TKIND_IR, TP_A_IFCONV, REGION_First_BB)) Trace_IR(TP_A_IFCONV, "IF_CONV", NULL, FALSE); if (!frequency_of_predicates) { frequency_of_predicates = hTN_MAPf_Create(&(info_mem._m)); } if (!init_op_info) { init_op_info = hTN_MAP_Create(&(info_mem._m)); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC)) { draw_global_cfg(); } BOOL changed = TRUE; for (INNERMOST_REGION_FIRST_ITER iter(region_tree); iter != 0; ++iter) { REGION* region = *iter; if (IPFEC_Query_Skiplist(if_conv_skip_rgn, region -> Id(), Current_PU_Count())) continue; if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC)) { draw_regional_cfg(region); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " \nIF CONVERSION -- region %d\n", region -> Id()); } if ( Is_In_Infinite_Loop(region) ) continue; if (Is_In_Abnormal_Loop(region)) continue; if (region->Region_Type () == IMPROPER) continue; // Calculate_Dominators is time comsumption, only recalculate // when the cfg changed if( changed ) Calculate_Dominators(); // do something to initialize IF_CONV_ALLOC temp_alloc(&_m); AREA_CONTAINER areas(temp_alloc); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " \n Start to initialize!\n"); } If_Conversion_Init(region,areas); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " IF_CONV_AREAs after initialization:\n\n"); Print_All_Areas(areas, TFile); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " \n Start to select proper areas!\n"); } // select the if-conversion candidates Select_Candidates(areas); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " IF_CONV_AREAs after selection:\n\n"); Print_All_Areas(areas, TFile); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " \n Start to convert candidates!\n"); } //convert the if-conversion candidates to predicated code changed = Convert_Candidates(areas); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC)) { draw_regional_cfg(region); } CXX_DELETE(&areas, &_m); if( changed ) Free_Dominators_Memory(); } if(!changed) Free_Dominators_Memory(); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC)) { draw_global_cfg(); } //trace after IF_CONV if (Get_Trace(TKIND_IR, TP_A_IFCONV, REGION_First_BB)) Trace_IR(TP_A_IFCONV, "IF_CONV", NULL); Stop_Timer(T_Ipfec_If_Conv_CU); } IF_CONVERTOR::IF_CONVERTOR() { if (!frequency_of_predicates) { frequency_of_predicates = hTN_MAPf_Create(&(info_mem._m)); } if (!init_op_info) { init_op_info = hTN_MAP_Create(&(info_mem._m)); } _loop_length = 0; } //***************************************************************************** // Function : Force_If_Conversion // Input : // - loop : a descriptor of a loop. here, we assume the loop is a SEME and // innermost loop. // - allow_muti_bb : a boolean value to indicate if multiple bb in a loop is // allowed // Output : // - a basic block : If allow_multi_bb, it will always be converted if // possible. If not possible, return NULL. // Description : // in swp phase, a loop without control flow in it is suitable to apply // swp. It is a driver to if-convert a loop body //***************************************************************************** BB * IF_CONVERTOR::Force_If_Convert(LOOP_DESCR *loop, BOOL allow_multi_bb) { BB *bb_entry = LOOP_DESCR_loophead(loop); // possible quick exit if there is already only one block in the region if (BB_SET_Size(LOOP_DESCR_bbset(loop)) == 1) { return bb_entry; } // check if it is safe to if-convert the loop IF_CONV_ALLOC temp_alloc(&_m); AREA_CONTAINER areas(temp_alloc); REGION* region = Home_Region(bb_entry); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_GRAPHIC)) { draw_regional_cfg(region); } if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " ======start to force_if_convert\n\n"); } if ( Is_In_Infinite_Loop(region) ) { return NULL; } If_Conversion_Init(region,areas); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " IF_CONV_AREAs after initialization:\n\n"); Print_All_Areas(areas, TFile); } // check if it can be merged into one basic block BOOL is_legal = Can_Merge_Into_One_Area(areas); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " is_legal: %d\n", (int)is_legal); } if (!is_legal) { return NULL; } // When relaxed if conversion is used, we don't blindly merge all areas to // one singel area and apply if conversion. Instead we use a similar approch // as the normal if conversion does, but the heuristics to calculate the // profitability is more relaxed because we might gain additional performance // through SWP. if (IPFEC_Relaxed_If_Conv) { if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf(TFile, " ======use relaxed_if_conv\n\n"); } // Calculate a rough estimate of the critical path of the loop INT32 loop_length1, loop_length2; loop_length1 = Calculate_Loop_Critical_Length (areas[0]); loop_length2 = Calculate_Loop_Cycled_Critical_Length (areas[0]); _loop_length = loop_length1 > loop_length2 ? loop_length1 : loop_length2; if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf (TFile, " Loop Length: %i\n", _loop_length); } Select_Candidates (areas, /*forced=*/TRUE); if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf (TFile, " IF_CONV_AREAs after selection:\n\n"); Print_All_Areas (areas, TFile); } // Check if the loop has been reduced to one area. // If not we will not If Convert the loop if (areas.size()!=1) { return NULL; } } else { // merge all areas AREA_CONTAINER::iterator area_iter; area_iter = areas.begin(); IF_CONV_AREA *head_area = *area_iter; area_iter++; for (; area_iter != areas.end(); area_iter++) { head_area -> Combine_Blocks_With (*area_iter, &_m); } // We can now delete all areas except the first one, // because all the other areas have been merged into // the first area areas.erase (areas.begin()+1,areas.end()); head_area -> Conv_Type(FULLY_IF_CONV); } BOOL can_one_bb = Can_Merge_Into_One_BB (*(areas.begin())); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf (TFile, " can_one_bb: %d\n", (int) can_one_bb); } // Do the if-conversion if (can_one_bb || allow_multi_bb) { if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_SUMMARY)) { fprintf (TFile, " \n Start to convert candidates!\n"); } Convert_Candidates(areas); // Update the loop descriptor BB* fall_thru_bb = NULL; BB* bb; IF_CONV_AREA* area = *(areas.begin()); BB_CONTAINER del_blks(&_m); BB_CONTAINER::iterator bb_iter; for (bb_iter = area -> Blocks().begin(); bb_iter != area -> Blocks().end(); bb_iter++) { bb = *bb_iter; REGIONAL_CFG_NODE* node = Regional_Cfg_Node(bb); REGION* home_region = node ? node -> Home_Region() : NULL; // home_region == NULL means the bb has been deleted if (!home_region) { // get rid of all the old blocks from the loop descriptors // Due to some bugs, when BB set in LOOP_DESCR is changed, // the "delete" operations should be performed after "add" // is done. // LOOP_DESCR_Delete_BB(loop, bb); del_blks.push_back (bb); } else if (home_region != region) { FmtAssert (fall_thru_bb == NULL, (" can only have one fall_thru_bb\n")); fall_thru_bb = bb; // Add the fall_thru_block to the loop descriptors // for all the enclosing loops LOOP_DESCR *enc_loop = LOOP_DESCR_Next_Enclosing_Loop(loop); if (enc_loop) { LOOP_DESCR_Add_BB (enc_loop, fall_thru_bb); } } } for (BB_CONTAINER::iterator iter = del_blks.begin(); iter != del_blks.end (); iter++) { LOOP_DESCR_Delete_BB (loop, *iter); } BB* single_bb = NULL; if (can_one_bb) { FmtAssert (areas.size() ==1, (" loop should be shrinked to one bb")); IF_CONV_AREA* area = *(areas.begin()); if (BB_SET_Size(LOOP_DESCR_bbset(loop)) == 1) { single_bb = area -> Entry_BB(); } } if (Get_Trace (TP_A_IFCONV, TT_IF_CONV_GRAPHIC)) { draw_regional_cfg(region); } return single_bb; } return NULL; } BOOL IF_CONVERTOR::Can_Merge_Into_One_Area(AREA_CONTAINER& areas) { INT break_num = 0; AREA_CONTAINER::iterator iter; for ( iter = areas.begin(); iter != areas.end(); iter++) { IF_CONV_AREA* area = *iter; if (area -> Area_Type() == UNSUITABLE) { return false; } if (area -> Area_Type() == UPWARD_UNSUITABLE && area -> Pred_Num()) { return false; } if (area -> Area_Type() == DOWNWARD_UNSUITABLE && area -> Succ_Num()) { return false; } } return true; } BOOL IF_CONVERTOR::Can_Merge_Into_One_BB(IF_CONV_AREA* area) { BB_CONTAINER& bbs = area -> Blocks(); BB_CONTAINER::iterator bb_iter; BB *bb; BOOL break_num = FALSE; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { bb =*bb_iter; BB_MERGE_TYPE merge_type = Classify_BB(bb, area); if (Get_Trace(TP_A_IFCONV, TT_IF_CONV_DETAILED)) { fprintf(TFile, " => BB_%d is",BB_id(bb)); Print_BB_Merge_Type(merge_type,TFile); fprintf(TFile,"type.\n"); } switch ( merge_type) { case CASE_ALL_IN_AREA: { break; } case CASE_CALL_IN: case CASE_IF_FALL_OUT: case CASE_IF_FALL_IN: case CASE_CHECK_IN: { return false; } case CASE_CALL_OUT: case CASE_UNCOND_BR: case CASE_FALL_OUT: case CASE_IF_OUT: case CASE_CHECK_OUT: { if (!break_num) { break_num= TRUE; break; } else return false; } default: Is_True(0,("Unknown block classification")); } } return true; } //============================================================================= // Print functions //============================================================================= void IF_CONVERTOR::Print_BB_Merge_Type(BB_MERGE_TYPE merge_type,FILE* file) { switch ( merge_type) { case CASE_ALL_IN_AREA: { fprintf(file, "CASE_ALL_IN_AREA"); break; } case CASE_CALL_IN: { fprintf(file, "CASE_CALL_IN"); break; } case CASE_CALL_OUT: { fprintf(file, "CASE_CALL_OUT"); break; } case CASE_UNCOND_BR: { fprintf(file, "CASE_UNCOND_BR"); break; } case CASE_FALL_OUT: { fprintf(file, "CASE_FALL_OUT"); break; } case CASE_IF_FALL_OUT: { fprintf(file, "CASE_IF_FALL_OUT"); break; } case CASE_IF_FALL_IN: { fprintf(file, "CASE_IF_FALL_IN"); break; } case CASE_IF_OUT: { fprintf(file, "CASE_IF_OUT"); break; } case CASE_CHECK_IN: { fprintf(file, "CASE_CHECK_IN"); break; } case CASE_CHECK_OUT: { fprintf(file, "CASE_CHECK_OUT"); break; } default: { Is_True(0,("Unknown block classification")); } } } void IF_CONVERTOR::Print_All_Areas(AREA_CONTAINER& areas, FILE* file) { AREA_CONTAINER::iterator iter; for (iter = areas.begin(); iter != areas.end(); iter++) { IF_CONV_AREA* area = *iter; area -> Print(TFile); } } // This function calculates a rough estimate of the loop critical path INT32 IF_CONVERTOR::Calculate_Loop_Critical_Length (IF_CONV_AREA* area) { INT32 critical_length = 0; INT32 length1, length2; AREA_CONTAINER::iterator area_succs; FmtAssert(area!=NULL, ("Parameter area is NULL pointer!")); critical_length += area->Critical_Len (); area_succs = area->Succ_Set().begin(); switch (area->Succ_Num ()) { case 0: break; case 1: critical_length += Calculate_Loop_Critical_Length (*area_succs); break; case 2: length1 = Calculate_Loop_Critical_Length (*area_succs); area_succs++; length2 = Calculate_Loop_Critical_Length (*area_succs); if (length1 > length2 ) { critical_length += length1; } else { critical_length += length2; } break; default: FmtAssert (0, ("Unexpected number of successors!")); break; } return critical_length; } // This function calculates a rough estimate of the loop critical path under // the assumption that one instruction takes one cycle INT32 IF_CONVERTOR::Calculate_Loop_Cycled_Critical_Length (IF_CONV_AREA* area) { INT32 cycled_critical_length = 0; INT32 length1, length2; AREA_CONTAINER::iterator area_succs; FmtAssert(area!=NULL, ("Parameter area is NULL pointer!")); cycled_critical_length += area->Cycled_Critical_Len (); area_succs = area->Succ_Set().begin(); switch (area->Succ_Num ()) { case 0: break; case 1: cycled_critical_length += Calculate_Loop_Cycled_Critical_Length (*area_succs); break; case 2: length1 = Calculate_Loop_Cycled_Critical_Length (*area_succs); area_succs++; length2 = Calculate_Loop_Cycled_Critical_Length (*area_succs); if (length1 > length2 ) { cycled_critical_length += length1; } else { cycled_critical_length += length2; } break; default: FmtAssert (0, ("Unexpected number of successors!")); break; } return cycled_critical_length; } void IF_CONV_AREA::Print(FILE* file) { fprintf(file, "\nIF_CONV_AREA_%d: (", Area_Label()); fprintf(file, " suitable type : "); switch (_if_suitable) { case UPWARD_UNSUITABLE: { fprintf(file, " UPWARD_UNSUITABLE; "); break; } case DOWNWARD_UNSUITABLE: { fprintf(file, " DOWNWARD_UNSUITABLE; "); break; } case UNSUITABLE: { fprintf(file, " UNSUITABLE; "); break; } case SUITABLE_FOR_IF_CONV: { fprintf(file, " SUITABLE_FOR_IF_CONV; "); break; } default: { Is_True(0, (" Illegal AREA_TYPE.\n")); } } fprintf(file, " if-conv type : "); switch (_need_if_convert ) { case NO_IF_CONV: { fprintf(file, " NO_IF_CONV;"); break; } case PARTIAL_IF_CONV: { fprintf(file, " PARTIAL_IF_CONV;"); break; } case FULLY_IF_CONV: { fprintf(file, " FULLY_IF_CONV;"); break; } default: { Is_True(0, (" Illegal IF_CONV_TYPE.\n")); } } fprintf(file, " length(cycled): %d; ",_cycled_critical_length); fprintf(file, " length : %d ", _critical_length); fprintf(file,")\n -- included blocks : "); BB_CONTAINER& bbs = _included_blocks; BB_CONTAINER::iterator bb_iter; BB *block; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { block = *bb_iter; fprintf(file,"BB%d, ", block -> id); } fprintf(file,"\n"); AREA_CONTAINER::iterator iter; fprintf(file, " -- predecessors : "); for ( iter = _predecessors.begin(); iter!=_predecessors.end(); iter++) { IF_CONV_AREA* pred = *iter; fprintf(file,"AREA_%d, ", pred->Area_Label()); } fprintf(file, "\n -- successors : "); for ( iter = _successors.begin(); iter!= _successors.end(); iter++) { IF_CONV_AREA* succ = *iter; fprintf(file,"AREA_%d, ", succ->Area_Label()); } fprintf(file, "\n"); if (_control_deps) { Is_True(_pred_assign_info, (" _pred_true_edges must be initialized!")); _control_deps -> Print(file); fprintf(file, " -- more detailed information for each bb : \n"); BB_CONTAINER::iterator bb_iter; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { block = *bb_iter; BB_SET *set; BB *bb; BB_PREDICATE_INFO *info; fprintf(file, " \n** BB%d : ", BB_id(block)); info = (BB_PREDICATE_INFO*)BB_MAP_Get( _pred_assign_info, block); fPrint_TN(file, " predicate: %s ; ", info -> Predicate()); fprintf(file, " transitional: %c ;", info -> Transitional()?'y':'n'); fPrint_TN(file, " true pred: %s ;", info -> True_TN()); fPrint_TN(file, " false pred: %s\n", info -> False_TN()); TN_CONTAINER::iterator iter; TN_CONTAINER tn_set; fprintf(file," # or preds:"); tn_set = info ->Or_TNs(); for (iter = tn_set.begin(); iter != tn_set.end(); iter++) { fPrint_TN(file, " %s,", *iter); } fprintf(file," # orcm preds:"); tn_set = info -> Orcm_TNs(); for (iter = tn_set.begin(); iter != tn_set.end(); iter++) { fPrint_TN(file, " %s,", *iter); } fprintf(file," # and preds:\n"); tn_set = info -> And_TNs(); for (iter = tn_set.begin(); iter != tn_set.end(); iter++) { fPrint_TN(file, " %s,", *iter); } fprintf(file," # andcm preds:"); tn_set = info -> Andcm_TNs(); for (iter = tn_set.begin(); iter != tn_set.end(); iter++) { fPrint_TN(file, " %s,", *iter); } fprintf(file, "\n"); if ( !info -> Has_Start_Node()) continue; fprintf(file, " # starting nodes for each control dependentor:\n"); BB_SET* cds = _control_deps -> Cntl_Dep_Parents(block); BB* cd; FOR_ALL_BB_SET_members(cds, cd) { BB* sn = info -> Start_Node(cd); if (sn) { fprintf(file, " BB%d ==> BB%d ; ", BB_id(cd), BB_id(sn)); } } fprintf(file, "\n"); } } } void IF_CONV_AREA::Print_IR(FILE *file) { fprintf(file, "\nIF_CONV_AREA_%d:========================\n", Area_Label()); BB_CONTAINER& bbs = _included_blocks; BB_CONTAINER::iterator bb_iter; BB *block; for (bb_iter = bbs.begin(); bb_iter != bbs.end(); bb_iter++) { block = *bb_iter; Print_BB (block); } fprintf(file,"\n"); } void CNTL_DEP::Print(FILE* file) { BB *block; fprintf(file, "\n -- control dependence information \n"); FOR_ALL_BB_SET_members(_bb_set, block) { BB_SET *set; BB *bb; fprintf(file, " ** BB_%d: cds : ", block -> id); set = (BB_SET*)BB_MAP_Get(_control_dependences, block); FOR_ALL_BB_SET_members(set, bb) { fprintf(file, " BB%d, ", BB_id(bb)); } fprintf(file, " true edges : "); set = (BB_SET*)BB_MAP_Get(_true_edges, block); FOR_ALL_BB_SET_members(set, bb) { fprintf(file, " BB%d, ", BB_id(bb)); } fprintf(file, "\n"); } }
33.104826
99
0.510645
sharugupta
bd6524839e12c4e2cc16bde087bafa0a111ebec1
6,323
cpp
C++
src/breakid.cpp
meelgroup/breakid
dfa763d2e9e39e89a1b1606217e5d54d998ecd17
[ "MIT" ]
1
2021-05-03T08:22:42.000Z
2021-05-03T08:22:42.000Z
src/breakid.cpp
meelgroup/breakid
dfa763d2e9e39e89a1b1606217e5d54d998ecd17
[ "MIT" ]
null
null
null
src/breakid.cpp
meelgroup/breakid
dfa763d2e9e39e89a1b1606217e5d54d998ecd17
[ "MIT" ]
null
null
null
/****************************************** Copyright (c) 2019 Jo Devriendt - KU Leuven 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 "breakid.hpp" #include "Breaking.hpp" #include "Theory.hpp" #include "Graph.hpp" #include "config.hpp" #include "breakid/solvertypesmini.hpp" #include "GitSHA1.h" #include <cstdlib> #include <fstream> #include <iterator> #include <sstream> #include <iostream> using std::cout; using std::endl; using std::string; using std::ofstream; using std::stringstream; using std::istringstream; using std::make_shared; using std::vector; using namespace BID; struct BID::PrivateData { vector<Group*> subgroups; uint32_t totalNbMatrices = 0; uint32_t totalNbRowSwaps = 0; OnlCNF* theory = NULL; Breaker* brkr = NULL; Config* conf = NULL; ~PrivateData() { for(auto& sg: subgroups) { delete sg; } subgroups.clear(); delete theory; delete conf; delete brkr; } }; BreakID::~BreakID() { delete dat; } BreakID::BreakID() { dat = new PrivateData; dat->conf = new Config; } void BreakID::set_useMatrixDetection(bool val) { dat->conf->useMatrixDetection = val; } void BreakID::set_useBinaryClauses(bool val) { dat->conf->useBinaryClauses = val; } void BreakID::set_useShatterTranslation(bool val) { dat->conf->useShatterTranslation = val; } void BreakID::set_useFullTranslation(bool val) { dat->conf->useFullTranslation = val; } void BreakID::set_symBreakingFormLength(int val) { dat->conf->symBreakingFormLength = val; } void BreakID::set_verbosity(uint32_t val) { dat->conf->verbosity = val; } void BreakID::set_steps_lim(int64_t val) { dat->conf->steps_lim = val; } int64_t BreakID::get_steps_remain() const { return dat->conf->remain_steps_lim; } void BreakID::start_dynamic_cnf(uint32_t nVars) { assert(dat->theory == NULL); dat->conf->nVars = nVars; dat->theory = new OnlCNF(dat->conf); } void BreakID::add_clause(BID::BLit* start, size_t num) { dat->theory->add_clause(start, num); } void BreakID::end_dynamic_cnf() { dat->theory->end_dynamic_cnf(); dat->theory->set_new_group(); } uint32_t BreakID::get_num_generators() { return dat->theory->group->getSize(); } void BreakID::detect_subgroups() { dat->theory->group->getDisjointGenerators(dat->subgroups); } uint64_t BreakID::get_num_subgroups() const { return dat->subgroups.size(); } void BreakID::print_subgroups(std::ostream& out) { for (auto& grp : dat->subgroups) { out << "group size: " << grp->getSize() << " support: " << grp->getSupportSize() << endl; grp->print(out); } } void BreakID::break_symm() { dat->brkr = new Breaker(dat->theory, dat->conf); for (auto& grp : dat->subgroups) { //Try to find matrix row interch. symmetries if (grp->getSize() > 1 && dat->conf->useMatrixDetection) { if (dat->conf->verbosity > 0) { cout << "Detecting row interchangeability..." << endl; } // Find set of clauses group permutates // add the subgroup to "grp->theory" dat->theory->setSubTheory(grp); // Upate group with matrix symmetries: matrixes, permutations grp->addMatrices(); //Update stats dat->totalNbMatrices += grp->getNbMatrices(); dat->totalNbRowSwaps += grp->getNbRowSwaps(); } //Symmetry if (dat->conf->symBreakingFormLength > -1) { if (dat->conf->verbosity > 0) { cout << "*** Constructing symmetry breaking formula..." << endl; } grp->addBreakingClausesTo(*dat->brkr); } } } void BreakID::print_symm_break_stats() { cout << "**** matrices detected: " << dat->totalNbMatrices << endl; cout << "**** row swaps detected: " << dat->totalNbRowSwaps << endl; cout << "**** extra binary symmetry breaking clauses added: " << dat->brkr->getNbBinClauses() << "\n"; cout << "**** regular symmetry breaking clauses added: " << dat->brkr->getNbRegClauses() << "\n"; cout << "**** row interchangeability breaking clauses added: " << dat->brkr->getNbRowClauses() << "\n"; cout << "**** total symmetry breaking clauses added: " << dat->brkr->getAddedNbClauses() << "\n"; cout << "**** auxiliary variables introduced: " << dat->brkr->getAuxiliaryNbVars() << "\n"; } uint32_t BreakID::get_num_break_cls() { return dat->brkr->getAddedNbClauses(); } uint32_t BreakID::get_num_aux_vars() { return dat->brkr->getAuxiliaryNbVars(); } vector<vector<BID::BLit>> BreakID::get_brk_cls() { return dat->brkr->get_brk_cls(); } void BreakID::print_perms_and_matrices(std::ostream& out) { for (auto grp : dat->subgroups) { grp->print(out); } } void BreakID::print_generators(std::ostream& out) { dat->theory->group->print(cout); } void BreakID::get_perms(vector<std::unordered_map<BLit, BLit> >* out) { assert(out->empty()); for (auto grp : dat->subgroups) { grp->get_perms_to(*out); } } std::string BreakID::get_sha1_version() const { return BID::get_version_sha1(); }
24.796078
80
0.641784
meelgroup
bd669e7b9abd96dc688d8060947ff6c18765c7c6
2,271
hh
C++
src/opbox/ops/OpHelpers.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-01-25T21:21:07.000Z
2021-04-29T17:24:00.000Z
src/opbox/ops/OpHelpers.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
8
2018-10-09T14:35:30.000Z
2020-09-30T20:09:42.000Z
src/opbox/ops/OpHelpers.hh
faodel/faodel
ef2bd8ff335433e695eb561d7ecd44f233e58bf0
[ "MIT" ]
2
2019-04-23T19:01:36.000Z
2021-05-11T07:44:55.000Z
// Copyright 2021 National Technology & Engineering Solutions of Sandia, LLC // (NTESS). Under the terms of Contract DE-NA0003525 with NTESS, the U.S. // Government retains certain rights in this software. #ifndef OPBOX_OPHELPERS_HH #define OPBOX_OPHELPERS_HH #include "opbox/common/Types.hh" #include "opbox/common/Message.hh" #include "opbox/OpBox.hh" namespace opbox { /** * @brief Designate that network should only notify Op about errors */ class ErrorOnlyCallback { private: Op *op; public: explicit ErrorOnlyCallback(Op *op) : op(op) {} WaitingType operator()(OpArgs *args) { if ((args->type >= UpdateType::send_error) && (args->type <= UpdateType::atomic_error)) { opbox::internal::UpdateOp(op, args); } return WaitingType::done_and_destroy; } }; /** * @brief Designate that network should only notify Op about successful events */ class SuccessOnlyCallback { private: Op *op; public: explicit SuccessOnlyCallback(Op *op) : op(op) {} WaitingType operator()(OpArgs *args) { if (args->type < UpdateType::timeout) { opbox::internal::UpdateOp(op, args); } return WaitingType::done_and_destroy; } }; /** * @brief Designate that network should only notify Op about unsuccessful events */ class UnsuccessfulOnlyCallback { private: Op *op; public: explicit UnsuccessfulOnlyCallback(Op *op) : op(op) {} WaitingType operator()(OpArgs *args){ if (args->type >= UpdateType::timeout) { opbox::internal::UpdateOp(op, args); } return WaitingType::done_and_destroy; } }; /** * @brief Designate that network should only notify Op about timeout events */ class TimeoutOnlyCallback { private: Op *op; public: explicit TimeoutOnlyCallback(Op *op) : op(op) {} WaitingType operator()(OpArgs *args) { if (args->type == UpdateType::timeout) { opbox::internal::UpdateOp(op, args); } return WaitingType::done_and_destroy; } }; /** * @brief Designate that network should notify Op about all events */ class AllEventsCallback { private: Op *op; public: explicit AllEventsCallback(Op *op) : op(op) {} WaitingType operator()(OpArgs *args) { opbox::internal::UpdateOp(op, args); return WaitingType::done_and_destroy; } }; } #endif // OPBOX_OPHELPERS_HH
23.65625
93
0.696169
faodel
bd6cbb970402b0aee3778775d4503e5743662c84
2,065
cpp
C++
stat01.cpp
DTL2020/stat01
5c9ec775071f234f062d23d6434649a0a48d92f5
[ "MIT" ]
null
null
null
stat01.cpp
DTL2020/stat01
5c9ec775071f234f062d23d6434649a0a48d92f5
[ "MIT" ]
null
null
null
stat01.cpp
DTL2020/stat01
5c9ec775071f234f062d23d6434649a0a48d92f5
[ "MIT" ]
null
null
null
// stat01.cpp : This file contains the 'main' function. Program execution begins and ends there. // #include "pch.h" #include "math.h" int ArrSamples[10] = { 52, 46, 54, 20, 50, 48, 51, 53, 45, 50 }; int ArrSADs[10][10] = {}; int ArrOut[10] = {}; int VectMinSumSADs[10] = {}; int iVectIncludedSamples[10] = {}; int thSAD = 5; int main() { for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { ArrSADs[i][j] = abs(ArrSamples[i] - ArrSamples[j]); } } //calc vect min sums sads for (int i = 0; i < 10; i++) { int minsunsads = 0; for (int j = 0; j < 10; j++) { minsunsads += ArrSADs[i][j]; } VectMinSumSADs[i] = minsunsads; } int idx_minsad = 0; int minsumsads = 10e10; for (int i = 0; i < 10; i++) { if (VectMinSumSADs[i] < minsumsads) { minsumsads = VectMinSumSADs[i]; idx_minsad = i; } } for (int i = 0; i < 10; i++) { if (ArrSADs[idx_minsad][i] < thSAD ) { iVectIncludedSamples[i] = 1; } else { iVectIncludedSamples[i] = 0; } } //calc output for (int i = 0; i < 10; i++) { float fMidval2 = 0; int cnt = 0; if (iVectIncludedSamples[i] == 0) // skip proc { ArrOut[i] = ArrSamples[i]; continue; } for (int j = 0; j < 10; j++) { if ((iVectIncludedSamples[j] != 0) || (ArrSADs[i][j] < thSAD)) { fMidval2 += ArrSamples[j]; cnt++; } else if (j == i) { fMidval2 += ArrSamples[j]; cnt++; } /* if (ArrSADs[i][j] < thSAD) { fMidval2 += ArrSamples[j]; cnt++; }*/ } fMidval2 /= cnt; ArrOut[i] = round(fMidval2); } // calc psnr float fMid_val = 0; for (int i = 0; i < 10; i++) { fMid_val += ArrSamples[i]; } fMid_val /= 10; float fNoise = 0; for(int i=0; i<10; i++) { fNoise += (ArrOut[i] - fMid_val)*(ArrOut[i] - fMid_val); } fNoise /= 10; float fpsnr = 10e10; if (fNoise != 0) { fpsnr = fMid_val* fMid_val / fNoise; } int idbr = 0; }
15.884615
97
0.498789
DTL2020
bd6cfe108e03104a4d200392a9adcdb0d11dfde9
11,152
cpp
C++
vlib/slib/utils/tree.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
vlib/slib/utils/tree.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
vlib/slib/utils/tree.cpp
syntheticgio/fda-hive
5e645c6a5b76b5a437635631819a1c934c7fd7fc
[ "Unlicense", "MIT" ]
null
null
null
/* * ::718604! * * Copyright(C) November 20, 2014 U.S. Food and Drug Administration * Authors: Dr. Vahan Simonyan (1), Dr. Raja Mazumder (2), et al * Affiliation: Food and Drug Administration (1), George Washington University (2) * * All rights Reserved. * * The MIT License (MIT) * * 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 <slib/utils/tree.hpp> #include <ssci/math/clust/clust2.hpp> using namespace slib; #if 0 struct ForCallBack { sTabular *tbl; sVec <idx> *values; sVec <idx> *uIDs; idx horizontal; }; static idx myCallBack(sStr &out, sHierarchicalClustering &clust, idx x, void *param_) { struct ForCallBack * param = static_cast<ForCallBack*>(param_); if (x >= param->values->dim()) return 0; if (param->horizontal) { if(!param->uIDs || !param->uIDs->dim()) param->tbl->printCell(out, (*(param->values))[x], 0); else { for( idx iu=0; iu<param->uIDs->dim(); ++iu ) { if(iu)out.printf(" "); param->tbl->printCell(out, (*(param->values))[x], (*(param->uIDs))[iu]); } } } else { param->tbl->printCell(out, -1, (*(param->values))[x]); } return 1; } #endif struct PrintNewickCallbackParam { sTabular * tbl; sVec <idx> * objToUse; sVec<idx> * uIDs; bool horizontal; }; static idx printNewickCallback(sStr &out, sHierarchicalClustering &clust, idx x, void *param_) { struct PrintNewickCallbackParam * param = static_cast<PrintNewickCallbackParam*>(param_); if( param->horizontal ) { idx ir = param->objToUse && param->objToUse->dim() ? (*param->objToUse)[x] : x; if( param->uIDs && param->uIDs->dim() ) { for(idx i = 0; i < param->uIDs->dim(); i++) { idx ic = (*param->uIDs)[i]; if( i ) { out.addString(" "); } param->tbl->printCell(out, ir, ic); } } else { out.addNum(ir); } } else { idx ic = param->objToUse && param->objToUse->dim() ? (*param->objToUse)[x] : x; if( param->uIDs && param->uIDs->dim() ) { for(idx i = 0; i < param->uIDs->dim(); i++) { idx ir = (*param->uIDs)[i]; if( i ) { out.addString(" "); } param->tbl->printCell(out, ir, ic); } } else { out.addNum(ic); } } return 1; } idx reorderIterate (sHierarchicalClusteringTree & tree, idx curPos, sVec <real> *averages, sVec <idx> newOrder, sVec <idx> colsToUse, sTabular * tbl) { if (curPos < 0) { return 0; } sHierarchicalClusteringTree::Tnode & node = tree.getNodeVec()[curPos]; if (curPos < tree.dimLeaves()) { idx row = newOrder[curPos]; real total = 0; for (idx i = 0; i < colsToUse.dim(); i++) { idx curCol = colsToUse[i]; total += tbl->rval(row, curCol); } (*averages)[curPos] = total/colsToUse.dim(); return 0; } reorderIterate (tree, node.out[0], averages, newOrder, colsToUse, tbl); reorderIterate (tree, node.out[1], averages, newOrder, colsToUse, tbl); if ((*averages)[node.out[0]] > (*averages) [node.out[1]]) { sSwapI(node.out[0], node.out[1]); } (*averages)[curPos] = ((*averages)[node.out[0]] + (*averages) [node.out[1]])/2; return 0; } idx rememberReorder (sHierarchicalClusteringTree & tree, idx curPosInTree, idx curPosInVec, sVec <idx> * newOrder) { if (curPosInTree < 0 || curPosInTree >= newOrder->dim()) { return curPosInVec; } sHierarchicalClusteringTree::Tnode & node = tree.getNodeVec()[curPosInTree]; if (curPosInTree < tree.dimLeaves()) { // leaf node (*newOrder)[curPosInVec] = curPosInTree; return curPosInVec + 1; } // inner node curPosInVec = rememberReorder(tree, curPosInVec, node.out[0], newOrder); curPosInVec = rememberReorder(tree, curPosInVec, node.out[1], newOrder); return curPosInVec; } namespace { struct DistCallbackParam { sTabular * tbl; idx * rowSet; idx * colSet; idx rowCnt; idx colCnt; bool horizontal; sTree::DistanceMethods distMethod; }; }; static real distCallback(idx x, idx y, void * param_) { const DistCallbackParam * param = static_cast<DistCallbackParam*>(param_); sDistAccum<real, sBufferIter<real> > * dist = 0; sEuclideanDistAccum<real, sBufferIter<real> > euclidean_dist; sManhattanDistAccum<real, sBufferIter<real> > manhattan_dist; sMaximumDistAccum<real, sBufferIter<real> > maximum_dist; sCosineDistAccum<real, sBufferIter<real> > cosine_dist; switch( param->distMethod ) { case sTree::EUCLIDEAN: dist = &euclidean_dist; break; case sTree::MANHATTAN: dist = &manhattan_dist; break; case sTree::MAXIMUM: dist = &maximum_dist; break; case sTree::COSINE: dist = &cosine_dist; break; } idx vec_dim = param->horizontal ? param->colCnt : param->rowCnt; idx ir1 = 0, ir2 = 0, ic1 = 0, ic2 = 0; if( param->horizontal ) { if( param->rowSet ) { ir1 = param->rowSet[x]; ir2 = param->rowSet[y]; } else { ir1 = x; ir2 = y; } } else { if( param->colSet ) { ic1 = param->colSet[x]; ic2 = param->colSet[y]; } else { ic1 = x; ic2 = y; } } for(idx i = 0; i < vec_dim; i++) { if( param->horizontal ) { if( param->colSet ) { ic1 = ic2 = param->colSet[i]; } else { ic1 = ic2 = i; } } else { if( param->rowSet ) { ir1 = ir2 = param->rowSet[i]; } else { ir1 = ir2 = i; } } dist->accum(param->tbl->rdiff(ir1, ic1, ir2, ic2), 0); } return dist->result(); } #define BENCH_TREE 1 #ifdef BENCH_TREE #define print_bench(fmt, ...) fprintf(stderr, "%s:%u %.2g sec (%.2g CPU) " fmt "\n", __FILE__, __LINE__, wall_clock.clock(0, 0, true), cpu_clock.clock(), ##__VA_ARGS__) #else #define print_bench(fmt, ...) #endif idx sTree::generateTree (sStr & out,sVec < idx > * columnsToUse, sVec <idx > * rowsToUse, sTabular * tbl, sVec <idx> * newOrder, idx horizontal, sVec < idx > * uIDs , DistanceMethods distMethod, neighborJoiningMethods jMethod) { #ifdef BENCH_TREE sTime cpu_clock, wall_clock; wall_clock.clock(0, 0, true); cpu_clock.clock(); #endif sVec <idx> * objToUse = horizontal ? rowsToUse : columnsToUse; //idx colCnt=(columnsToUse && columnsToUse->dim()) ? columnsToUse->dim() : tbl->cols();//! the total number of columns to go through DistCallbackParam dist_cb_param; dist_cb_param.tbl = tbl; dist_cb_param.rowSet = rowsToUse && rowsToUse->dim() ? rowsToUse->ptr() : 0; dist_cb_param.colSet = columnsToUse && columnsToUse->dim() ? columnsToUse->ptr() : 0; dist_cb_param.rowCnt = rowsToUse ? rowsToUse->dim() : tbl->rows(); dist_cb_param.colCnt = columnsToUse ? columnsToUse->dim() : tbl->cols(); dist_cb_param.horizontal = horizontal; dist_cb_param.distMethod = distMethod; idx cnt = horizontal ? dist_cb_param.rowCnt : dist_cb_param.colCnt; // count of objToUse print_bench("to setup %" DEC " items (%s)", cnt, horizontal ? "horizontal" : "vertical"); sHierarchicalClustering * nj; if( jMethod==FAST ) { nj = new sFastNeighborJoining(); } else { nj = new sNeighborJoining (); } nj->resetDistance(cnt, distCallback, &dist_cb_param); print_bench("to make dist matrix"); nj->recluster(); print_bench("to cluster using %s", jMethod==FAST ? "FNJ" : "NJ"); #ifdef DEBUG_TREE fprintf(stderr, "Distance matrix:\n"); sStr distbuf; nj.printMatrixCSV(distbuf); fprintf(stderr, "%s\n", distbuf.ptr()); sFil heatmapCSV("distmatrix.csv"); nj.printMatrixCSV(heatmapCSV); #endif sVec<idx> leafOrder; nj->getTree().getLeaves(leafOrder); print_bench("to get leaves"); newOrder->resize(leafOrder.dim()); for (idx i=0; i < leafOrder.dim(); i++) { idx newPos=leafOrder[i]; (*newOrder)[i]=(*objToUse)[newPos]; } print_bench("to make new leaf order"); #if 0 sVec <real> perRowAverage; if (horizontal) { sHierarchicalClusteringTree & tree = nj->getTree(); perRowAverage.resize(tree.dim()); //sHierarchicalClusteringTree root = tree.getNodeVec(); reorderIterate (tree, &tree.getRoot() - tree.getNodeVec().ptr(), &perRowAverage, *newOrder, *columnsToUse, tbl); //rememberReorder (tree, &tree.getRoot() - tree.getNodeVec().ptr(), 0, newOrder); sVec<idx> leafOrder; tree.getLeaves(leafOrder); //newOrder->resize(leafOrder.dim()); for (idx i=0; i < leafOrder.dim(); i++) { idx newPos=leafOrder[i]; (*newOrder)[i]=(*objToUse)[newPos]; } } print_bench("to make averages"); ForCallBack obj; obj.tbl = tbl; obj.values = newOrder; obj.uIDs=uIDs; obj.horizontal = horizontal; nj->printNewick(out,sHierarchicalClusteringTree::Newick_PRINT_DISTANCE|sHierarchicalClusteringTree::Newick_PRINT_LEAF_NAMES,myCallBack,&obj); #endif PrintNewickCallbackParam print_newick_callback_param; print_newick_callback_param.tbl = tbl; print_newick_callback_param.objToUse = objToUse; print_newick_callback_param.uIDs = uIDs; print_newick_callback_param.horizontal = horizontal; nj->printNewick(out, sHierarchicalClusteringTree::Newick_PRINT_DISTANCE|sHierarchicalClusteringTree::Newick_PRINT_LEAF_NAMES, printNewickCallback, &print_newick_callback_param); print_bench("to print Newick"); return 0; }
30.140541
226
0.600699
syntheticgio
bd6f08af91ce141d502613f4aff0f290a93618ad
20,380
cpp
C++
OpenYuma/netconf/test/support/callbacks/running-cb-checker.cpp
5GExchange/escape
eb35d460597a0386b18dd5b6a5f62a3f30eed5fa
[ "Apache-2.0" ]
10
2016-11-16T16:26:16.000Z
2021-04-26T17:20:28.000Z
OpenYuma/netconf/test/support/callbacks/running-cb-checker.cpp
5GExchange/escape
eb35d460597a0386b18dd5b6a5f62a3f30eed5fa
[ "Apache-2.0" ]
3
2017-04-20T11:29:17.000Z
2017-11-06T17:12:12.000Z
OpenYuma/netconf/test/support/callbacks/running-cb-checker.cpp
5GExchange/escape
eb35d460597a0386b18dd5b6a5f62a3f30eed5fa
[ "Apache-2.0" ]
10
2017-03-27T13:58:52.000Z
2020-06-24T22:42:51.000Z
// ---------------------------------------------------------------------------| // Test Harness includes // ---------------------------------------------------------------------------| #include "test/support/callbacks/running-cb-checker.h" // ---------------------------------------------------------------------------| // File wide namespace use // ---------------------------------------------------------------------------| using namespace std; // ---------------------------------------------------------------------------| namespace YumaTest { // ---------------------------------------------------------------------------! RunningCBChecker::RunningCBChecker() : CallbackChecker() { } // ---------------------------------------------------------------------------! RunningCBChecker::~RunningCBChecker() { } // ---------------------------------------------------------------------------| void RunningCBChecker::addMainContainer(const std::string& modName, const std::string& containerName) { vector<string> empty; addExpectedCallback(modName, containerName, empty, "edit", "validate", ""); addExpectedCallback(modName, containerName, empty, "edit", "apply", ""); addExpectedCallback(modName, containerName, empty, "edit", "commit", "create"); } // ---------------------------------------------------------------------------| void RunningCBChecker::addElement(const std::string& modName, const std::string& containerName, const std::vector<std::string>& element) { addExpectedCallback(modName, containerName, element, "edit", "validate", ""); addExpectedCallback(modName, containerName, element, "edit", "apply", ""); addExpectedCallback(modName, containerName, element, "edit", "commit", "replace"); } // ---------------------------------------------------------------------------| void RunningCBChecker::addKey(const std::string& modName, const std::string& containerName, const std::vector<std::string>& listElement, const std::string& key) { vector<string> elements(listElement); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.pop_back(); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); elements.pop_back(); addExpectedCallback(modName, containerName, elements, "edit", "commit", "create"); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "commit", "create"); } // ---------------------------------------------------------------------------| void RunningCBChecker::addChoice(const std::string& modName, const std::string& containerName, const std::vector<std::string>& choiceElement, const std::vector<std::string>& removeElement) { vector<string> deleteElements(removeElement); addExpectedCallback(modName, containerName, deleteElements, "edit", "validate", ""); addExpectedCallback(modName, containerName, deleteElements, "edit", "apply", ""); addExpectedCallback(modName, containerName, deleteElements, "edit", "commit", "delete"); vector<string> addElements(choiceElement); addExpectedCallback(modName, containerName, addElements, "edit", "validate", ""); addExpectedCallback(modName, containerName, addElements, "edit", "apply", ""); addExpectedCallback(modName, containerName, addElements, "edit", "commit", "create"); } // ---------------------------------------------------------------------------| void RunningCBChecker::addKeyValuePair(const std::string& modName, const std::string& containerName, const std::vector<std::string>& listElement, const std::string& key, const std::string& value) { vector<string> elements(listElement); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.pop_back(); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); elements.pop_back(); addExpectedCallback(modName, containerName, elements, "edit", "commit", "create"); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "commit", "create"); elements.pop_back(); elements.push_back(value); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); addExpectedCallback(modName, containerName, elements, "edit", "commit", "create"); } // ---------------------------------------------------------------------------| void RunningCBChecker::commitKeyValuePairs(const std::string& modName, const std::string& containerName, const std::vector<std::string>& listElement, const std::string& key, const std::string& value, int count) { // Do nothing as commits are not performed separately when using writeable running. } // ---------------------------------------------------------------------------| void RunningCBChecker::deleteKey(const std::string& modName, const std::string& containerName, const std::vector<std::string>& listElement, const std::string& key) { vector<string> elements(listElement); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.pop_back(); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); //TODO - Add commit callbacks } // ---------------------------------------------------------------------------| void RunningCBChecker::deleteKeyValuePair(const std::string& modName, const std::string& containerName, const std::vector<std::string>& listElement, const std::string& key, const std::string& value) { vector<string> elements(listElement); elements.push_back(value); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); addExpectedCallback(modName, containerName, elements, "edit", "commit", "delete"); elements.pop_back(); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.push_back(key); addExpectedCallback(modName, containerName, elements, "edit", "validate", ""); elements.pop_back(); addExpectedCallback(modName, containerName, elements, "edit", "apply", ""); addExpectedCallback(modName, containerName, elements, "edit", "commit", "delete"); } // ---------------------------------------------------------------------------| void RunningCBChecker::addResourceNode(const std::string& modName, const std::string& containerName, const std::vector<std::string>& elements, bool statusConfig, bool alarmConfig) { vector<string> hierarchy(elements); hierarchy.push_back("resourceNode"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("resourceType"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("configuration"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); if (statusConfig) { hierarchy.pop_back(); hierarchy.push_back("statusConfig"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); } if (alarmConfig) { hierarchy.pop_back(); hierarchy.push_back("alarmConfig"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); } hierarchy.pop_back(); hierarchy.push_back("physicalPath"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("resourceType"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("configuration"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); if (statusConfig) { hierarchy.pop_back(); hierarchy.push_back("statusConfig"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); } if (alarmConfig) { hierarchy.pop_back(); hierarchy.push_back("alarmConfig"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); } hierarchy.pop_back(); hierarchy.push_back("physicalPath"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("resourceType"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("configuration"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); if (statusConfig) { hierarchy.pop_back(); hierarchy.push_back("statusConfig"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); } if (alarmConfig) { hierarchy.pop_back(); hierarchy.push_back("alarmConfig"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); } hierarchy.pop_back(); hierarchy.push_back("physicalPath"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); } // ---------------------------------------------------------------------------| void RunningCBChecker::addResourceCon(const std::string& modName, const std::string& containerName, const std::vector<std::string>& elements) { vector<string> hierarchy(elements); hierarchy.push_back("resourceConnection"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("sourceId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("sourcePinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("destinationId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("destinationPinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("bitrate"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("sourceId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("sourcePinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("destinationId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("destinationPinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("bitrate"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("sourceId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("sourcePinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("destinationId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("destinationPinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("bitrate"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); } // ---------------------------------------------------------------------------| void RunningCBChecker::addStreamCon(const std::string& modName, const std::string& containerName, const std::vector<std::string>& elements) { vector<string> hierarchy(elements); hierarchy.push_back("streamConnection"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("sourceStreamId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("destinationStreamId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("sourceId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("sourcePinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("destinationId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("destinationPinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); hierarchy.push_back("bitrate"); addExpectedCallback(modName, containerName, hierarchy, "edit", "validate", ""); hierarchy.pop_back(); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("sourceStreamId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("destinationStreamId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("sourceId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("sourcePinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("destinationId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("destinationPinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); hierarchy.push_back("bitrate"); addExpectedCallback(modName, containerName, hierarchy, "edit", "apply", ""); hierarchy.pop_back(); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.push_back("id"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("sourceStreamId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("destinationStreamId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("sourceId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("sourcePinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("destinationId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("destinationPinId"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); hierarchy.pop_back(); hierarchy.push_back("bitrate"); addExpectedCallback(modName, containerName, hierarchy, "edit", "commit", "create"); } // ---------------------------------------------------------------------------| void RunningCBChecker::updateLeaf(const std::string& modName, const std::string& containerName, const std::vector<std::string>& listElement, const std::string& phase) { addExpectedCallback(modName, containerName, listElement, "edit", "validate", ""); addExpectedCallback(modName, containerName, listElement, "edit", "apply", ""); addExpectedCallback(modName, containerName, listElement, "edit", "commit", phase); } // ---------------------------------------------------------------------------| void RunningCBChecker::updateContainer(const std::string& modName, const std::string& containerName, const std::vector<std::string>& listElement, const std::string& phase) { addExpectedCallback(modName, containerName, listElement, "edit", "validate", ""); addExpectedCallback(modName, containerName, listElement, "edit", "apply", ""); addExpectedCallback(modName, containerName, listElement, "edit", "commit", phase); } } // namespace YumaTest
49.466019
92
0.600638
5GExchange
bd71aae4ecfcdd068a0e2da125a0653a56d85402
1,592
cpp
C++
Windows/IniReader.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
11
2020-03-10T02:06:00.000Z
2022-02-17T19:59:50.000Z
Windows/IniReader.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
null
null
null
Windows/IniReader.cpp
cas-nctu/multispec
0bc840bdb073b5feaeec650c2da762cfa34ee37d
[ "Apache-2.0" ]
5
2020-05-30T00:59:22.000Z
2021-12-06T01:37:05.000Z
#include "IniReader.h" #include <iostream> #include <Windows.h> CIniReader::CIniReader(char* szFileName) { memset(m_szFileName, 0x00, 255); memcpy(m_szFileName, szFileName, strlen(szFileName)); } int CIniReader::ReadInteger(char* szSection, char* szKey, int iDefaultValue) { int iResult = GetPrivateProfileInt((LPCWSTR)szSection, (LPCWSTR)szKey, iDefaultValue, (LPCWSTR)m_szFileName); return iResult; } float CIniReader::ReadFloat(char* szSection, char* szKey, float fltDefaultValue) { char szResult[255]; char szDefault[255]; float fltResult; sprintf_s(szDefault, "%f",fltDefaultValue); GetPrivateProfileString((LPCWSTR)szSection, (LPCWSTR)szKey, (LPCWSTR)szDefault, (LPWSTR)szResult, 255, (LPCWSTR)m_szFileName); fltResult = (float)atof(szResult); return fltResult; } bool CIniReader::ReadBoolean(char* szSection, char* szKey, bool bolDefaultValue) { char szResult[255]; char szDefault[255]; bool bolResult; sprintf_s(szDefault, "%s", bolDefaultValue? "True" : "False"); GetPrivateProfileString((LPCWSTR)szSection, (LPCWSTR)szKey, (LPCWSTR)szDefault, (LPWSTR)szResult, 255, (LPCWSTR)m_szFileName); bolResult = (strcmp(szResult, "True") == 0 || strcmp(szResult, "true") == 0) ? true : false; return bolResult; } char* CIniReader::ReadString(char* szSection, char* szKey, const char* szDefaultValue) { char* szResult = new char[255]; memset(szResult, 0x00, 255); GetPrivateProfileString((LPCWSTR)szSection, (LPCWSTR)szKey, (LPCWSTR)szDefaultValue, (LPWSTR)szResult, 255, (LPCWSTR)m_szFileName); return szResult; }
37.023256
130
0.731784
cas-nctu
bd76eaf5676f3498c1a498bc055beb34dee5bac1
7,252
cpp
C++
test/range/test-element_types.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
test/range/test-element_types.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
test/range/test-element_types.cpp
rogiervd/range
2ed4ee2063a02cadc575fe4e7a3b7dd61bbd2b5d
[ "Apache-2.0" ]
null
null
null
/* Copyright 2014, 2015 Rogier van Dalen. 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. */ #define BOOST_TEST_MODULE test_range_element_types #include "utility/test/boost_unit_test.hpp" #include "range/element_types.hpp" #include <type_traits> #include <list> #include <tuple> #include "meta/vector.hpp" #include "range/std.hpp" #include "range/take.hpp" BOOST_AUTO_TEST_SUITE(test_range_element_types) BOOST_AUTO_TEST_CASE (test_element_types_contents) { { typedef std::tuple<> tuple; static_assert (std::is_same < meta::as_vector <range::element_types <tuple>>::type, meta::vector<>>::value, ""); static_assert (std::is_same < meta::as_vector <range::element_types <tuple &>>::type, meta::vector<>>::value, ""); static_assert (std::is_same < meta::as_vector <range::element_types <tuple const &>>::type, meta::vector<>>::value, ""); } { typedef std::tuple <int> tuple; static_assert (std::is_same < meta::as_vector <range::element_types <tuple>>::type, meta::vector <int &&>>::value, ""); static_assert (std::is_same < meta::as_vector <range::element_types <tuple &>>::type, meta::vector <int &>>::value, ""); static_assert (std::is_same < meta::as_vector <range::element_types <tuple const &>>::type, meta::vector <int const &>>::value, ""); } { typedef std::tuple <int, int, int const &, float> tuple; static_assert (std::is_same < meta::as_vector <range::element_types <tuple>>::type, meta::vector <int &&, int &&, int const &, float &&> >::value, ""); static_assert (std::is_same < meta::as_vector <range::element_types <tuple &>>::type, meta::vector <int &, int &, int const &, float &> >::value, ""); static_assert (std::is_same < meta::as_vector <range::element_types <tuple const &>>::type, meta::vector < int const &, int const &, int const &, float const &> >::value, ""); } } BOOST_AUTO_TEST_CASE (test_element_types_behaviour) { { typedef meta::as_vector <range::element_types <std::tuple<>>>::type types; static_assert (meta::empty <types>::value, ""); static_assert (meta::size <types>::value == 0, ""); static_assert (meta::empty <direction::front, types>::value, ""); static_assert (meta::size <direction::front, types>::value == 0, ""); static_assert (meta::empty <direction::back, types>::value, ""); static_assert (meta::size <direction::back, types>::value == 0, ""); } { typedef range::element_types <std::tuple <float>> types; static_assert (!meta::empty <types>::value, ""); static_assert (meta::size <types>::value == 1, ""); static_assert (!meta::empty <direction::front, types>::value, ""); static_assert (meta::size <direction::front, types>::value == 1, ""); static_assert (!meta::empty <direction::back, types>::value, ""); static_assert (meta::size <direction::back, types>::value == 1, ""); static_assert (std::is_same < meta::first <types>::type, float &&>::value, ""); static_assert (std::is_same < meta::first <direction::front, types>::type, float &&>::value, ""); static_assert (std::is_same < meta::first <direction::back, types>::type, float &&>::value, ""); static_assert (meta::empty <meta::drop <types>::type>::value, ""); static_assert (meta::empty < meta::drop <direction::front, types>::type>::value, ""); static_assert (meta::empty < meta::drop <direction::back, types>::type>::value, ""); } { typedef range::element_types <std::tuple <float, bool, int>> types; static_assert (!meta::empty <types>::value, ""); static_assert (meta::size <types>::value == 3, ""); static_assert (!meta::empty <direction::front, types>::value, ""); static_assert (meta::size <direction::front, types>::value == 3, ""); static_assert (!meta::empty <direction::back, types>::value, ""); static_assert (meta::size <direction::back, types>::value == 3, ""); static_assert (std::is_same < meta::first <types>::type, float &&>::value, ""); static_assert (std::is_same < meta::first <direction::front, types>::type, float &&>::value, ""); static_assert (std::is_same < meta::first <direction::back, types>::type, int &&>::value, ""); static_assert (!meta::empty <meta::drop <types>::type>::value, ""); static_assert (meta::empty <meta::drop < direction::front, rime::size_t <3>, types>::type>::value, ""); static_assert (std::is_same < meta::first <meta::drop <types>::type>::type, bool &&>::value, ""); } } template <class ... Types> struct show_types; // Used on a homogeneous type, element_types becomes an infinite meta-range. BOOST_AUTO_TEST_CASE (test_element_types_homogeneous) { { typedef range::element_types <std::vector <int> &> types; static_assert (std::is_same < meta::first <types>::type, int &>::value, ""); static_assert (std::is_same < meta::first <meta::drop <types>::type>::type, int &>::value, ""); static_assert (std::is_same < meta::first <meta::drop <rime::size_t <34>, types>::type>::type, int &>::value, ""); // After one call to "drop", the range is turned into a view. typedef meta::drop <types>::type view; static_assert (std::is_same <meta::drop <view>::type, view>::value, ""); // It then becomes heterogeneous. static_assert (std::is_same < meta::drop <view>::type, view>::value, ""); static_assert (std::is_same < meta::drop <rime::size_t <3>, view>::type, view>::value, ""); } { std::list <int> l; auto v = range::take (l, rime::size_t <2>()); typedef range::element_types <decltype (v)> types; static_assert (std::is_same < meta::first <types>::type, int &>::value, ""); static_assert (std::is_same < meta::first <meta::drop <types>::type>::type, int &>::value, ""); static_assert (!meta::empty <types>::value, ""); static_assert (!meta::empty <meta::drop <types>::type>::value, ""); static_assert (meta::empty < meta::drop <meta::drop <types>::type>::type>::value, ""); } } BOOST_AUTO_TEST_SUITE_END()
37.381443
80
0.58246
rogiervd
bd779588491df32e3b54d34308caeb9a53f634d1
11,939
cpp
C++
src/Geometry/Boundaries/TetrahedralBoundary.cpp
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
src/Geometry/Boundaries/TetrahedralBoundary.cpp
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
src/Geometry/Boundaries/TetrahedralBoundary.cpp
parasol-ppl/PPL
04de04b23e0368e576d2136fee8729de44a3eda5
[ "BSD-3-Clause" ]
null
null
null
#include "TetrahedralBoundary.h" #include "Geometry/GMSPolyhedron.h" #include "Simulator/Conversions.h" #include "Utilities/MPUtils.h" #include "Utilities/PMPLExceptions.h" #include <algorithm> /*------------------------------- Construction -------------------------------*/ TetrahedralBoundary:: TetrahedralBoundary(const std::array<Point3d, 4>& _pts, const bool _check) : m_points(_pts) { if(_check) OrderPoints(); m_normals = ComputeNormals(); m_bbx = ComputeBBX(); m_volume = ComputeVolume(); } TetrahedralBoundary:: TetrahedralBoundary(const std::vector<Point3d>& _pts, const bool _check) { // Ensure the input vector contains exactly four points. if(_pts.size() != 4) throw RunTimeException(WHERE) << "Can't build tetrahedron with " << _pts.size() << " points."; std::copy(_pts.begin(), _pts.end(), m_points.begin()); if(_check) OrderPoints(); m_normals = ComputeNormals(); m_bbx = ComputeBBX(); m_volume = ComputeVolume(); } TetrahedralBoundary:: TetrahedralBoundary(XMLNode& _node) { throw NotImplementedException(WHERE); } TetrahedralBoundary:: ~TetrahedralBoundary() noexcept = default; std::unique_ptr<Boundary> TetrahedralBoundary:: Clone() const { return std::unique_ptr<TetrahedralBoundary>(new TetrahedralBoundary(*this)); } /*---------------------------- Property Accessors ----------------------------*/ Boundary::Space TetrahedralBoundary:: Type() const noexcept { return Boundary::Space::Workspace; } std::string TetrahedralBoundary:: Name() const noexcept { return "Tetrahedral"; } size_t TetrahedralBoundary:: GetDimension() const noexcept { return 3; } double TetrahedralBoundary:: GetMaxDist(const double _r1, const double _r2) const { auto edges = ComputeEdges(); std::array<double, 6> edgeLengths; for(size_t i = 0; i < 6; ++i) edgeLengths[i] = edges[i].norm(); return *std::max_element(edgeLengths.begin(), edgeLengths.end()); } const Range<double>& TetrahedralBoundary:: GetRange(const size_t _i) const { return m_bbx.GetRange(_i); } const std::vector<double>& TetrahedralBoundary:: GetCenter() const noexcept { throw RunTimeException(WHERE) << "Impl is wrong, need to compute the barycenter."; return m_bbx.GetCenter(); } double TetrahedralBoundary:: GetVolume() const noexcept { return m_volume; } /*--------------------------------- Sampling ---------------------------------*/ std::vector<double> TetrahedralBoundary:: GetRandomPoint() const { // From: // C. Rocchini and P. Cignoni, "Generating Random Points in a Tetrahedron," // Journal of Graphics Tools, 2001. // Pick a point in unit cube. double s = DRand(); double t = DRand(); double u = DRand(); // Cut cube in half with plane s + t = 1. if(s + t > 1) { s = 1 - s; t = 1 - t; } // Cut cube with planes t + u = 1 and s + t + u = 1. if(s + t + u > 1) { if(t + u > 1) { double ttmp = 1 - u; double utmp = 1 - s - t; std::swap(t, ttmp); std::swap(u, utmp); } else { double stmp = 1 - t - u; double utmp = s + t + u - 1; std::swap(s, stmp); std::swap(u, utmp); } } // Determine random point in tetrahedron. auto pt = m_points[0] + s * (m_points[1] - m_points[0]) + t * (m_points[2] - m_points[0]) + u * (m_points[3] - m_points[0]); return std::vector<double>{pt[0], pt[1], pt[2]}; } void TetrahedralBoundary:: PushInside(std::vector<double>& _sample) const noexcept { if(_sample.size() != 3) throw RunTimeException(WHERE) << "Only three dimensional points are " << "supported."; const Vector3d input(_sample[0], _sample[1], _sample[2]); // If _sample is already in the boundary, there is nothing to do. if(InBoundary(input)) return; const Vector3d output = GetClearancePoint(input); _sample = {output[0], output[1], output[2]}; } /*--------------------------- Containment Testing ----------------------------*/ bool TetrahedralBoundary:: InBoundary(const Vector3d& _p) const { // Check dot-product with normals touching point 0. const Vector3d p = _p - m_points[0]; for(size_t i = 0; i < 3; ++i) if(p * m_normals[i] > 0) return false; // Check dot-product with last normal. if((_p - m_points[1]) * m_normals[3] > 0) return false; return true; } bool TetrahedralBoundary:: InBoundary(const std::vector<double>& _v) const { if(_v.size() != 3) throw RunTimeException(WHERE) << "Does not make sense for vectors of " << "dimension " << _v.size() << " != 3."; return InBoundary(Vector3d(_v[0], _v[1], _v[2])); } bool TetrahedralBoundary:: InBoundary(const Cfg& _c) const { return InWorkspace(_c); } /*---------------------------- Clearance Testing -----------------------------*/ double TetrahedralBoundary:: GetClearance(const Vector3d& _p) const { throw NotImplementedException(WHERE); } Vector3d TetrahedralBoundary:: GetClearancePoint(const Vector3d& _p) const { // If _p is inside, the clearance point will be _p projected to the nearest // plane. // Otherwise, there are possibilities: // 1. _p is nearest to a vertex. This happens when it is 'in front' of exactly // three facet planes. The near point is the shared vertex. // 2. _p is nearest to an edge. This happens when it is 'in front' of exactly // two facet planes. The near point is the nearest point on the edge. // 3. _p is nearest to a facet. This happens when it is 'in front' of exactly // one facet plane. The near point is the nearest point on the triangle. throw NotImplementedException(WHERE); return Vector3d(); } /*--------------------------------- Modifiers --------------------------------*/ void TetrahedralBoundary:: SetCenter(const std::vector<double>& _c) noexcept { const size_t maxIndex = std::min(_c.size(), size_t(3)); for(size_t i = 0; i < maxIndex; ++i) { const double offset = _c[i] - GetCenter()[i]; for(size_t j = 0; j < 4; ++j) m_points[j][i] += offset; } m_bbx.SetCenter(_c); } void TetrahedralBoundary:: Translate(const Vector3d& _v) { m_bbx.Translate({_v[0], _v[1], _v[2]}); for(auto& p : m_points) p += _v; } void TetrahedralBoundary:: Translate(const std::vector<double>& _t) { m_bbx.Translate(_t); const size_t maxIndex = std::min(size_t(3), _t.size()); Vector3d v; for(size_t i = 0; i < maxIndex; ++i) v[i] = _t[i]; for(auto& p : m_points) p += v; } void TetrahedralBoundary:: ResetBoundary(const std::vector<std::pair<double, double>>& _bbx, const double _margin) { throw NotImplementedException(WHERE) << "Does not make sense for this object."; } /*------------------------------------ I/O -----------------------------------*/ void TetrahedralBoundary:: Read(std::istream& _is, CountingStreamBuffer& _cbs) { throw NotImplementedException(WHERE); } void TetrahedralBoundary:: Write(std::ostream& _os) const { _os << *this; } /*------------------------------- CGAL Representation ------------------------*/ Boundary::CGALPolyhedron TetrahedralBoundary:: CGAL() const { // Define builder object. struct builder : public CGAL::Modifier_base<CGALPolyhedron::HalfedgeDS> { const std::array<Point3d, 4>& m_points; /// The first three points must form an outward-facing facet. builder(const std::array<Point3d, 4>& _points) : m_points(_points) {} void operator()(CGALPolyhedron::HalfedgeDS& _h) { using Point = CGALPolyhedron::HalfedgeDS::Vertex::Point; CGAL::Polyhedron_incremental_builder_3<CGALPolyhedron::HalfedgeDS> b(_h); b.begin_surface(4, 4, 12); for(const auto& point : m_points) b.add_vertex(Point(point[0], point[1], point[2])); // Face 1 b.begin_facet(); b.add_vertex_to_facet(0); b.add_vertex_to_facet(1); b.add_vertex_to_facet(2); b.end_facet(); // Face 2 b.begin_facet(); b.add_vertex_to_facet(1); b.add_vertex_to_facet(3); b.add_vertex_to_facet(2); b.end_facet(); // Face 3 b.begin_facet(); b.add_vertex_to_facet(0); b.add_vertex_to_facet(3); b.add_vertex_to_facet(1); b.end_facet(); // Face 4 b.begin_facet(); b.add_vertex_to_facet(0); b.add_vertex_to_facet(2); b.add_vertex_to_facet(3); b.end_facet(); b.end_surface(); } }; CGALPolyhedron cp; builder b(m_points); cp.delegate(b); if(!cp.is_valid()) throw RunTimeException(WHERE) << "TetrahedralBoundary:: Invalid CGAL " << "polyhedron created!"; return cp; } GMSPolyhedron TetrahedralBoundary:: MakePolyhedron() const { GMSPolyhedron poly; // Add vertices. auto& v = poly.GetVertexList(); v = {m_points[0], m_points[1], m_points[2], m_points[3]}; // Add facets. auto& f = poly.GetPolygonList(); f.emplace_back(0, 1, 2, v); f.emplace_back(0, 2, 3, v); f.emplace_back(0, 3, 1, v); f.emplace_back(1, 3, 2, v); poly.Invert(); return poly; } /*-------------------------------- Helpers -----------------------------------*/ void TetrahedralBoundary:: OrderPoints() noexcept { // Get the points. const Vector3d& base = m_points[0]; const Vector3d& a = m_points[1]; const Vector3d& b = m_points[2]; const Vector3d& c = m_points[3]; // Find a,b,c relative to base. const Vector3d edgeA = a - base; const Vector3d edgeB = b - base; const Vector3d edgeC = c - base; // Points are OK if the norm of (base, a, b) faces away from edgeC. // Otherwise, swap points a and b to fix the ordering. const Vector3d norm = edgeA % edgeB; const bool normFacesAway = norm * edgeC < 0; if(!normFacesAway) std::swap(m_points[1], m_points[2]); } std::array<Vector3d, 6> TetrahedralBoundary:: ComputeEdges() const { std::array<Vector3d, 6> edges = {m_points[1] - m_points[0], m_points[2] - m_points[0], m_points[3] - m_points[0], m_points[2] - m_points[1], m_points[3] - m_points[1], m_points[3] - m_points[2]}; return edges; } std::array<Vector3d, 4> TetrahedralBoundary:: ComputeNormals() const { auto edges = ComputeEdges(); std::array<Vector3d, 4> normals = {(edges[0] % edges[1]).normalize(), (edges[1] % edges[2]).normalize(), (edges[2] % edges[0]).normalize(), (edges[4] % edges[3]).normalize()}; return normals; } NBox TetrahedralBoundary:: ComputeBBX() const { NBox bbx(3); for(size_t i = 0; i < bbx.GetDimension(); ++i) { Range<double> r(std::numeric_limits<double>::max(), std::numeric_limits<double>::lowest()); for(size_t j = 0; j < 4; ++j) r.ExpandToInclude(m_points[j][i]); bbx.SetRange(i, r); } return bbx; } double TetrahedralBoundary:: ComputeVolume() const { const mathtool::Vector3d v1 = m_points[2] - m_points[0], v2 = m_points[1] - m_points[0], v3 = m_points[3] - m_points[0], n = v1 % v2, h = v3.proj(n); const double baseArea = n.norm() / 2., height = h.norm(); return baseArea * height / 3.; } /*---------------------------------- I/O -------------------------------------*/ std::ostream& operator<<(std::ostream& _os, const TetrahedralBoundary& _b) { _os << "["; bool first = true; for(const auto& point : _b.m_points) { _os << (first ? "" : " ; ") << point; first = false; } return _os << "]"; } /*----------------------------------------------------------------------------*/
24.667355
84
0.580869
parasol-ppl
bd79d91c0558c2941b64895d1855dc3838658d2c
6,650
cpp
C++
4 course/info_protection/lab07/Widget.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
4 course/info_protection/lab07/Widget.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
4 course/info_protection/lab07/Widget.cpp
SgAkErRu/labs
9cf71e131513beb3c54ad3599f2a1e085bff6947
[ "BSD-3-Clause" ]
null
null
null
#include "Widget.h" #include "./ui_Widget.h" #include <cmath> #include <algorithm> #include <random> #include <QFileDialog> #include <QMessageBox> using namespace std; Widget::Widget(QWidget *parent) : QWidget(parent) , ui(new Ui::Widget) { ui->setupUi(this); this->prepareProbabilityTable(); this->prepareKeys(); } Widget::~Widget() { delete ui; } void Widget::prepareKeys() { // Генерируем массив из 1000 чисел. const uint16_t numberSize = 1000; vector<uint16_t> numbers(numberSize); iota(numbers.begin(), numbers.end(), 0); // Перемешиваем его. mt19937 mt (mt19937::result_type(time(nullptr))); shuffle(numbers.begin(), numbers.end(), mt); // Настраиваем таблицу. ui->tableWidget->horizontalHeader()->setMinimumSectionSize(headerSectionWidth); ui->tableWidget->horizontalHeader()->setDefaultSectionSize(headerSectionWidth); ui->tableWidget->setRowCount(maxRowCount); auto numberIt = numbers.begin(); // Для каждой буквы алфавита сгенерируем числа. auto columnCount = ALPHABET.length(); for (int i = 0; i < columnCount; ++i) { QChar c = ALPHABET[i]; ui->tableWidget->insertColumn(i); ui->tableWidget->setHorizontalHeaderItem(i, new QTableWidgetItem(QString(c))); // Список строк в соответствии с вероятностью появления символа c. auto rowCount = probabilityTable[c]; for (int j = 0; j < rowCount; ++j) { // Сохраняем омофон в таблицу. auto homophone = QString::number(*numberIt++).rightJustified(3, '0'); ui->tableWidget->setItem(j, i, new QTableWidgetItem(homophone)); // Сохраним в специальных контейнерах соответствие между буквой и омофоном. // Омофоны по букве. homophonesBySymbol[c].push_back(homophone); // И буква по омофону. symbolByHomophone[homophone] = c; } } } void Widget::prepareProbabilityTable() { probabilityTable[' '] = 146; probabilityTable[L'О'] = 94; probabilityTable[L'Е'] = 71; probabilityTable[L'А'] = 69; probabilityTable[L'И'] = 64; probabilityTable[L'Н'] = 57; probabilityTable[L'Т'] = 54; probabilityTable[L'С'] = 46; probabilityTable[L'Р'] = 42; probabilityTable[L'В'] = 38; probabilityTable[L'Л'] = 39; probabilityTable[L'К'] = 29; probabilityTable[L'М'] = 27; probabilityTable[L'Д'] = 24; probabilityTable[L'П'] = 26; probabilityTable[L'У'] = 23; probabilityTable[L'Я'] = 17; probabilityTable[L'Ы'] = 15; probabilityTable[L'З'] = 16; probabilityTable[L'Ъ'] = 1; probabilityTable[L'Ь'] = 13; probabilityTable[L'Б'] = 13; probabilityTable[L'Г'] = 14; probabilityTable[L'Ч'] = 12; probabilityTable[L'Й'] = 10; probabilityTable[L'Х'] = 8; probabilityTable[L'Ж'] = 7; probabilityTable[L'Ю'] = 5; probabilityTable[L'Ш'] = 6; probabilityTable[L'Ц'] = 5; probabilityTable[L'Щ'] = 4; probabilityTable[L'Э'] = 2; probabilityTable[L'Ф'] = 3; } Widget::Text Widget::readFromFile(const QString &filename) { Text text; QFile file(filename); if (file.open(QIODevice::ReadOnly)) { while (!file.atEnd()) { QString buffer = file.readLine(); text.push_back(buffer); } } else { QMessageBox::warning(this, "Ошибка!", "Не удалось открыть файл " + filename); } file.close(); return text; } void Widget::saveToFile(const Text &text, const QString &filename) { if (filename.length() <= 0) { return; } QFile file(filename); if (file.open(QIODevice::WriteOnly)) { for (auto &line : text) { file.write(line.toUtf8()); file.write("\n"); } } else { QMessageBox::warning(this, "Ошибка!", "Не удалось сохранить файл " + filename); } file.close(); } void Widget::openFileOnSystem(const QString &filename) const { #ifdef WIN32 std::wstring s = L"start \"\" \"" + filename.toStdWString() + L"\""; _wsystem(s.c_str()); #else auto s = "open \"" + filename.toStdString() + "\""; system(s.c_str()); #endif } Widget::Text Widget::crypt(const Text &text) const { mt19937 mt (mt19937::result_type(time(nullptr))); Text res; res.reserve(text.size()); for (const auto &origLine : text) { QString newLine; newLine.reserve(origLine.length() * 3); for (QChar c : origLine) { auto homophones = homophonesBySymbol[ c.isUpper() ? c : c.toUpper() ]; uniform_int_distribution<uint16_t> dist(0, uint16_t(homophones.size()-1)); newLine.push_back( homophones[dist(mt)] ); } res.push_back( newLine ); } return res; } Widget::Text Widget::decrypt(const Text &text) const { Text res; res.reserve(text.size()); for (const auto &origLine : text) { QString newLine; newLine.reserve(origLine.length() / 3); auto len = origLine.length(); for (qsizetype i = 0; i < len; i += 3) { auto homophone = origLine.mid(i, 3); auto decryptedChar = symbolByHomophone[homophone]; newLine.push_back( decryptedChar ); } res.push_back( newLine ); } return res; } void Widget::on_pushButton_openOrigFile_clicked() { this->origFileName = QFileDialog::getOpenFileName(this, "Открыть файл", ""); if (this->origFileName.length() > 0) { ui->lineEdit_origFilePath->setText(this->origFileName); } } void Widget::on_pushButton_saveOutFile_clicked() { this->outFileName = QFileDialog::getSaveFileName(this, "Сохранить файл", ""); if (this->outFileName.length() > 0) { // указываем путь ui->lineEdit_outFilePath->setText(this->outFileName); } } void Widget::on_pushButton_crypt_clicked() { const auto text = this->readFromFile(this->origFileName); if (text.length()) { this->saveToFile(this->crypt(text), this->outFileName); this->openFileOnSystem(this->outFileName); } } void Widget::on_pushButton_decrypt_clicked() { const auto text = this->readFromFile(this->origFileName); if (text.length()) { this->saveToFile(this->decrypt(text), this->outFileName); this->openFileOnSystem(this->outFileName); } } void Widget::on_lineEdit_outFilePath_textEdited(const QString &arg1) { this->outFileName = arg1; } void Widget::on_lineEdit_origFilePath_textEdited(const QString &arg1) { this->origFileName = arg1; }
24.906367
87
0.614586
SgAkErRu
bd7c798477d19239b38f3ba1e89147f3289c6ad2
1,963
cpp
C++
sem/4ex/work1/4ex2Pp.cpp
ruska112/infTasks
db3bf563376dac435f5fed74e03bc3592d67c46f
[ "MIT" ]
null
null
null
sem/4ex/work1/4ex2Pp.cpp
ruska112/infTasks
db3bf563376dac435f5fed74e03bc3592d67c46f
[ "MIT" ]
1
2021-11-16T11:17:37.000Z
2021-11-16T11:44:54.000Z
sem/4ex/work1/4ex2Pp.cpp
ruska112/infTasks
db3bf563376dac435f5fed74e03bc3592d67c46f
[ "MIT" ]
null
null
null
#include <iostream> const int maxRow = 128; const int maxCol = 128; int matrixRepacer (double *a, int n, int m) { int result = 0; int i, j; int negColCount = 0; int posRowCount = 0; double rowSum = 0; if ( n > 0 && n < maxRow && m > 0 && m < maxCol ) { for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { if (a[j*8 + i] < 0) { negColCount++; } rowSum += a[i*8 + j]; } if (rowSum > 0) { posRowCount++; } rowSum = 0; } if (negColCount > posRowCount) { result = 1; } else if (posRowCount > negColCount) { result = 2; } else { result = 3; } } return result; } int main() { int n, m; int i, j; int funcRes; do { system("clear"); printf("Enter count of row: "); scanf("%d", &n); } while (n <= 0 || n > maxRow); do { system("clear"); printf("Enter count of column: "); scanf("%d", &m); } while (m <= 0 || m > maxCol); double* a = new double [n * m]; for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("[%d][%d]", i, j); scanf("%lf", &a[i*8 + j]); } } for (i = 0; i < n; i++) { for (j = 0; j < m; j++) { printf("%3.1lf ", a[i*8 + j]); } printf("\n"); } funcRes = matrixRepacer(a, n, m); if (funcRes == 1) { printf("Column with negative element greater than row with positive sum\n"); } else if (funcRes == 2) { printf("Column with negative element less than row with positive sum\n"); } else if (funcRes) { printf("Column with negative element equal with row with positive sum\n"); } else { printf("\nError\n"); } delete[] a; return 0; }
20.882979
84
0.417219
ruska112
bd7fbf79e4f67ceb44f81e36a7a4aa0edcc97f06
1,037
cpp
C++
RLSimion/Lib/actor-cacla.cpp
xcillero001/SimionZoo
b343b08f3356e1aa230d4132b0abb58aac4c5e98
[ "MIT" ]
1
2019-02-21T10:40:28.000Z
2019-02-21T10:40:28.000Z
RLSimion/Lib/actor-cacla.cpp
JosuGom3z/SimionZoo
b343b08f3356e1aa230d4132b0abb58aac4c5e98
[ "MIT" ]
null
null
null
RLSimion/Lib/actor-cacla.cpp
JosuGom3z/SimionZoo
b343b08f3356e1aa230d4132b0abb58aac4c5e98
[ "MIT" ]
null
null
null
#include "actor.h" #include "vfa.h" #include "policy.h" #include "policy-learner.h" #include "../Common/named-var-set.h" #include "features.h" #include "etraces.h" #include "config.h" #include "parameters-numeric.h" #include "app.h" CACLALearner::CACLALearner(ConfigNode* pConfigNode): PolicyLearner(pConfigNode) { m_pStateFeatures = new FeatureList("Actor/s"); m_pAlpha = CHILD_OBJECT_FACTORY<NumericValue>(pConfigNode, "Alpha", "Learning gain [0..1]"); } CACLALearner::~CACLALearner() { delete m_pStateFeatures; } void CACLALearner::update(const State *s, const Action *a, const State *s_p, double r, double td) { double lastNoise; double alpha; //CACLA (van Hasselt) //if delta>0: theta= theta + alpha*(lastNoise)*phi_pi(s) if (td > 0.0) { alpha = m_pAlpha->get(); if (alpha != 0.0) { m_pPolicy->getFeatures(s, m_pStateFeatures); lastNoise = a->get(m_pPolicy->getOutputAction()) - m_pPolicy->getDeterministicOutput(m_pStateFeatures); m_pPolicy->addFeatures(m_pStateFeatures, alpha*lastNoise); } } }
23.044444
106
0.714561
xcillero001
bd8095816328e10b87f8d4df9e155e24214d5ad3
1,178
cc
C++
glacier/channel.cc
iceice/Glacier
779082cc197f753fb2feff63ac8fbe3f5512828c
[ "MIT" ]
2
2020-02-05T04:08:07.000Z
2020-08-15T01:57:41.000Z
glacier/channel.cc
iceice/Glacier
779082cc197f753fb2feff63ac8fbe3f5512828c
[ "MIT" ]
null
null
null
glacier/channel.cc
iceice/Glacier
779082cc197f753fb2feff63ac8fbe3f5512828c
[ "MIT" ]
null
null
null
#include "glacier/channel.h" #include <sys/epoll.h> #include "glacier/base/logging.h" Channel::Channel(EventLoop *loop) : loop_(loop), fd_(0), events_(0), revents_(0), lastevents_(0) {} Channel::Channel(EventLoop *loop, int fd) : loop_(loop), fd_(fd), events_(0), revents_(0), lastevents_(0) {} Channel::~Channel() {} void Channel::handleEvents() { events_ = 0; if ((revents_ & EPOLLHUP) && !(revents_ & EPOLLIN)) { // 文件描述符被挂断,并且文件描述符不可读 return; } if (revents_ & EPOLLERR) { // 文件描述符发生错误 try { errorCallback_(); } catch (const std::bad_function_call &e) { LOG_ERROR << "errorCallback_"; } return; } if (revents_ & (EPOLLIN | EPOLLPRI | EPOLLRDHUP)) { // 文件描述符可读,或有紧急的数据可读,或对端断开连接 try { readCallback_(); } catch (const std::bad_function_call &e) { LOG_ERROR << "errorCallback_"; } } if (revents_ & EPOLLOUT) { // 文件描述符可写 try { writeCallback_(); } catch (const std::bad_function_call &e) { LOG_ERROR << "errorCallback_"; } } // 更新events try { connCallback_(); } catch (const std::bad_function_call &e) { LOG_ERROR << "errorCallback_"; } }
24.040816
70
0.60781
iceice
bd8111c165e2e9957726dbc6a112caae08e73659
1,324
cpp
C++
aws-cpp-sdk-ecr/source/model/ReplicationDestination.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-02-10T08:06:54.000Z
2022-02-10T08:06:54.000Z
aws-cpp-sdk-ecr/source/model/ReplicationDestination.cpp
perfectrecall/aws-sdk-cpp
fb8cbebf2fd62720b65aeff841ad2950e73d8ebd
[ "Apache-2.0" ]
1
2022-01-03T23:59:37.000Z
2022-01-03T23:59:37.000Z
aws-cpp-sdk-ecr/source/model/ReplicationDestination.cpp
ravindra-wagh/aws-sdk-cpp
7d5ff01b3c3b872f31ca98fb4ce868cd01e97696
[ "Apache-2.0" ]
1
2021-12-30T04:25:33.000Z
2021-12-30T04:25:33.000Z
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ecr/model/ReplicationDestination.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::Utils::Json; using namespace Aws::Utils; namespace Aws { namespace ECR { namespace Model { ReplicationDestination::ReplicationDestination() : m_regionHasBeenSet(false), m_registryIdHasBeenSet(false) { } ReplicationDestination::ReplicationDestination(JsonView jsonValue) : m_regionHasBeenSet(false), m_registryIdHasBeenSet(false) { *this = jsonValue; } ReplicationDestination& ReplicationDestination::operator =(JsonView jsonValue) { if(jsonValue.ValueExists("region")) { m_region = jsonValue.GetString("region"); m_regionHasBeenSet = true; } if(jsonValue.ValueExists("registryId")) { m_registryId = jsonValue.GetString("registryId"); m_registryIdHasBeenSet = true; } return *this; } JsonValue ReplicationDestination::Jsonize() const { JsonValue payload; if(m_regionHasBeenSet) { payload.WithString("region", m_region); } if(m_registryIdHasBeenSet) { payload.WithString("registryId", m_registryId); } return payload; } } // namespace Model } // namespace ECR } // namespace Aws
17.653333
78
0.726586
perfectrecall
bd831a3528c2092c4cd2450efb5bba7e57838dac
700
cpp
C++
Source/Core/FileFormat/TIFF/Tag.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
42
2015-07-24T23:05:07.000Z
2022-03-16T01:31:04.000Z
Source/Core/FileFormat/TIFF/Tag.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
4
2015-03-17T05:42:49.000Z
2020-08-09T15:21:45.000Z
Source/Core/FileFormat/TIFF/Tag.cpp
X1aoyueyue/KVS
ad47d62bef4fdd9ddd3412a26ee6557b63f0543b
[ "BSD-3-Clause" ]
29
2015-01-03T05:56:32.000Z
2021-10-05T15:28:33.000Z
/****************************************************************************/ /** * @file Tag.cpp * @author Naohisa Sakamoto */ /****************************************************************************/ #include "Tag.h" #include <kvs/Type> #include <string> namespace kvs { namespace tiff { Tag::Tag(): m_id( 0 ), m_name( "" ) { } Tag::Tag( const kvs::UInt16 id, const std::string& name ): m_id( id ), m_name( name ) { } Tag::Tag( const Tag& tag ): m_id( tag.m_id ), m_name( tag.m_name ) { } Tag& Tag::operator = ( const Tag& tag ) { m_id = tag.m_id; m_name = tag.m_name; return *this; } } // end of namespace tiff } // end of namespace kvs
15.217391
78
0.437143
X1aoyueyue
bd83428194070b0305b44555f9d4ff38707a74ca
7,413
cpp
C++
blades/xbmc/xbmc/filesystem/FavouritesDirectory.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
4
2016-04-26T03:43:54.000Z
2016-11-17T08:09:04.000Z
blades/xbmc/xbmc/filesystem/FavouritesDirectory.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
17
2015-01-05T21:06:22.000Z
2015-12-07T20:45:44.000Z
blades/xbmc/xbmc/filesystem/FavouritesDirectory.cpp
krattai/AEBL
a7b12c97479e1236d5370166b15ca9f29d7d4265
[ "BSD-2-Clause" ]
3
2016-04-26T03:43:55.000Z
2020-11-06T11:02:08.000Z
/* * Copyright (C) 2005-2013 Team XBMC * http://xbmc.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, 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 XBMC; see the file COPYING. If not, see * <http://www.gnu.org/licenses/>. * */ #include "FavouritesDirectory.h" #include "File.h" #include "Directory.h" #include "Util.h" #include "profiles/ProfilesManager.h" #include "FileItem.h" #include "utils/XBMCTinyXML.h" #include "utils/log.h" #include "utils/StringUtils.h" #include "utils/URIUtils.h" #include "settings/AdvancedSettings.h" #include "video/VideoInfoTag.h" #include "music/tags/MusicInfoTag.h" #include "URL.h" namespace XFILE { bool CFavouritesDirectory::GetDirectory(const CURL& url, CFileItemList &items) { items.Clear(); if (url.IsProtocol("favourites")) { return Load(items); //load the default favourite files } return LoadFavourites(url.Get(), items); //directly load the given file } bool CFavouritesDirectory::Exists(const CURL& url) { if (url.IsProtocol("favourites")) { return XFILE::CFile::Exists("special://xbmc/system/favourites.xml") || XFILE::CFile::Exists(URIUtils::AddFileToFolder(CProfilesManager::GetInstance().GetProfileUserDataFolder(), "favourites.xml")); } return XFILE::CDirectory::Exists(url); //directly load the given file } bool CFavouritesDirectory::Load(CFileItemList &items) { items.Clear(); std::string favourites; favourites = "special://xbmc/system/favourites.xml"; if(XFILE::CFile::Exists(favourites)) CFavouritesDirectory::LoadFavourites(favourites, items); else CLog::Log(LOGDEBUG, "CFavourites::Load - no system favourites found, skipping"); favourites = URIUtils::AddFileToFolder(CProfilesManager::GetInstance().GetProfileUserDataFolder(), "favourites.xml"); if(XFILE::CFile::Exists(favourites)) CFavouritesDirectory::LoadFavourites(favourites, items); else CLog::Log(LOGDEBUG, "CFavourites::Load - no userdata favourites found, skipping"); return true; } bool CFavouritesDirectory::LoadFavourites(const std::string& strPath, CFileItemList& items) { CXBMCTinyXML doc; if (!doc.LoadFile(strPath)) { CLog::Log(LOGERROR, "Unable to load %s (row %i column %i)", strPath.c_str(), doc.Row(), doc.Column()); return false; } TiXmlElement *root = doc.RootElement(); if (!root || strcmp(root->Value(), "favourites")) { CLog::Log(LOGERROR, "Favourites.xml doesn't contain the <favourites> root element"); return false; } TiXmlElement *favourite = root->FirstChildElement("favourite"); while (favourite) { // format: // <favourite name="Cool Video" thumb="foo.jpg">PlayMedia(c:\videos\cool_video.avi)</favourite> // <favourite name="My Album" thumb="bar.tbn">ActivateWindow(MyMusic,c:\music\my album)</favourite> // <favourite name="Apple Movie Trailers" thumb="path_to_thumb.png">RunScript(special://xbmc/scripts/apple movie trailers/default.py)</favourite> const char *name = favourite->Attribute("name"); const char *thumb = favourite->Attribute("thumb"); if (name && favourite->FirstChild()) { if(!items.Contains(favourite->FirstChild()->Value())) { CFileItemPtr item(new CFileItem(name)); item->SetPath(favourite->FirstChild()->Value()); if (thumb) item->SetArt("thumb", thumb); items.Add(item); } } favourite = favourite->NextSiblingElement("favourite"); } return true; } bool CFavouritesDirectory::Save(const CFileItemList &items) { std::string favourites; CXBMCTinyXML doc; TiXmlElement xmlRootElement("favourites"); TiXmlNode *rootNode = doc.InsertEndChild(xmlRootElement); if (!rootNode) return false; for (int i = 0; i < items.Size(); i++) { const CFileItemPtr item = items[i]; TiXmlElement favNode("favourite"); favNode.SetAttribute("name", item->GetLabel().c_str()); if (item->HasArt("thumb")) favNode.SetAttribute("thumb", item->GetArt("thumb").c_str()); TiXmlText execute(item->GetPath()); favNode.InsertEndChild(execute); rootNode->InsertEndChild(favNode); } favourites = URIUtils::AddFileToFolder(CProfilesManager::GetInstance().GetProfileUserDataFolder(), "favourites.xml"); return doc.SaveFile(favourites); } bool CFavouritesDirectory::AddOrRemove(CFileItem *item, int contextWindow) { if (!item) return false; // load our list CFileItemList items; Load(items); std::string executePath(GetExecutePath(*item, contextWindow)); CFileItemPtr match = items.Get(executePath); if (match) { // remove the item items.Remove(match.get()); } else { // create our new favourite item CFileItemPtr favourite(new CFileItem(item->GetLabel())); if (item->GetLabel().empty()) favourite->SetLabel(CUtil::GetTitleFromPath(item->GetPath(), item->m_bIsFolder)); favourite->SetArt("thumb", item->GetArt("thumb")); favourite->SetPath(executePath); items.Add(favourite); } // and save our list again return Save(items); } bool CFavouritesDirectory::IsFavourite(CFileItem *item, int contextWindow) { CFileItemList items; if (!Load(items)) return false; return items.Contains(GetExecutePath(*item, contextWindow)); } std::string CFavouritesDirectory::GetExecutePath(const CFileItem &item, int contextWindow) { return GetExecutePath(item, StringUtils::Format("%i", contextWindow)); } std::string CFavouritesDirectory::GetExecutePath(const CFileItem &item, const std::string &contextWindow) { std::string execute; if (item.m_bIsFolder && (g_advancedSettings.m_playlistAsFolders || !(item.IsSmartPlayList() || item.IsPlayList()))) { if (!contextWindow.empty()) execute = StringUtils::Format("ActivateWindow(%s,%s,return)", contextWindow.c_str(), StringUtils::Paramify(item.GetPath()).c_str()); } /* TODO:STRING_CLEANUP */ else if (item.IsScript() && item.GetPath().size() > 9) // plugin://<foo> execute = StringUtils::Format("RunScript(%s)", StringUtils::Paramify(item.GetPath().substr(9)).c_str()); else if (item.IsAndroidApp() && item.GetPath().size() > 26) // androidapp://sources/apps/<foo> execute = StringUtils::Format("StartAndroidActivity(%s)", StringUtils::Paramify(item.GetPath().substr(26)).c_str()); else // assume a media file { if (item.IsVideoDb() && item.HasVideoInfoTag()) execute = StringUtils::Format("PlayMedia(%s)", StringUtils::Paramify(item.GetVideoInfoTag()->m_strFileNameAndPath).c_str()); else if (item.IsMusicDb() && item.HasMusicInfoTag()) execute = StringUtils::Format("PlayMedia(%s)", StringUtils::Paramify(item.GetMusicInfoTag()->GetURL()).c_str()); else if (item.IsPicture()) execute = StringUtils::Format("ShowPicture(%s)", StringUtils::Paramify(item.GetPath()).c_str()); else execute = StringUtils::Format("PlayMedia(%s)", StringUtils::Paramify(item.GetPath()).c_str()); } return execute; } }
34.802817
149
0.699987
krattai
bd835e711c819860aecaaf8983c4ca5097b3fa0d
7,142
cpp
C++
src/rogui.cpp
lucasw/rogui
175896fb1236c839c17b325687cd7e3395fe0133
[ "BSD-3-Clause" ]
3
2019-10-02T07:40:44.000Z
2020-03-26T15:57:01.000Z
src/rogui.cpp
lucasw/rogui
175896fb1236c839c17b325687cd7e3395fe0133
[ "BSD-3-Clause" ]
1
2019-04-07T22:56:02.000Z
2019-04-08T00:51:53.000Z
src/rogui.cpp
lucasw/rogui
175896fb1236c839c17b325687cd7e3395fe0133
[ "BSD-3-Clause" ]
null
null
null
#include <iostream> #include <rogui/map.hpp> #include <rogui/rogui.hpp> #include <rogui/utility.hpp> #if 0 #include <opencv2/highgui.hpp> #include <opencv2/imgproc.hpp> #endif #define IMGUI_DEFINE_MATH_OPERATORS #include <imgui_internal.h> namespace rogui { Player::Player(const std::string& name) : Character(name) { // TODO(lucasw) eventually these need to be context specific, what menu is being used key_actions_.insert(std::make_pair(SDLK_h, std::bind(&Player::move, this, -1, 0))); key_actions_.insert(std::make_pair(SDLK_j, std::bind(&Player::move, this, 0, 1))); key_actions_.insert(std::make_pair(SDLK_k, std::bind(&Player::move, this, 0, -1))); key_actions_.insert(std::make_pair(SDLK_l, std::bind(&Player::move, this, 1, 0))); key_actions_.insert(std::make_pair(SDLK_y, std::bind(&Player::move, this, -1, -1))); key_actions_.insert(std::make_pair(SDLK_u, std::bind(&Player::move, this, 1, -1))); key_actions_.insert(std::make_pair(SDLK_b, std::bind(&Player::move, this, -1, 1))); key_actions_.insert(std::make_pair(SDLK_n, std::bind(&Player::move, this, 1, 1))); } void Player::handleKey(const SDL_Keycode& key) { if (key_actions_.count(key) > 0) { key_actions_.at(key)(); } } #if 0 bool Player::move(const int dx, const int dy) { const int tmp_x = x_ + dx; const int tmp_y = y_ + dy; // std::cout << dx << " " << dy << "\n"; if (auto map = map_.lock()) { // TODO(lucasw) later passability will depend on player traits if (map->passable(tmp_x, tmp_y)) { x_ = tmp_x; y_ = tmp_y; return true; } } return false; } void Player::draw(const ImVec2 window_offset, const float scale) { // ImDrawList* draw_list = ImGui::GetWindowDrawList(); const float screen_x = window_offset.x + x_ * scale; const float screen_y = window_offset.y + y_ * scale; // TODO(lucasw) change font size based on scale - but do it once // at beginning of map draw and then restore default. ImGui::SetCursorScreenPos(ImVec2(screen_x + scale * 0.3, screen_y + scale * 0.1)); // TODO(lucasw) text color ImGui::Text("%c", sym_); } #endif ////////////////////////////////////////////////////////////////////////// Rogui::Rogui(const ImVec2 size) : size_(size) { std::cout << "#### Rogui ####\n"; window_flags_ = ImGuiWindowFlags_NoCollapse | ImGuiWindowFlags_NoMove | ImGuiWindowFlags_NoResize | ImGuiWindowFlags_NoTitleBar | ImGuiWindowFlags_HorizontalScrollbar; map_ = std::make_shared<Map>(8 * 8, 8 * 5); generateInit(map_); // generateRandom(map_); generateDucci(map_); populateMap(map_); player_ = std::make_shared<Player>("player"); player_->sym_ = '@'; player_->map_ = map_; player_->x_ = map_->width_ / 2; player_->y_ = map_->height_ / 2; // TODO(lucasw) probably should decouple maps and views into maps, // only the latter would map_->player_ = player_; map_->characters_.push_back(player_); msg_.reserve(80 * 20); } #if 0 bool Rogui::droppedFile(const std::string name) { if (name == "") return false; try { land_ = std::make_shared<Land>(name); } catch (std::runtime_error& ex) { msg_ = std::string(ex.what()); return false; } msg_ = "loaded new map " + name; return true; } #endif void Rogui::update(const std::vector<SDL_Keycode>& key_presses) { // map_->update(); for (const auto& key : key_presses) { player_->handleKey(key); } } void Rogui::drawImage() { #if 0 if (!land_) { return; } if (land_->image_.empty()) return; cv::Mat image = land_->image_; ImGuiIO& io = ImGui::GetIO(); (void)io; ImVec2 image_size; image_size.x = image.cols * zoom_; image_size.y = image.rows * zoom_; ImVec2 win_sz = ImGui::GetWindowSize(); // bool dirty = false; float region_width = ImGui::GetWindowContentRegionWidth(); // const ImVec2 uv0(-10.0, -10.0); // = win_sz * 0.5 - image_size * 0.5; // const ImVec2 uv1(10.0, 10.0); // = win_sz * 0.5 + image_size * 0.5; // ImGui::Text("%f %f, %f %f", win_sz.x, win_sz.y, pos.x, pos.y); if (image_size.x < region_width) { ImGui::SetCursorPosX((region_width - image_size.x) * 0.5); } // float region_height = ImGui::GetWindowContentRegionHeight(); float region_height = win_sz.y; if (image_size.y < region_height) { ImGui::SetCursorPosY((region_height - image_size.y) * 0.5); } ImVec2 screen_pos1 = ImGui::GetCursorScreenPos(); ImGui::Image((void*)(intptr_t)texture_id_, image_size); // , uv0, uv1); ImGuiWindow* window = ImGui::GetCurrentWindow(); ImGuiID active_id = ImGui::GetActiveID(); const bool any_scrollbar_active = active_id && (active_id == ImGui::GetScrollbarID(window, ImGuiAxis_X) || active_id == ImGui::GetScrollbarID(window, ImGuiAxis_Y)); if (!any_scrollbar_active) { ImVec2 image_pos = (io.MousePos - screen_pos1) / zoom_; int x = image_pos.x; int y = image_pos.y; bool clicked = ImGui::IsMouseDown(0); if ((x >= 0) && (y >= 0) && (x < land_->image_.cols) && (y < land_->image_.rows)) { // mouse_over_image = true; if (clicked) { // make new Person msg_ = "making new person " + std::to_string(x) + " " + std::to_string(y) + " " + spawn_types_[spawn_ind_]; const std::string nation = spawn_types_[spawn_ind_]; land_->addPerson(x, y, nation); } } } #endif } void Rogui::draw() { bool is_open = true; // draw the map { ImGui::SetNextWindowPos(pos_); const float map_x = size_.x * 0.75; const float map_y = size_.y * 0.75; ImGui::SetNextWindowSize(ImVec2(map_x, map_y)); ImGui::Begin("##map view", &is_open, window_flags_); // TODO(lucasw) get this from gui const float scale = 16.0; const int grid_x = 0; const int grid_y = 0; const size_t grid_width = map_x / scale; const size_t grid_height = map_y / scale; map_->draw(grid_x, grid_y, grid_width, grid_height, scale); ImGui::End(); } // draw the controls and status to the right // draw the console on the bottom #if 0 ImGui::Begin("##controls", &is_open, window_flags_); if (is_open) { if (ImGui::Button("reset")) { land_->resetPeople(); } // ImGui::SliderInt("ticks between updates", &land_.ticks_to_move_, 1, 100); } ImGui::Text("%s", msg_.c_str()); if (land_) { for(const auto& people_pair : land_->num_peoples_) { ImGui::Text("%s %lu peoples", people_pair.first.c_str(), people_pair.second); } ImGui::Text("image %d x %d", land_->image_.cols, land_->image_.rows); ImGui::Text("map %d x %d", land_->map_.cols, land_->map_.rows); ImGui::Combo("spawn type", &spawn_ind_, "Red\0Blue\0"); } ImGui::End(); ImGui::SetNextWindowPos(ImVec2(pos_.x + size_.x * 0.25, pos_.y)); ImGui::SetNextWindowSize(ImVec2(size_.x * 0.75, size_.y)); ImGui::Begin("##automata", &is_open, window_flags_); if (is_open) { if ((land_) && (!land_->map_.empty())) { msg_ = "updating land and people"; // TODO(lucasw) if updated land_->draw(); glTexFromMat(land_->image_, texture_id_); drawImage(); } } ImGui::End(); #endif } } // namespace rogui
29.758333
87
0.637777
lucasw