blob_id
stringlengths
40
40
directory_id
stringlengths
40
40
path
stringlengths
3
264
content_id
stringlengths
40
40
detected_licenses
listlengths
0
85
license_type
stringclasses
2 values
repo_name
stringlengths
5
140
snapshot_id
stringlengths
40
40
revision_id
stringlengths
40
40
branch_name
stringclasses
986 values
visit_date
timestamp[us]
revision_date
timestamp[us]
committer_date
timestamp[us]
github_id
int64
3.89k
681M
star_events_count
int64
0
209k
fork_events_count
int64
0
110k
gha_license_id
stringclasses
23 values
gha_event_created_at
timestamp[us]
gha_created_at
timestamp[us]
gha_language
stringclasses
145 values
src_encoding
stringclasses
34 values
language
stringclasses
1 value
is_vendor
bool
1 class
is_generated
bool
2 classes
length_bytes
int64
3
10.4M
extension
stringclasses
122 values
content
stringlengths
3
10.4M
authors
listlengths
1
1
author_id
stringlengths
0
158
b4839835e3d88d9dace058cec1763c9cad7a1f1d
ec9d278be872a4202dd918512c55ba317e93b65e
/homework/02.Per-fragment Phong Shading/Camera.cpp
d936a357a1852c30e1426dd3df83da5b7730796c
[]
no_license
hyungoo-kang-kmucs/graphics
7f43fcddf87ca9c05132d0f56c334b894a1f176f
4aae1d873c456401ab5f5010ad72a5d41ed2c2af
refs/heads/master
2020-04-30T14:45:29.957317
2019-05-23T04:26:27
2019-05-23T04:26:27
176,901,227
0
0
null
2019-03-21T08:24:31
2019-03-21T08:24:30
null
UTF-8
C++
false
false
906
cpp
#include "Camera.h" #include "transform.hpp" const Camera::vec3 Camera::center_position() const { return vec3(position_[0] + front_dir_[0], position_[1] + front_dir_[1], position_[2] + front_dir_[2]); } // TODO: fill up the following functions properly void Camera::move_forward(float delta) { position_ += delta * front_dir_; } void Camera::move_backward(float delta) { move_forward(-delta); } void Camera::move_left(float delta) { position_ -= delta * right_dir_; } void Camera::move_right(float delta) { move_left(-delta); } void Camera::move_up(float delta) { position_ += delta * up_dir_; } void Camera::move_down(float delta) { move_up(-delta); } void Camera::pitch(float delta) { // TODO: fill up this function properly } void Camera::yaw(float delta) { // TODO: fill up this function properly } void Camera::roll(float delta) { // TODO: fill up this function properly }
[ "noreply@github.com" ]
hyungoo-kang-kmucs.noreply@github.com
932c663aaba9275596621c5082e57fba21ca836a
e7f4c25dc251fd6b74efa7014c3d271724536797
/test/encodings/unicode_group_S_u_encoding_policy_substitute.re
119d99810ebcba551da8fb5e96f0442d8eaf8dab
[ "LicenseRef-scancode-warranty-disclaimer", "LicenseRef-scancode-public-domain" ]
permissive
nightlark/re2c
163cc308e9023b290e08cc82cc704a8ae5b90114
96104a652622c63ca2cc0b1d2b1d3dad8c34aae6
refs/heads/master
2023-08-08T18:35:31.715463
2023-07-21T21:23:56
2023-07-21T21:29:45
100,122,233
1
0
null
2017-08-12T15:51:24
2017-08-12T15:51:24
null
UTF-8
C++
false
false
8,344
re
// re2c $INPUT -o $OUTPUT -u --encoding-policy substitute #include <stdio.h> #define YYCTYPE unsigned int bool scan(const YYCTYPE * start, const YYCTYPE * const limit) { __attribute__((unused)) const YYCTYPE * YYMARKER; // silence compiler warnings when YYMARKER is not used # define YYCURSOR start S: /*!re2c re2c:yyfill:enable = 0; S = [\x24-\x24\x2b-\x2b\x3c-\x3e\x5e-\x5e\x60-\x60\x7c-\x7c\x7e-\x7e\xa2-\xa6\xa8-\xa9\xac-\xac\xae-\xb1\xb4-\xb4\xb8-\xb8\xd7-\xd7\xf7-\xf7\u02c2-\u02c5\u02d2-\u02df\u02e5-\u02eb\u02ed-\u02ed\u02ef-\u02ff\u0375-\u0375\u0384-\u0385\u03f6-\u03f6\u0482-\u0482\u058d-\u058f\u0606-\u0608\u060b-\u060b\u060e-\u060f\u06de-\u06de\u06e9-\u06e9\u06fd-\u06fe\u07f6-\u07f6\u07fe-\u07ff\u09f2-\u09f3\u09fa-\u09fb\u0af1-\u0af1\u0b70-\u0b70\u0bf3-\u0bfa\u0c7f-\u0c7f\u0d4f-\u0d4f\u0d79-\u0d79\u0e3f-\u0e3f\u0f01-\u0f03\u0f13-\u0f13\u0f15-\u0f17\u0f1a-\u0f1f\u0f34-\u0f34\u0f36-\u0f36\u0f38-\u0f38\u0fbe-\u0fc5\u0fc7-\u0fcc\u0fce-\u0fcf\u0fd5-\u0fd8\u109e-\u109f\u1390-\u1399\u166d-\u166d\u17db-\u17db\u1940-\u1940\u19de-\u19ff\u1b61-\u1b6a\u1b74-\u1b7c\u1fbd-\u1fbd\u1fbf-\u1fc1\u1fcd-\u1fcf\u1fdd-\u1fdf\u1fed-\u1fef\u1ffd-\u1ffe\u2044-\u2044\u2052-\u2052\u207a-\u207c\u208a-\u208c\u20a0-\u20bf\u2100-\u2101\u2103-\u2106\u2108-\u2109\u2114-\u2114\u2116-\u2118\u211e-\u2123\u2125-\u2125\u2127-\u2127\u2129-\u2129\u212e-\u212e\u213a-\u213b\u2140-\u2144\u214a-\u214d\u214f-\u214f\u218a-\u218b\u2190-\u2307\u230c-\u2328\u232b-\u2426\u2440-\u244a\u249c-\u24e9\u2500-\u2767\u2794-\u27c4\u27c7-\u27e5\u27f0-\u2982\u2999-\u29d7\u29dc-\u29fb\u29fe-\u2b73\u2b76-\u2b95\u2b98-\u2bff\u2ce5-\u2cea\u2e80-\u2e99\u2e9b-\u2ef3\u2f00-\u2fd5\u2ff0-\u2ffb\u3004-\u3004\u3012-\u3013\u3020-\u3020\u3036-\u3037\u303e-\u303f\u309b-\u309c\u3190-\u3191\u3196-\u319f\u31c0-\u31e3\u3200-\u321e\u322a-\u3247\u3250-\u3250\u3260-\u327f\u328a-\u32b0\u32c0-\u33ff\u4dc0-\u4dff\ua490-\ua4c6\ua700-\ua716\ua720-\ua721\ua789-\ua78a\ua828-\ua82b\ua836-\ua839\uaa77-\uaa79\uab5b-\uab5b\ufb29-\ufb29\ufbb2-\ufbc1\ufdfc-\ufdfd\ufe62-\ufe62\ufe64-\ufe66\ufe69-\ufe69\uff04-\uff04\uff0b-\uff0b\uff1c-\uff1e\uff3e-\uff3e\uff40-\uff40\uff5c-\uff5c\uff5e-\uff5e\uffe0-\uffe6\uffe8-\uffee\ufffc-\ufffd\U00010137-\U0001013f\U00010179-\U00010189\U0001018c-\U0001018e\U00010190-\U0001019b\U000101a0-\U000101a0\U000101d0-\U000101fc\U00010877-\U00010878\U00010ac8-\U00010ac8\U0001173f-\U0001173f\U00011fd5-\U00011ff1\U00016b3c-\U00016b3f\U00016b45-\U00016b45\U0001bc9c-\U0001bc9c\U0001d000-\U0001d0f5\U0001d100-\U0001d126\U0001d129-\U0001d164\U0001d16a-\U0001d16c\U0001d183-\U0001d184\U0001d18c-\U0001d1a9\U0001d1ae-\U0001d1e8\U0001d200-\U0001d241\U0001d245-\U0001d245\U0001d300-\U0001d356\U0001d6c1-\U0001d6c1\U0001d6db-\U0001d6db\U0001d6fb-\U0001d6fb\U0001d715-\U0001d715\U0001d735-\U0001d735\U0001d74f-\U0001d74f\U0001d76f-\U0001d76f\U0001d789-\U0001d789\U0001d7a9-\U0001d7a9\U0001d7c3-\U0001d7c3\U0001d800-\U0001d9ff\U0001da37-\U0001da3a\U0001da6d-\U0001da74\U0001da76-\U0001da83\U0001da85-\U0001da86\U0001e14f-\U0001e14f\U0001e2ff-\U0001e2ff\U0001ecac-\U0001ecac\U0001ecb0-\U0001ecb0\U0001ed2e-\U0001ed2e\U0001eef0-\U0001eef1\U0001f000-\U0001f02b\U0001f030-\U0001f093\U0001f0a0-\U0001f0ae\U0001f0b1-\U0001f0bf\U0001f0c1-\U0001f0cf\U0001f0d1-\U0001f0f5\U0001f110-\U0001f16c\U0001f170-\U0001f1ac\U0001f1e6-\U0001f202\U0001f210-\U0001f23b\U0001f240-\U0001f248\U0001f250-\U0001f251\U0001f260-\U0001f265\U0001f300-\U0001f6d5\U0001f6e0-\U0001f6ec\U0001f6f0-\U0001f6fa\U0001f700-\U0001f773\U0001f780-\U0001f7d8\U0001f7e0-\U0001f7eb\U0001f800-\U0001f80b\U0001f810-\U0001f847\U0001f850-\U0001f859\U0001f860-\U0001f887\U0001f890-\U0001f8ad\U0001f900-\U0001f90b\U0001f90d-\U0001f971\U0001f973-\U0001f976\U0001f97a-\U0001f9a2\U0001f9a5-\U0001f9aa\U0001f9ae-\U0001f9ca\U0001f9cd-\U0001fa53\U0001fa60-\U0001fa6d\U0001fa70-\U0001fa73\U0001fa78-\U0001fa7a\U0001fa80-\U0001fa82\U0001fa90-\U0001fa95]; S { goto S; } * { return YYCURSOR == limit; } */ } static const unsigned int chars_S [] = {0x24,0x24, 0x2b,0x2b, 0x3c,0x3e, 0x5e,0x5e, 0x60,0x60, 0x7c,0x7c, 0x7e,0x7e, 0xa2,0xa6, 0xa8,0xa9, 0xac,0xac, 0xae,0xb1, 0xb4,0xb4, 0xb8,0xb8, 0xd7,0xd7, 0xf7,0xf7, 0x2c2,0x2c5, 0x2d2,0x2df, 0x2e5,0x2eb, 0x2ed,0x2ed, 0x2ef,0x2ff, 0x375,0x375, 0x384,0x385, 0x3f6,0x3f6, 0x482,0x482, 0x58d,0x58f, 0x606,0x608, 0x60b,0x60b, 0x60e,0x60f, 0x6de,0x6de, 0x6e9,0x6e9, 0x6fd,0x6fe, 0x7f6,0x7f6, 0x7fe,0x7ff, 0x9f2,0x9f3, 0x9fa,0x9fb, 0xaf1,0xaf1, 0xb70,0xb70, 0xbf3,0xbfa, 0xc7f,0xc7f, 0xd4f,0xd4f, 0xd79,0xd79, 0xe3f,0xe3f, 0xf01,0xf03, 0xf13,0xf13, 0xf15,0xf17, 0xf1a,0xf1f, 0xf34,0xf34, 0xf36,0xf36, 0xf38,0xf38, 0xfbe,0xfc5, 0xfc7,0xfcc, 0xfce,0xfcf, 0xfd5,0xfd8, 0x109e,0x109f, 0x1390,0x1399, 0x166d,0x166d, 0x17db,0x17db, 0x1940,0x1940, 0x19de,0x19ff, 0x1b61,0x1b6a, 0x1b74,0x1b7c, 0x1fbd,0x1fbd, 0x1fbf,0x1fc1, 0x1fcd,0x1fcf, 0x1fdd,0x1fdf, 0x1fed,0x1fef, 0x1ffd,0x1ffe, 0x2044,0x2044, 0x2052,0x2052, 0x207a,0x207c, 0x208a,0x208c, 0x20a0,0x20bf, 0x2100,0x2101, 0x2103,0x2106, 0x2108,0x2109, 0x2114,0x2114, 0x2116,0x2118, 0x211e,0x2123, 0x2125,0x2125, 0x2127,0x2127, 0x2129,0x2129, 0x212e,0x212e, 0x213a,0x213b, 0x2140,0x2144, 0x214a,0x214d, 0x214f,0x214f, 0x218a,0x218b, 0x2190,0x2307, 0x230c,0x2328, 0x232b,0x2426, 0x2440,0x244a, 0x249c,0x24e9, 0x2500,0x2767, 0x2794,0x27c4, 0x27c7,0x27e5, 0x27f0,0x2982, 0x2999,0x29d7, 0x29dc,0x29fb, 0x29fe,0x2b73, 0x2b76,0x2b95, 0x2b98,0x2bff, 0x2ce5,0x2cea, 0x2e80,0x2e99, 0x2e9b,0x2ef3, 0x2f00,0x2fd5, 0x2ff0,0x2ffb, 0x3004,0x3004, 0x3012,0x3013, 0x3020,0x3020, 0x3036,0x3037, 0x303e,0x303f, 0x309b,0x309c, 0x3190,0x3191, 0x3196,0x319f, 0x31c0,0x31e3, 0x3200,0x321e, 0x322a,0x3247, 0x3250,0x3250, 0x3260,0x327f, 0x328a,0x32b0, 0x32c0,0x33ff, 0x4dc0,0x4dff, 0xa490,0xa4c6, 0xa700,0xa716, 0xa720,0xa721, 0xa789,0xa78a, 0xa828,0xa82b, 0xa836,0xa839, 0xaa77,0xaa79, 0xab5b,0xab5b, 0xfb29,0xfb29, 0xfbb2,0xfbc1, 0xfdfc,0xfdfd, 0xfe62,0xfe62, 0xfe64,0xfe66, 0xfe69,0xfe69, 0xff04,0xff04, 0xff0b,0xff0b, 0xff1c,0xff1e, 0xff3e,0xff3e, 0xff40,0xff40, 0xff5c,0xff5c, 0xff5e,0xff5e, 0xffe0,0xffe6, 0xffe8,0xffee, 0xfffc,0xfffd, 0x10137,0x1013f, 0x10179,0x10189, 0x1018c,0x1018e, 0x10190,0x1019b, 0x101a0,0x101a0, 0x101d0,0x101fc, 0x10877,0x10878, 0x10ac8,0x10ac8, 0x1173f,0x1173f, 0x11fd5,0x11ff1, 0x16b3c,0x16b3f, 0x16b45,0x16b45, 0x1bc9c,0x1bc9c, 0x1d000,0x1d0f5, 0x1d100,0x1d126, 0x1d129,0x1d164, 0x1d16a,0x1d16c, 0x1d183,0x1d184, 0x1d18c,0x1d1a9, 0x1d1ae,0x1d1e8, 0x1d200,0x1d241, 0x1d245,0x1d245, 0x1d300,0x1d356, 0x1d6c1,0x1d6c1, 0x1d6db,0x1d6db, 0x1d6fb,0x1d6fb, 0x1d715,0x1d715, 0x1d735,0x1d735, 0x1d74f,0x1d74f, 0x1d76f,0x1d76f, 0x1d789,0x1d789, 0x1d7a9,0x1d7a9, 0x1d7c3,0x1d7c3, 0x1d800,0x1d9ff, 0x1da37,0x1da3a, 0x1da6d,0x1da74, 0x1da76,0x1da83, 0x1da85,0x1da86, 0x1e14f,0x1e14f, 0x1e2ff,0x1e2ff, 0x1ecac,0x1ecac, 0x1ecb0,0x1ecb0, 0x1ed2e,0x1ed2e, 0x1eef0,0x1eef1, 0x1f000,0x1f02b, 0x1f030,0x1f093, 0x1f0a0,0x1f0ae, 0x1f0b1,0x1f0bf, 0x1f0c1,0x1f0cf, 0x1f0d1,0x1f0f5, 0x1f110,0x1f16c, 0x1f170,0x1f1ac, 0x1f1e6,0x1f202, 0x1f210,0x1f23b, 0x1f240,0x1f248, 0x1f250,0x1f251, 0x1f260,0x1f265, 0x1f300,0x1f6d5, 0x1f6e0,0x1f6ec, 0x1f6f0,0x1f6fa, 0x1f700,0x1f773, 0x1f780,0x1f7d8, 0x1f7e0,0x1f7eb, 0x1f800,0x1f80b, 0x1f810,0x1f847, 0x1f850,0x1f859, 0x1f860,0x1f887, 0x1f890,0x1f8ad, 0x1f900,0x1f90b, 0x1f90d,0x1f971, 0x1f973,0x1f976, 0x1f97a,0x1f9a2, 0x1f9a5,0x1f9aa, 0x1f9ae,0x1f9ca, 0x1f9cd,0x1fa53, 0x1fa60,0x1fa6d, 0x1fa70,0x1fa73, 0x1fa78,0x1fa7a, 0x1fa80,0x1fa82, 0x1fa90,0x1fa95, 0x0,0x0}; static unsigned int encode_utf32 (const unsigned int * ranges, unsigned int ranges_count, unsigned int * s) { unsigned int * const s_start = s; for (unsigned int i = 0; i < ranges_count; i += 2) for (unsigned int j = ranges[i]; j <= ranges[i + 1]; ++j) *s++ = j; return s - s_start; } int main () { unsigned int * buffer_S = new unsigned int [7293]; YYCTYPE * s = (YYCTYPE *) buffer_S; unsigned int buffer_len = encode_utf32 (chars_S, sizeof (chars_S) / sizeof (unsigned int), buffer_S); /* convert 32-bit code units to YYCTYPE; reuse the same buffer */ for (unsigned int i = 0; i < buffer_len; ++i) s[i] = buffer_S[i]; if (!scan (s, s + buffer_len)) printf("test 'S' failed\n"); delete [] buffer_S; return 0; }
[ "skvadrik@gmail.com" ]
skvadrik@gmail.com
5919291e78afd731ec9ed4108904d7182a5af82a
756953bd7487da84962013ed4efc19a5ed2561a5
/src/modules/mmnetwork.cpp
20e14a4458025579829ceeb0e73c5c960b69b427
[]
no_license
Dummiesman/mm2hook
a4ade067fdc981ea4accde5dbfeb7653b2b5247f
511c96a24b88f3210791dd8ea668fb377b02c4f5
refs/heads/master
2023-08-19T05:39:17.219544
2023-08-10T15:32:00
2023-08-10T15:32:00
93,969,666
2
0
null
2017-06-10T22:53:27
2017-06-10T22:53:27
null
UTF-8
C++
false
false
51
cpp
#include <modules\mmnetwork.h> using namespace MM2;
[ "aaro4130@gmail.com" ]
aaro4130@gmail.com
d28db5ca2d50f2ba57c7303635c979beb841a8a6
a607d5ed2d93f569a9f5fef5904194235b08daa2
/test/OpenSpaceToolkit/Physics/Units/Derived/Angle.test.cpp
5690a9a78fab9c088b8bf985733c21e8f90d94c4
[ "MPL-2.0", "BSL-1.0", "Apache-2.0" ]
permissive
verstaen/open-space-toolkit-physics
da353fc122aa341787612ac7e405d7a11915b622
ca55011fd0de9aadacad84317fdce06985e5dbd8
refs/heads/master
2021-02-18T21:02:43.657790
2020-11-06T15:29:41
2020-11-06T15:29:41
245,236,749
0
0
Apache-2.0
2020-03-05T18:18:38
2020-03-05T18:18:37
null
UTF-8
C++
false
false
49,473
cpp
//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// /// @project Open Space Toolkit ▸ Physics /// @file OpenSpaceToolkit/Physics/Units/Derived/Angle.test.cpp /// @author Lucas Brémond <lucas@loftorbital.com> /// @license Apache License 2.0 //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// #include <OpenSpaceToolkit/Physics/Units/Derived/Angle.hpp> #include <OpenSpaceToolkit/Mathematics/Geometry/Angle.hpp> #include <OpenSpaceToolkit/Core/Types/Real.hpp> #include <Global.test.hpp> //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////// TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Constructor) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { const Real value = 123.456 ; const Angle::Unit unit = Angle::Unit::Radian ; EXPECT_NO_THROW(Angle(value, unit)) ; } { const Real value = Real::Undefined() ; const Angle::Unit unit = Angle::Unit::Undefined ; EXPECT_NO_THROW(Angle(value, unit)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, EqualToOperator) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_TRUE(Angle(0.0, Angle::Unit::Radian) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(+1.0, Angle::Unit::Radian) == Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(-1.0, Angle::Unit::Radian) == Angle(-1.0, Angle::Unit::Radian)) ; } { EXPECT_TRUE(Angle(0.0, Angle::Unit::Radian) == Angle(Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(0.0, Angle::Unit::Radian) == Angle(2.0 * Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(0.0, Angle::Unit::Radian) == Angle(4.0 * Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(Real::TwoPi(), Angle::Unit::Radian) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(Real::TwoPi(), Angle::Unit::Radian) == Angle(Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(Real::TwoPi(), Angle::Unit::Radian) == Angle(2.0 * Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(Real::TwoPi(), Angle::Unit::Radian) == Angle(4.0 * Real::TwoPi(), Angle::Unit::Radian)) ; } { EXPECT_TRUE(Angle(0.0, Angle::Unit::Degree) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(0.0, Angle::Unit::Arcminute) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(0.0, Angle::Unit::Arcsecond) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(0.0, Angle::Unit::Revolution) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(90.0, Angle::Unit::Degree) == Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(5400.0, Angle::Unit::Arcminute) == Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(324000.0, Angle::Unit::Arcsecond) == Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(0.25, Angle::Unit::Revolution) == Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(360.0, Angle::Unit::Degree) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(21600.0, Angle::Unit::Arcminute) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(1296000.0, Angle::Unit::Arcsecond) == Angle(0.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(1.0, Angle::Unit::Revolution) == Angle(0.0, Angle::Unit::Radian)) ; } { EXPECT_FALSE(Angle(1.0, Angle::Unit::Radian) == Angle(2.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(+1.0, Angle::Unit::Radian) == Angle(-1.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle::Undefined() == Angle(1.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(1.0, Angle::Unit::Radian) == Angle::Undefined()) ; EXPECT_FALSE(Angle::Undefined() == Angle::Undefined()) ; } { EXPECT_FALSE(Angle(90.0, Angle::Unit::Degree) == Angle(Real::Pi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(5400.0, Angle::Unit::Arcminute) == Angle(Real::Pi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(324000.0, Angle::Unit::Arcsecond) == Angle(Real::Pi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(0.25, Angle::Unit::Revolution) == Angle(Real::Pi(), Angle::Unit::Radian)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, NotEqualToOperator) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_TRUE(Angle(1.0, Angle::Unit::Radian) != Angle(2.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(+1.0, Angle::Unit::Radian) != Angle(-1.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle::Undefined() != Angle(1.0, Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(1.0, Angle::Unit::Radian) != Angle::Undefined()) ; EXPECT_TRUE(Angle::Undefined() != Angle::Undefined()) ; } { EXPECT_TRUE(Angle(90.0, Angle::Unit::Degree) != Angle(Real::Pi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(5400.0, Angle::Unit::Arcminute) != Angle(Real::Pi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(324000.0, Angle::Unit::Arcsecond) != Angle(Real::Pi(), Angle::Unit::Radian)) ; EXPECT_TRUE(Angle(0.25, Angle::Unit::Revolution) != Angle(Real::Pi(), Angle::Unit::Radian)) ; } { EXPECT_FALSE(Angle(0.0, Angle::Unit::Radian) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(+1.0, Angle::Unit::Radian) != Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(-1.0, Angle::Unit::Radian) != Angle(-1.0, Angle::Unit::Radian)) ; } { EXPECT_FALSE(Angle(0.0, Angle::Unit::Radian) != Angle(Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(0.0, Angle::Unit::Radian) != Angle(2.0 * Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(0.0, Angle::Unit::Radian) != Angle(4.0 * Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(Real::TwoPi(), Angle::Unit::Radian) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(Real::TwoPi(), Angle::Unit::Radian) != Angle(Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(Real::TwoPi(), Angle::Unit::Radian) != Angle(2.0 * Real::TwoPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(Real::TwoPi(), Angle::Unit::Radian) != Angle(4.0 * Real::TwoPi(), Angle::Unit::Radian)) ; } { EXPECT_FALSE(Angle(0.0, Angle::Unit::Degree) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(0.0, Angle::Unit::Arcminute) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(0.0, Angle::Unit::Arcsecond) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(0.0, Angle::Unit::Revolution) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(90.0, Angle::Unit::Degree) != Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(5400.0, Angle::Unit::Arcminute) != Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(324000.0, Angle::Unit::Arcsecond) != Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(0.25, Angle::Unit::Revolution) != Angle(Real::HalfPi(), Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(360.0, Angle::Unit::Degree) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(21600.0, Angle::Unit::Arcminute) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(1296000.0, Angle::Unit::Arcsecond) != Angle(0.0, Angle::Unit::Radian)) ; EXPECT_FALSE(Angle(1.0, Angle::Unit::Revolution) != Angle(0.0, Angle::Unit::Radian)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, AdditionOperator) { using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(2.0, Angle::Unit::Radian), Angle(1.0, Angle::Unit::Radian) + Angle(1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) + Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Degree), Angle(1.0, Angle::Unit::Degree) + Angle(1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Degree), Angle(-1.0, Angle::Unit::Degree) + Angle(+1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcminute), Angle(1.0, Angle::Unit::Arcminute) + Angle(1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcminute), Angle(-1.0, Angle::Unit::Arcminute) + Angle(+1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcsecond), Angle(1.0, Angle::Unit::Arcsecond) + Angle(1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcsecond), Angle(-1.0, Angle::Unit::Arcsecond) + Angle(+1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Revolution), Angle(1.0, Angle::Unit::Revolution) + Angle(1.0, Angle::Unit::Revolution)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Revolution), Angle(-1.0, Angle::Unit::Revolution) + Angle(+1.0, Angle::Unit::Revolution)) ; } { EXPECT_EQ(Angle(2.0, Angle::Unit::Radian), Angle(2.0, Angle::Unit::Radian) + Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Degree), Angle(2.0, Angle::Unit::Degree) + Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcminute), Angle(2.0, Angle::Unit::Arcminute) + Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcsecond), Angle(2.0, Angle::Unit::Arcsecond) + Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Revolution), Angle(2.0, Angle::Unit::Revolution) + Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) + Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Degree), Angle(-2.0, Angle::Unit::Degree) + Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcminute), Angle(-2.0, Angle::Unit::Arcminute) + Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcsecond), Angle(-2.0, Angle::Unit::Arcsecond) + Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Revolution), Angle(-2.0, Angle::Unit::Revolution) + Angle::Revolutions(-3.0)) ; } { EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) + Angle(360.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) + Angle(360.0 * 60.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) + Angle(360.0 * 3600.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) + Angle(1.0, Angle::Unit::Revolution)) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) + Angle::Undefined()) ; EXPECT_ANY_THROW(Angle::Undefined() + Angle(1.0, Angle::Unit::Radian)) ; EXPECT_ANY_THROW(Angle::Undefined() + Angle::Undefined()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, SubtractionOperator) { using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(1.0, Angle::Unit::Radian) - Angle(1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) - Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Degree), Angle(1.0, Angle::Unit::Degree) - Angle(1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Degree), Angle(-1.0, Angle::Unit::Degree) - Angle(+1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcminute), Angle(1.0, Angle::Unit::Arcminute) - Angle(1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcminute), Angle(-1.0, Angle::Unit::Arcminute) - Angle(+1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcsecond), Angle(1.0, Angle::Unit::Arcsecond) - Angle(1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcsecond), Angle(-1.0, Angle::Unit::Arcsecond) - Angle(+1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Revolution), Angle(1.0, Angle::Unit::Revolution) - Angle(1.0, Angle::Unit::Revolution)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Revolution), Angle(-1.0, Angle::Unit::Revolution) - Angle(+1.0, Angle::Unit::Revolution)) ; } { EXPECT_EQ(Angle(2.0, Angle::Unit::Radian), Angle(2.0, Angle::Unit::Radian) - Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Degree), Angle(2.0, Angle::Unit::Degree) - Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcminute), Angle(2.0, Angle::Unit::Arcminute) - Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcsecond), Angle(2.0, Angle::Unit::Arcsecond) - Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Revolution), Angle(2.0, Angle::Unit::Revolution) - Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) - Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Degree), Angle(-2.0, Angle::Unit::Degree) - Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcminute), Angle(-2.0, Angle::Unit::Arcminute) - Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcsecond), Angle(-2.0, Angle::Unit::Arcsecond) - Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Revolution), Angle(-2.0, Angle::Unit::Revolution) - Angle::Revolutions(-3.0)) ; } { EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) - Angle(360.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) - Angle(360.0 * 60.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) - Angle(360.0 * 3600.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) - Angle(1.0, Angle::Unit::Revolution)) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) - Angle::Undefined()) ; EXPECT_ANY_THROW(Angle::Undefined() - Angle(1.0, Angle::Unit::Radian)) ; EXPECT_ANY_THROW(Angle::Undefined() - Angle::Undefined()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, MultiplicationOperator) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(+1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) * +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) * +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) * -1.0) ; EXPECT_EQ(Angle(+1.0, Angle::Unit::Radian), +1.0 * Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), +1.0 * Angle(-1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), -1.0 * Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(+6.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) * +3.0) ; EXPECT_EQ(Angle(-6.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) * +3.0) ; EXPECT_EQ(Angle(-6.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) * -3.0) ; EXPECT_EQ(Angle(+6.0, Angle::Unit::Radian), +2.0 * Angle(+3.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(-6.0, Angle::Unit::Radian), +2.0 * Angle(-3.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(-6.0, Angle::Unit::Radian), -2.0 * Angle(+3.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) * 0.0) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) * 0.0) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(0.0, Angle::Unit::Radian) * 0.0) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), 0.0 * Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), 0.0 * Angle(-1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), 0.0 * Angle(0.0, Angle::Unit::Radian)) ; } { EXPECT_EQ(Angle(6.0, Angle::Unit::Degree), Angle(3.0, Angle::Unit::Degree) * 2.0) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Arcminute), Angle(3.0, Angle::Unit::Arcminute) * 2.0) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Arcsecond), Angle(3.0, Angle::Unit::Arcsecond) * 2.0) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Revolution), Angle(3.0, Angle::Unit::Revolution) * 2.0) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Degree), 2.0 * Angle(3.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Arcminute), 2.0 * Angle(3.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Arcsecond), 2.0 * Angle(3.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Revolution), 2.0 * Angle(3.0, Angle::Unit::Revolution)) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) * Real::Undefined()) ; EXPECT_ANY_THROW(Real::Undefined() * Angle(1.0, Angle::Unit::Radian)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, DivisionOperator) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(+1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) / +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) / +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) / -1.0) ; EXPECT_EQ(Angle(+1.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) / +2.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) / +2.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) / -2.0) ; EXPECT_EQ(Angle(+2.0, Angle::Unit::Radian), Angle(+4.0, Angle::Unit::Radian) / +2.0) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-4.0, Angle::Unit::Radian) / +2.0) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(+4.0, Angle::Unit::Radian) / -2.0) ; } { EXPECT_EQ(Angle(0.5, Angle::Unit::Degree), Angle(1.0, Angle::Unit::Degree) / 2.0) ; EXPECT_EQ(Angle(0.5, Angle::Unit::Arcminute), Angle(1.0, Angle::Unit::Arcminute) / 2.0) ; EXPECT_EQ(Angle(0.5, Angle::Unit::Arcsecond), Angle(1.0, Angle::Unit::Arcsecond) / 2.0) ; EXPECT_EQ(Angle(0.5, Angle::Unit::Revolution), Angle(1.0, Angle::Unit::Revolution) / 2.0) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) / Real::Undefined()) ; EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) / Real::Zero()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, AdditionAssignmentOperator) { using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(2.0, Angle::Unit::Radian), Angle(1.0, Angle::Unit::Radian) += Angle(1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) += Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Degree), Angle(1.0, Angle::Unit::Degree) += Angle(1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Degree), Angle(-1.0, Angle::Unit::Degree) += Angle(+1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcminute), Angle(1.0, Angle::Unit::Arcminute) += Angle(1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcminute), Angle(-1.0, Angle::Unit::Arcminute) += Angle(+1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcsecond), Angle(1.0, Angle::Unit::Arcsecond) += Angle(1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcsecond), Angle(-1.0, Angle::Unit::Arcsecond) += Angle(+1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Revolution), Angle(1.0, Angle::Unit::Revolution) += Angle(1.0, Angle::Unit::Revolution)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Revolution), Angle(-1.0, Angle::Unit::Revolution) += Angle(+1.0, Angle::Unit::Revolution)) ; } { EXPECT_EQ(Angle(2.0, Angle::Unit::Radian), Angle(2.0, Angle::Unit::Radian) += Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Degree), Angle(2.0, Angle::Unit::Degree) += Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcminute), Angle(2.0, Angle::Unit::Arcminute) += Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcsecond), Angle(2.0, Angle::Unit::Arcsecond) += Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Revolution), Angle(2.0, Angle::Unit::Revolution) += Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) += Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Degree), Angle(-2.0, Angle::Unit::Degree) += Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcminute), Angle(-2.0, Angle::Unit::Arcminute) += Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcsecond), Angle(-2.0, Angle::Unit::Arcsecond) += Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Revolution), Angle(-2.0, Angle::Unit::Revolution) += Angle::Revolutions(-3.0)) ; } { EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) += Angle(360.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) += Angle(360.0 * 60.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) += Angle(360.0 * 3600.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) += Angle(1.0, Angle::Unit::Revolution)) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) += Angle::Undefined()) ; EXPECT_ANY_THROW(Angle::Undefined() += Angle(1.0, Angle::Unit::Radian)) ; EXPECT_ANY_THROW(Angle::Undefined() += Angle::Undefined()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, SubtractionAssignmentOperator) { using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(1.0, Angle::Unit::Radian) -= Angle(1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) -= Angle(+1.0, Angle::Unit::Radian)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Degree), Angle(1.0, Angle::Unit::Degree) -= Angle(1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Degree), Angle(-1.0, Angle::Unit::Degree) -= Angle(+1.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcminute), Angle(1.0, Angle::Unit::Arcminute) -= Angle(1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcminute), Angle(-1.0, Angle::Unit::Arcminute) -= Angle(+1.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Arcsecond), Angle(1.0, Angle::Unit::Arcsecond) -= Angle(1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcsecond), Angle(-1.0, Angle::Unit::Arcsecond) -= Angle(+1.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Revolution), Angle(1.0, Angle::Unit::Revolution) -= Angle(1.0, Angle::Unit::Revolution)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Revolution), Angle(-1.0, Angle::Unit::Revolution) -= Angle(+1.0, Angle::Unit::Revolution)) ; } { EXPECT_EQ(Angle(2.0, Angle::Unit::Radian), Angle(2.0, Angle::Unit::Radian) -= Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Degree), Angle(2.0, Angle::Unit::Degree) -= Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcminute), Angle(2.0, Angle::Unit::Arcminute) -= Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Arcsecond), Angle(2.0, Angle::Unit::Arcsecond) -= Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(2.0, Angle::Unit::Revolution), Angle(2.0, Angle::Unit::Revolution) -= Angle::Revolutions(1.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) -= Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Degree), Angle(-2.0, Angle::Unit::Degree) -= Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcminute), Angle(-2.0, Angle::Unit::Arcminute) -= Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Arcsecond), Angle(-2.0, Angle::Unit::Arcsecond) -= Angle::Revolutions(-3.0)) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Revolution), Angle(-2.0, Angle::Unit::Revolution) -= Angle::Revolutions(-3.0)) ; } { EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) -= Angle(360.0, Angle::Unit::Degree)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) -= Angle(360.0 * 60.0, Angle::Unit::Arcminute)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) -= Angle(360.0 * 3600.0, Angle::Unit::Arcsecond)) ; EXPECT_EQ(Angle(123.456, Angle::Unit::Radian), Angle(123.456, Angle::Unit::Radian) -= Angle(1.0, Angle::Unit::Revolution)) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) -= Angle::Undefined()) ; EXPECT_ANY_THROW(Angle::Undefined() -= Angle(1.0, Angle::Unit::Radian)) ; EXPECT_ANY_THROW(Angle::Undefined() -= Angle::Undefined()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, MultiplicationAssignmentOperator) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(+1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) *= +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) *= +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) *= -1.0) ; EXPECT_EQ(Angle(+6.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) *= +3.0) ; EXPECT_EQ(Angle(-6.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) *= +3.0) ; EXPECT_EQ(Angle(-6.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) *= -3.0) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) *= 0.0) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) *= 0.0) ; EXPECT_EQ(Angle(0.0, Angle::Unit::Radian), Angle(0.0, Angle::Unit::Radian) *= 0.0) ; } { EXPECT_EQ(Angle(6.0, Angle::Unit::Degree), Angle(3.0, Angle::Unit::Degree) *= 2.0) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Arcminute), Angle(3.0, Angle::Unit::Arcminute) *= 2.0) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Arcsecond), Angle(3.0, Angle::Unit::Arcsecond) *= 2.0) ; EXPECT_EQ(Angle(6.0, Angle::Unit::Revolution), Angle(3.0, Angle::Unit::Revolution) *= 2.0) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) *= Real::Undefined()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, DivisionAssignmentOperator) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(Angle(+1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) /= +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(-1.0, Angle::Unit::Radian) /= +1.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian) /= -1.0) ; EXPECT_EQ(Angle(+1.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) /= +2.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(-2.0, Angle::Unit::Radian) /= +2.0) ; EXPECT_EQ(Angle(-1.0, Angle::Unit::Radian), Angle(+2.0, Angle::Unit::Radian) /= -2.0) ; EXPECT_EQ(Angle(+2.0, Angle::Unit::Radian), Angle(+4.0, Angle::Unit::Radian) /= +2.0) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(-4.0, Angle::Unit::Radian) /= +2.0) ; EXPECT_EQ(Angle(-2.0, Angle::Unit::Radian), Angle(+4.0, Angle::Unit::Radian) /= -2.0) ; } { EXPECT_EQ(Angle(0.5, Angle::Unit::Degree), Angle(1.0, Angle::Unit::Degree) /= 2.0) ; EXPECT_EQ(Angle(0.5, Angle::Unit::Arcminute), Angle(1.0, Angle::Unit::Arcminute) /= 2.0) ; EXPECT_EQ(Angle(0.5, Angle::Unit::Arcsecond), Angle(1.0, Angle::Unit::Arcsecond) /= 2.0) ; EXPECT_EQ(Angle(0.5, Angle::Unit::Revolution), Angle(1.0, Angle::Unit::Revolution) /= 2.0) ; } { EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) /= Real::Undefined()) ; EXPECT_ANY_THROW(Angle(1.0, Angle::Unit::Radian) /= Real::Zero()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, AngleConversionOperator) { using ostk::physics::units::Angle ; { EXPECT_EQ(ostk::math::geom::Angle(+1.0, ostk::math::geom::Angle::Unit::Radian), Angle(+1.0, Angle::Unit::Radian)) ; } { EXPECT_NO_THROW(ostk::math::geom::Angle angle = Angle::Undefined() ; (void) angle ;) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, StreamOperator) { using ostk::physics::units::Angle ; { testing::internal::CaptureStdout() ; EXPECT_NO_THROW(std::cout << Angle(0.5, Angle::Unit::Degree) << std::endl) ; EXPECT_FALSE(testing::internal::GetCapturedStdout().empty()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, IsDefined) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_TRUE(Angle(0.0, Angle::Unit::Radian).isDefined()) ; EXPECT_TRUE(Angle(1.0, Angle::Unit::Radian).isDefined()) ; EXPECT_TRUE(Angle(1.0, Angle::Unit::Degree).isDefined()) ; EXPECT_TRUE(Angle(1.0, Angle::Unit::Arcminute).isDefined()) ; EXPECT_TRUE(Angle(1.0, Angle::Unit::Arcsecond).isDefined()) ; EXPECT_TRUE(Angle(1.0, Angle::Unit::Revolution).isDefined()) ; } { EXPECT_FALSE(Angle::Undefined().isDefined()) ; EXPECT_FALSE(Angle(Real::Undefined(), Angle::Unit::Radian).isDefined()) ; EXPECT_FALSE(Angle(1.0, Angle::Unit::Undefined).isDefined()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, GetUnit) { using ostk::physics::units::Angle ; { EXPECT_EQ(Angle::Unit::Radian, Angle(1.0, Angle::Unit::Radian).getUnit()) ; EXPECT_EQ(Angle::Unit::Degree, Angle(1.0, Angle::Unit::Degree).getUnit()) ; EXPECT_EQ(Angle::Unit::Arcminute, Angle(1.0, Angle::Unit::Arcminute).getUnit()) ; EXPECT_EQ(Angle::Unit::Arcsecond, Angle(1.0, Angle::Unit::Arcsecond).getUnit()) ; EXPECT_EQ(Angle::Unit::Revolution, Angle(1.0, Angle::Unit::Revolution).getUnit()) ; } { EXPECT_ANY_THROW(Angle::Undefined().getUnit()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, In) { using ostk::physics::units::Angle ; { EXPECT_EQ(1.0, Angle(1.0, Angle::Unit::Radian).in(Angle::Unit::Radian)) ; EXPECT_EQ(1.0, Angle(1.0, Angle::Unit::Degree).in(Angle::Unit::Degree)) ; EXPECT_EQ(1.0, Angle(1.0, Angle::Unit::Arcminute).in(Angle::Unit::Arcminute)) ; EXPECT_EQ(1.0, Angle(1.0, Angle::Unit::Arcsecond).in(Angle::Unit::Arcsecond)) ; EXPECT_EQ(1.0, Angle(1.0, Angle::Unit::Revolution).in(Angle::Unit::Revolution)) ; } { EXPECT_ANY_THROW(Angle::Undefined().in(Angle::Unit::Radian)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, InRadians) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(123.456, Angle(123.456, Angle::Unit::Radian).inRadians()) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(Real::Pi(), Angle(Real::Pi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(Real::Pi(), Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(Real::Pi(), Angle(-Real::Pi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(Real::Pi(), Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inRadians(0.0, Real::TwoPi())) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(-Real::Pi(), Angle(Real::Pi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(-Real::Pi(), Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(-Real::Pi(), Angle(-Real::Pi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(-Real::Pi(), Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inRadians(-Real::Pi(), Real::Pi())) ; } { EXPECT_ANY_THROW(Angle::Undefined().inRadians()) ; } { EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inRadians(0.0, 0.0)) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inRadians(0.0, Real::Pi())) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inRadians(+Real::Pi(), -Real::Pi())) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, InDegrees) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(360.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inDegrees()) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(180.0, Angle(Real::Pi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(180.0, Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(180.0, Angle(-Real::Pi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(180.0, Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(0.0, 360.0)) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(-180.0, Angle(Real::Pi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(-180.0, Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(-180.0, Angle(-Real::Pi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(-180.0, Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inDegrees(-180.0, +180.0)) ; } { EXPECT_ANY_THROW(Angle::Undefined().inDegrees()) ; } { EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(0.0, 0.0)) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(0.0, 180.0)) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(+180.0, -180.0)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, InArcminutes) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(360.0 * 60.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inArcminutes()) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(180.0 * 60.0, Angle(Real::Pi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(180.0 * 60.0, Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(180.0 * 60.0, Angle(-Real::Pi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(180.0 * 60.0, Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(0.0, 360.0 * 60.0)) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(-180.0 * 60.0, Angle(Real::Pi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(-180.0 * 60.0, Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(-180.0 * 60.0, Angle(-Real::Pi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(-180.0 * 60.0, Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inArcminutes(-180.0 * 60.0, +180.0 * 60.0)) ; } { EXPECT_ANY_THROW(Angle::Undefined().inArcminutes()) ; } { EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(0.0, 0.0)) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(0.0, 180.0 * 60.0)) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(+180.0 * 60.0, -180.0 * 60.0)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, InArcseconds) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(360.0 * 3600.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inArcseconds()) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(180.0 * 3600.0, Angle(Real::Pi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(180.0 * 3600.0, Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(180.0 * 3600.0, Angle(-Real::Pi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(180.0 * 3600.0, Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(0.0, 360.0 * 3600.0)) ; } { EXPECT_EQ(0.0, Angle(0.0, Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(-180.0 * 3600.0, Angle(Real::Pi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(-180.0 * 3600.0, Angle(3.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(4.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(-180.0 * 3600.0, Angle(-Real::Pi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(-Real::TwoPi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(-180.0 * 3600.0, Angle(-3.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; EXPECT_EQ(0.0, Angle(-4.0 * Real::Pi(), Angle::Unit::Radian).inArcseconds(-180.0 * 3600.0, +180.0 * 3600.0)) ; } { EXPECT_ANY_THROW(Angle::Undefined().inArcseconds()) ; } { EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(0.0, 0.0)) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(0.0, 180.0 * 3600.0)) ; EXPECT_ANY_THROW(Angle(0.0, Angle::Unit::Radian).inDegrees(+180.0 * 3600.0, -180.0 * 3600.0)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, InRevolutions) { using ostk::core::types::Real ; using ostk::physics::units::Angle ; { EXPECT_EQ(1.0, Angle(Real::TwoPi(), Angle::Unit::Radian).inRevolutions()) ; } { EXPECT_ANY_THROW(Angle::Undefined().inRevolutions()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, ToString) { using ostk::physics::units::Angle ; { EXPECT_EQ("1.0 [rad]", Angle(1.0, Angle::Unit::Radian).toString()) ; EXPECT_EQ("1.0 [deg]", Angle(1.0, Angle::Unit::Degree).toString()) ; EXPECT_EQ("1.0 [amin]", Angle(1.0, Angle::Unit::Arcminute).toString()) ; EXPECT_EQ("1.0 [asec]", Angle(1.0, Angle::Unit::Arcsecond).toString()) ; EXPECT_EQ("1.0 [rev]", Angle(1.0, Angle::Unit::Revolution).toString()) ; EXPECT_EQ("-1.0 [rad]", Angle(-1.0, Angle::Unit::Radian).toString()) ; EXPECT_EQ("-1.0 [deg]", Angle(-1.0, Angle::Unit::Degree).toString()) ; EXPECT_EQ("-1.0 [amin]", Angle(-1.0, Angle::Unit::Arcminute).toString()) ; EXPECT_EQ("-1.0 [asec]", Angle(-1.0, Angle::Unit::Arcsecond).toString()) ; EXPECT_EQ("-1.0 [rev]", Angle(-1.0, Angle::Unit::Revolution).toString()) ; EXPECT_EQ("123.456 [rad]", Angle(123.456, Angle::Unit::Radian).toString()) ; EXPECT_EQ("123.456 [deg]", Angle(123.456, Angle::Unit::Degree).toString()) ; EXPECT_EQ("123.456 [amin]", Angle(123.456, Angle::Unit::Arcminute).toString()) ; EXPECT_EQ("123.456 [asec]", Angle(123.456, Angle::Unit::Arcsecond).toString()) ; EXPECT_EQ("123.456 [rev]", Angle(123.456, Angle::Unit::Revolution).toString()) ; } { EXPECT_EQ("1.000 [rad]", Angle(1.0, Angle::Unit::Radian).toString(3)) ; EXPECT_EQ("1.000 [deg]", Angle(1.0, Angle::Unit::Degree).toString(3)) ; EXPECT_EQ("1.000 [amin]", Angle(1.0, Angle::Unit::Arcminute).toString(3)) ; EXPECT_EQ("1.000 [asec]", Angle(1.0, Angle::Unit::Arcsecond).toString(3)) ; EXPECT_EQ("1.000 [rev]", Angle(1.0, Angle::Unit::Revolution).toString(3)) ; EXPECT_EQ("-1.000 [rad]", Angle(-1.0, Angle::Unit::Radian).toString(3)) ; EXPECT_EQ("-1.000 [deg]", Angle(-1.0, Angle::Unit::Degree).toString(3)) ; EXPECT_EQ("-1.000 [amin]", Angle(-1.0, Angle::Unit::Arcminute).toString(3)) ; EXPECT_EQ("-1.000 [asec]", Angle(-1.0, Angle::Unit::Arcsecond).toString(3)) ; EXPECT_EQ("-1.000 [rev]", Angle(-1.0, Angle::Unit::Revolution).toString(3)) ; EXPECT_EQ("123.456 [rad]", Angle(123.456123, Angle::Unit::Radian).toString(3)) ; EXPECT_EQ("123.456 [deg]", Angle(123.456123, Angle::Unit::Degree).toString(3)) ; EXPECT_EQ("123.456 [amin]", Angle(123.456123, Angle::Unit::Arcminute).toString(3)) ; EXPECT_EQ("123.456 [asec]", Angle(123.456123, Angle::Unit::Arcsecond).toString(3)) ; EXPECT_EQ("123.456 [rev]", Angle(123.456123, Angle::Unit::Revolution).toString(3)) ; } { EXPECT_ANY_THROW(Angle::Undefined().toString()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Undefined) { using ostk::physics::units::Angle ; { EXPECT_NO_THROW(Angle::Undefined()) ; EXPECT_FALSE(Angle::Undefined().isDefined()) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Radians) { using ostk::physics::units::Angle ; { EXPECT_NO_THROW(Angle::Radians(123.456)) ; EXPECT_TRUE(Angle::Radians(123.456).isDefined()) ; EXPECT_EQ(123.456, Angle::Radians(123.456).in(Angle::Unit::Radian)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Degrees) { using ostk::physics::units::Angle ; { EXPECT_NO_THROW(Angle::Degrees(123.456)) ; EXPECT_TRUE(Angle::Degrees(123.456).isDefined()) ; EXPECT_EQ(123.456, Angle::Degrees(123.456).in(Angle::Unit::Degree)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Arcminutes) { using ostk::physics::units::Angle ; { EXPECT_NO_THROW(Angle::Arcminutes(123.456)) ; EXPECT_TRUE(Angle::Arcminutes(123.456).isDefined()) ; EXPECT_EQ(123.456, Angle::Arcminutes(123.456).in(Angle::Unit::Arcminute)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Arcseconds) { using ostk::physics::units::Angle ; { EXPECT_NO_THROW(Angle::Arcseconds(123.456)) ; EXPECT_TRUE(Angle::Arcseconds(123.456).isDefined()) ; EXPECT_EQ(123.456, Angle::Arcseconds(123.456).in(Angle::Unit::Arcsecond)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Revolutions) { using ostk::physics::units::Angle ; { EXPECT_NO_THROW(Angle::Revolutions(123.456)) ; EXPECT_TRUE(Angle::Revolutions(123.456).isDefined()) ; EXPECT_EQ(123.456, Angle::Revolutions(123.456).in(Angle::Unit::Revolution)) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, Parse) { using ostk::physics::units::Angle ; { EXPECT_EQ(Angle::Degrees(123.0), Angle::Parse("123 [deg]")) ; EXPECT_EQ(Angle::Degrees(123.0), Angle::Parse("123.0 [deg]")) ; EXPECT_EQ(Angle::Degrees(123.456), Angle::Parse("123.456 [deg]")) ; EXPECT_EQ(Angle::Degrees(1.2e6), Angle::Parse("1.2e6 [deg]")) ; EXPECT_EQ(Angle::Degrees(+123.0), Angle::Parse("+123 [deg]")) ; EXPECT_EQ(Angle::Degrees(+123.0), Angle::Parse("+123.0 [deg]")) ; EXPECT_EQ(Angle::Degrees(+123.456), Angle::Parse("+123.456 [deg]")) ; EXPECT_EQ(Angle::Degrees(+1.2e6), Angle::Parse("+1.2e6 [deg]")) ; EXPECT_EQ(Angle::Degrees(-123.0), Angle::Parse("-123 [deg]")) ; EXPECT_EQ(Angle::Degrees(-123.0), Angle::Parse("-123.0 [deg]")) ; EXPECT_EQ(Angle::Degrees(-123.456), Angle::Parse("-123.456 [deg]")) ; EXPECT_EQ(Angle::Degrees(-1.2e6), Angle::Parse("-1.2e6 [deg]")) ; EXPECT_EQ(Angle(123.0, Angle::Unit::Radian), Angle::Parse("123.0 [rad]")) ; EXPECT_EQ(Angle(123.0, Angle::Unit::Arcminute), Angle::Parse("123.0 [amin]")) ; EXPECT_EQ(Angle(123.0, Angle::Unit::Arcsecond), Angle::Parse("123.0 [asec]")) ; EXPECT_EQ(Angle(123.0, Angle::Unit::Revolution), Angle::Parse("123.0 [rev]")) ; } { EXPECT_ANY_THROW(Angle::Parse("")) ; EXPECT_ANY_THROW(Angle::Parse("1")) ; EXPECT_ANY_THROW(Angle::Parse("1.0")) ; EXPECT_ANY_THROW(Angle::Parse("1.0 []")) ; EXPECT_ANY_THROW(Angle::Parse("1.0 [m]")) ; EXPECT_ANY_THROW(Angle::Parse("abc")) ; EXPECT_ANY_THROW(Angle::Parse("1.0 [deg]")) ; } } TEST (OpenSpaceToolkit_Physics_Units_Derived_Angle, StringFromUnit) { using ostk::physics::units::Angle ; { EXPECT_EQ("Undefined", Angle::StringFromUnit(Angle::Unit::Undefined)) ; EXPECT_EQ("Radian", Angle::StringFromUnit(Angle::Unit::Radian)) ; EXPECT_EQ("Degree", Angle::StringFromUnit(Angle::Unit::Degree)) ; EXPECT_EQ("Arcminute", Angle::StringFromUnit(Angle::Unit::Arcminute)) ; EXPECT_EQ("Arcsecond", Angle::StringFromUnit(Angle::Unit::Arcsecond)) ; EXPECT_EQ("Revolution", Angle::StringFromUnit(Angle::Unit::Revolution)) ; } } ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
[ "lucas.bremond@gmail.com" ]
lucas.bremond@gmail.com
dafa9466c6391714feadc8c4c8761ba6ef590b35
b9412984b1cf9be86620d43aeddd96f567ea9a57
/07OOP_18040206HanDaeHyun/Chapter(7-10)/Chapter(7-10).cpp
ed9a22c88c165f66aaf8208e1ffc9b468e03b99b
[]
no_license
Daeja/techwing
cfbfb82268b7f0f33408fac972bdab73eef00da3
ee7a5ce36a2e2dbe0c2fd4f97e7989aaec8b457b
refs/heads/master
2020-03-13T04:34:18.945374
2018-04-25T07:20:59
2018-04-25T07:20:59
130,965,732
0
0
null
null
null
null
UHC
C++
false
false
7,436
cpp
#include <iostream> #include <typeinfo> #include "CMyString.h" #include "CStack.h" using namespace std; /******************************************************************************** AUTHOR : 한대현 NAME : swapValues PARAMS : [IN ] T T1, T T2 [OUT] void COMMENTS : 템플릿 자료형을 활용한 스왑 함수 ********************************************************************************/ template < typename T > void swapValues(T & T1, T & T2) { T tempTemplate = T1; T1 = T2; T2 = tempTemplate; } /******************************************************************************** AUTHOR : 한대현 NAME : swapValues PARAMS : [IN ] char * pc1, char * pc2 [OUT] void COMMENTS : 템플릿 자료형을 활용한 스왑 함수(Overloading) ********************************************************************************/ void swapValues(char * pc1, char * pc2) { char * pcTemp = new char [ STRING_BUFFER ]; if( NULL == pc1 ) { pc1 = new char[ STRING_BUFFER ]; } if( NULL == pc2 ) { pc2 = new char[ STRING_BUFFER ]; } strcpy_s(pcTemp, STRING_BUFFER, pc1); strcpy_s(pc1, STRING_BUFFER, pc2); strcpy_s(pc2, STRING_BUFFER, pcTemp); delete [] pcTemp; } /******************************************************************************** AUTHOR : 한대현 NAME : printPushSuccess PARAMS : [IN ] bIsSuccess [OUT] void COMMENTS : Overflow 발생 여부 확인 ********************************************************************************/ void printPushSuccess(int nIsSuccess) { if( nIsSuccess == PUSH_SUCCESS ) { cout << "스택 push() 성공" << endl; } else { cout << "Overflow 발생" << endl; } } /******************************************************************************** AUTHOR : 한대현 NAME : printPopSuccess PARAMS : [IN ] bIsSuccess [OUT] void COMMENTS : Underflow 발생 여부 확인 ********************************************************************************/ void printPopSuccess(int nIsSuccess) { if( nIsSuccess == PUSH_SUCCESS ) { cout << "스택 pop() 성공" << endl; } else { cout << "Underflow 발생" << endl; } } /******************************************************************************** AUTHOR : 한대현 NAME : push PARAMS : [IN ] CStack<T> & stack, T Value [OUT] void COMMENTS : 템플릿을 이용한 push함수 ********************************************************************************/ template <typename T> void push(CStack<T> & stack, T Value) { int nIsPushSuccess = 0; nIsPushSuccess = stack.push(Value); cout << "결과 : "; printPushSuccess(nIsPushSuccess); cout << endl << "넣은 값 : " << Value << endl << endl; } /******************************************************************************** AUTHOR : 한대현 NAME : pop PARAMS : [IN ] CStack<T> & stack [OUT] void COMMENTS : 템플릿을 이용한 pop함수 ********************************************************************************/ template <typename T> void pop(CStack<T> & stack) { T result = 0; int nIsPopSuccess = 0; nIsPopSuccess = stack.pop(result); cout << "결과 : "; printPopSuccess(nIsPopSuccess); cout << endl << "빠진 값 : " << result << endl << endl; } /******************************************************************************** AUTHOR : 한대현 NAME : push PARAMS : [IN ] CStack<char *> & stack, char * Value [OUT] void COMMENTS : 템플릿 함수의 특수화를 이용한 push 함수 ********************************************************************************/ template <> void push(CStack<char *> & stack, char * Value) { int nIsPushSuccess = 0; nIsPushSuccess = stack.push(Value); cout << "결과 : "; printPushSuccess(nIsPushSuccess); cout << "넣은 값 : " << Value << endl << endl; } /******************************************************************************** AUTHOR : 한대현 NAME : pop PARAMS : [IN ] CStack<char *> & stack [OUT] void COMMENTS : 템플릿 함수의 특수화를 이용한 pop 함수 ********************************************************************************/ template <> void pop(CStack<char *> & stack) { char result [STRING_BUFFER]; int nIsPopSuccess = 0; memset(result, 0, STRING_BUFFER); nIsPopSuccess = stack.pop(result); cout << "결과 : "; printPopSuccess(nIsPopSuccess); cout << "빠진 값 : " << result << endl << endl; //delete [] result; } int main() { cout << "7-10-1번 문제입니다." << endl; int nInt1 = 100; int nInt2 = 200; float fFloat1 = (float)1.1; float fFloat2 = (float)2.2; char * pcChar1 = new char [ STRING_BUFFER ]; char * pcChar2 = new char [ STRING_BUFFER ]; char szChar1[STRING_BUFFER] = "Techwing"; char szChar2[STRING_BUFFER] = "Bye!"; CMyString string1 = (CMyString)"SW-3 HAN DAE HYUN"; CMyString string2 = (CMyString)"Hello World!"; strcpy_s(pcChar1, STRING_BUFFER, "Hi! World"); strcpy_s(pcChar2, STRING_BUFFER, "Bye Bye!"); cout << nInt1 << ", " << nInt2 << endl; swapValues(nInt1, nInt2); cout << nInt1 << ", " << nInt2 << endl; cout << fFloat1 << ", " << fFloat2 << endl; swapValues(fFloat1, fFloat2); cout << fFloat1 << ", " << fFloat2 << endl; cout << pcChar1 << ", " << pcChar2 << endl; swapValues(pcChar1, pcChar2); cout << pcChar1 << ", " << pcChar2 << endl; cout << szChar1 << ", " << szChar2 << endl; swapValues(szChar1, szChar2); cout << szChar1 << ", " << szChar2 << endl; cout << string1 << ", " << string2 << endl; swapValues(string1, string2); cout << string1 << ", " << string2 << endl; cout << endl << endl << "7-10-2번 문제입니다." << endl; cout << endl << endl << "int 응용" << endl << endl; // int CStack<int> stackInt(5); push(stackInt, 10); pop(stackInt); pop(stackInt); pop(stackInt); pop(stackInt); push(stackInt, 10); push(stackInt, 20); push(stackInt, 30); push(stackInt, 40); push(stackInt, 50); push(stackInt, 60); pop(stackInt); cout << endl << endl << "float 응용" << endl << endl; // float CStack<float> stackFloat; push(stackFloat, (float)10.123); push(stackFloat, (float)10.1234); push(stackFloat, (float)14.4); push(stackFloat, (float)1818.1); pop(stackFloat); cout << endl << endl << "char * 응용" << endl << endl; // char * CStack<char *> stackpChar(5); push(stackpChar, (char *)"Hi!!"); push(stackpChar, (char *)"My name is"); push(stackpChar, (char *)"Han dae-hyun"); push(stackpChar, (char *)"Nice to meet you."); push(stackpChar, (char *)"Techwing SW3 Team"); push(stackpChar, (char *)"eurghulrhgluhrlgiuhdliugrhliusrhglirg"); push(stackpChar, (char *)""); pop(stackpChar); pop(stackpChar); pop(stackpChar); push(stackpChar, (char *)"Han dae-hyun"); push(stackpChar, (char *)"Nice to meet you."); push(stackpChar, (char *)"Techwing SW3 Team"); cout << endl << endl << "CMyString 객체 응용" << endl << endl; // CMyString CStack<CMyString> stackString(5); push(stackpChar, (char *)"Hi!!"); push(stackpChar, (char *)"My name is"); push(stackpChar, (char *)"Han dae-hyun"); push(stackpChar, (char *)"Nice to meet you."); push(stackpChar, (char *)"Techwing SW3 Team"); pop(stackpChar); pop(stackpChar); pop(stackpChar); push(stackpChar, (char *)"Han dae-hyun"); push(stackpChar, (char *)"Nice to meet you."); push(stackpChar, (char *)"Techwing SW3 Team"); // 추가 CMyString string; cin >> string; cout << string << endl; cout << typeid(string).name() << endl; return 0; }
[ "hyunx5@naver.com" ]
hyunx5@naver.com
2fe8f63d46e76a1b766f927c462284eb2f7c813d
ef4a6746c64cd967094a02d5172c1679d08b37de
/3.2 c project, aduino start/Arduino/sketch_dec19a/sketch_dec19a.ino
ad5df7c76ba632e0c15387ea4a64d3bce6f94701
[]
no_license
cladren123/multicampus2
6dae63975ff8692b859f8c22c1704a2792b438d8
b44332596d39b3b1e8d94fb4962e8d0dddd0f735
refs/heads/master
2023-03-26T04:17:03.825033
2021-03-26T12:58:14
2021-03-26T12:58:14
341,168,146
0
0
null
null
null
null
UTF-8
C++
false
false
183
ino
void setup() { // put your setup code here, to run once: Serial.begin(9600); Serial.print("Hello World!!"); } void loop() { // put your main code here, to run repeatedly: }
[ "gold3987@naver.com" ]
gold3987@naver.com
a0aa096ef2e347b58e8d221aba32089b0c172c0d
a01eaed695583aad70bd7e1da1af0ec736c7bf22
/nativeLib/org.apache.qpid/include/qpid/framing/ClusterConnectionRetractOfferBody.h
f7409ad104e66f10d0691164b65498366a1bd60b
[]
no_license
SeanTheGuyThatAlwaysHasComputerTrouble/awips2
600d3e6f7ea1b488471e387c642d54cb6eebca1a
c8f8c20ca34e41ac23ad8e757130e91c77b558fe
refs/heads/master
2021-01-19T18:00:12.598133
2013-03-26T17:06:45
2013-03-26T17:06:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,720
h
#ifndef QPID_FRAMING_CLUSTERCONNECTIONRETRACTOFFERBODY_H #define QPID_FRAMING_CLUSTERCONNECTIONRETRACTOFFERBODY_H /* * * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * */ /// /// This file was automatically generated from the AMQP specification. /// Do not edit. /// #include "qpid/framing/AMQMethodBody.h" #include "qpid/framing/AMQP_ServerOperations.h" #include "qpid/framing/MethodBodyConstVisitor.h" #include "qpid/framing/ModelMethod.h" #include <ostream> #include "qpid/framing/amqp_types_full.h" #include "qpid/CommonImportExport.h" namespace qpid { namespace framing { class ClusterConnectionRetractOfferBody : public ModelMethod { uint16_t flags; public: static const ClassId CLASS_ID = 0x81; static const MethodId METHOD_ID = 0x22; ClusterConnectionRetractOfferBody(ProtocolVersion=ProtocolVersion()) : flags(0) {} typedef void ResultType; template <class T> ResultType invoke(T& invocable) const { return invocable.retractOffer(); } using AMQMethodBody::accept; void accept(MethodBodyConstVisitor& v) const { v.visit(*this); } boost::intrusive_ptr<AMQBody> clone() const { return BodyFactory::copy(*this); } ClassId amqpClassId() const { return CLASS_ID; } MethodId amqpMethodId() const { return METHOD_ID; } bool isContentBearing() const { return false; } bool resultExpected() const { return false; } bool responseExpected() const { return false; } QPID_COMMON_EXTERN void encode(Buffer&) const; QPID_COMMON_EXTERN void decode(Buffer&, uint32_t=0); QPID_COMMON_EXTERN void encodeStructBody(Buffer&) const; QPID_COMMON_EXTERN void decodeStructBody(Buffer&, uint32_t=0); QPID_COMMON_EXTERN uint32_t encodedSize() const; QPID_COMMON_EXTERN uint32_t bodySize() const; QPID_COMMON_EXTERN void print(std::ostream& out) const; }; /* class ClusterConnectionRetractOfferBody */ }} #endif /*!QPID_FRAMING_CLUSTERCONNECTIONRETRACTOFFERBODY_H*/
[ "root@lightning.(none)" ]
root@lightning.(none)
b7a26a4973455eaccbd7f7b09a01f39c5e5ce422
7e36880b77ab4351e5cddd6adb54c846fcdb3fed
/arm-bcm2708/gcc-linaro-arm-linux-gnueabihf-raspbian-x64/arm-linux-gnueabihf/include/c++/4.8.3/ext/vstring_fwd.h
c8c86016061108f0f8b6be667dc8b48fc88039fa
[]
no_license
occidens/tools
aa5c3dabbade6bcaa10cb49967865fb4535801c2
172999c595b3ec4573b419854e973e6f26463ae7
refs/heads/master
2021-01-18T09:46:48.028765
2014-04-16T14:53:11
2014-04-16T14:53:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,217
h
// <vstring.h> Forward declarations -*- C++ -*- // Copyright (C) 2005-2013 Free Software Foundation, Inc. // // This file is part of the GNU ISO C++ Library. This library is free // software; you can redistribute it and/or modify it under the // terms of the GNU General Public License as published by the // Free Software Foundation; either version 3, or (at your option) // any later version. // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // Under Section 7 of GPL version 3, you are granted additional // permissions described in the GCC Runtime Library Exception, version // 3.1, as published by the Free Software Foundation. // You should have received a copy of the GNU General Public License and // a copy of the GCC Runtime Library Exception along with this program; // see the files COPYING3 and COPYING.RUNTIME respectively. If not, see // <http://www.gnu.org/licenses/>. /** @file ext/vstring_fwd.h * This is an internal header file, included by other library headers. * Do not attempt to use it directly. @headername{ext/vstring.h} */ #ifndef _VSTRING_FWD_H #define _VSTRING_FWD_H 1 #pragma GCC system_header #include <bits/c++config.h> #include <bits/char_traits.h> #include <bits/allocator.h> namespace __gnu_cxx _GLIBCXX_VISIBILITY(default) { _GLIBCXX_BEGIN_NAMESPACE_VERSION template<typename _CharT, typename _Traits, typename _Alloc> class __sso_string_base; template<typename _CharT, typename _Traits, typename _Alloc> class __rc_string_base; template<typename _CharT, typename _Traits = std::char_traits<_CharT>, typename _Alloc = std::allocator<_CharT>, template <typename, typename, typename> class _Base = __sso_string_base> class __versa_string; typedef __versa_string<char> __vstring; typedef __vstring __sso_string; typedef __versa_string<char, std::char_traits<char>, std::allocator<char>, __rc_string_base> __rc_string; #ifdef _GLIBCXX_USE_WCHAR_T typedef __versa_string<wchar_t> __wvstring; typedef __wvstring __wsso_string; typedef __versa_string<wchar_t, std::char_traits<wchar_t>, std::allocator<wchar_t>, __rc_string_base> __wrc_string; #endif #if ((__cplusplus >= 201103L) \ && defined(_GLIBCXX_USE_C99_STDINT_TR1)) typedef __versa_string<char16_t> __u16vstring; typedef __u16vstring __u16sso_string; typedef __versa_string<char16_t, std::char_traits<char16_t>, std::allocator<char16_t>, __rc_string_base> __u16rc_string; typedef __versa_string<char32_t> __u32vstring; typedef __u32vstring __u32sso_string; typedef __versa_string<char32_t, std::char_traits<char32_t>, std::allocator<char32_t>, __rc_string_base> __u32rc_string; #endif _GLIBCXX_END_NAMESPACE_VERSION } // namespace #endif /* _VSTRING_FWD_H */
[ "popcornmix@gmail.com" ]
popcornmix@gmail.com
8e7edcf2ef8f4c9f4659932534a2628ab2c96428
18f0ad99e21e2e35126f8c3c28079d358fa2129a
/DSP-G1_Trellis_Synth/DSP-G1_Trellis_Synth.ino
74df2e869f7c37c7a2dade22ebe3b71213d811ef
[ "MIT" ]
permissive
ladyada/Adafruit_Learning_System_Guides
9bf18dfa35941e0cbecbb3c2d02b4fa3cb79744f
6d76801878cbf65132ccea950dc47ae842c73dcd
refs/heads/master
2023-08-20T20:30:42.910576
2022-01-10T20:28:11
2022-01-10T20:28:11
115,837,894
13
2
MIT
2020-03-31T23:23:45
2017-12-31T02:34:47
C
UTF-8
C++
false
false
23,664
ino
#include <MIDI.h> #include "Adafruit_Trellis.h" //use Trellis 0-11 and 16-27 as input for notes. //use Trellis 12-15 and 28-31 for input to modes, sequencer, patches //six potentiometers as CC value input //rotary switch to choose banks of CC numbers for knobs //John Park for Adafruit Industries MIDI_CREATE_DEFAULT_INSTANCE(); Adafruit_Trellis matrix0 = Adafruit_Trellis(); //left Trellis Adafruit_Trellis matrix1 = Adafruit_Trellis(); //right Trellis Adafruit_TrellisSet trellis = Adafruit_TrellisSet(&matrix0, &matrix1); #define NUMTRELLIS 2 #define numKeys (NUMTRELLIS * 16) //#define INTPIN A2 #define MOMENTARY 0 #define LATCHING 1 int holdMode = 0; int lastHoldMode = 0; static const unsigned LED = 13; // LED pin on the Feather /*********************/ //pick scale mode here: //0=chromatic, 1=major, 2=minor, 3=dorian, 4=mixolydian, 5=harmonic minor int scaleMode = 0; //Dorian /*********************/ int octave = 1; int transpose[6] = {0, 12, 24, 36, 48, 60}; //multiply notes depending on octave //Trellis assignments /* //First three rows map to MIDI Notes, bottom row is special functions ------------------------------------------------------------------------------- 0 1 2 3 16 17 18 19 M16 M17 M18 M19 M20 M21 M22 M23 4 5 6 7 20 21 22 23 M8 M9 M10 M11 M12 M13 M14 M15 8 9 10 11 24 25 26 27 M0 M1 M2 M3 M4 M5 M6 M7 ------------------------------------------------------------------------------- 12 13 14 15 28 29 30 31 seq patch pause/play rec I II III hold mode ------------------------------------------------------------------------------- */ //Map physical Trellis grids to single logical grid int logicalPads[32] = { 0, 1, 2, 3, 8, 9, 10, 11, 16, 17, 18, 19, 24, 25, 26, 27, 4, 5, 6, 7, 12, 13, 14, 15, 20, 21, 22, 23, 28, 29, 30, 31 } ; int padNoteMap[24] = { 16, 17, 18, 19, 20, 21, 22, 23, 8, 9, 10, 11, 12, 13, 14, 15, 0, 1, 2, 3, 4, 5, 6, 7}; int padFuncMap[8] = { //note, only hold mode is implemented currently 0, // sequencer 1, // patch 2, // pause/play / recall 3, // record / store 4, // sequence I / patch I 5, // seq. II / patch II 6, // seq. III / patch III 7 //hold mode: LATCHING or MOMENTARY }; //Define Scales int scalesMatrix[6][24] = { //Chromatic { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 }, //Major { 0, 2, 4, 5, 7, 9, 11, 12, 12, 14, 16, 17, 19, 21, 23, 24, 24, 26, 28, 29, 31, 33, 35, 36 }, //Minor { 0, 2, 3, 5, 7, 8, 10, 12, 12, 14, 15, 17, 19, 20, 22, 24, 24, 26, 27, 29, 31, 32, 34, 36 }, //Dorian { 0, 2, 3, 5, 6, 9, 10, 12, 12, 14, 15, 17, 18, 21, 22, 24, 24, 26, 27, 29, 30, 33, 34, 36 }, //Mixolydian { 0, 2, 4, 5, 7, 9, 10, 12, 12, 14, 16, 17, 19, 21, 22, 24, 24, 26, 28, 29, 31, 33, 34, 36 }, //Harmonic Minor { 0, 2, 3, 5, 7, 8, 11, 12, 12, 14, 15, 17, 19, 20, 23, 24, 24, 26, 27, 29, 31, 32, 35, 36 } }; //Set up selector switch pins to read digital input pins that set the CC bank const int CC_bankPin0 = 9; const int CC_bankPin1 = 10; const int CC_bankPin2 = 11; const int CC_bankPin3 = 12; int CC_bankState0 = 0; int CC_bankState1 = 0; int CC_bankState2 = 0; int CC_bankState3 = 0; //current bank per knob. assume not on 0-3 int currentBank[6] = {4, 4, 4, 4, 4, 4}; //last bank per knob. assume not on 0-3 int lastBank[6] = {5, 5, 5, 5, 5, 5}; //Set up potentiometer pins const int CC0_pin = A0; //potentiometer pin int CC0_value; //store pot value const int CC1_pin = A1; int CC1_value; const int CC2_pin = A2; int CC2_value; const int CC3_pin = A3; int CC3_value; const int CC4_pin = A4; int CC4_value; const int CC5_pin = A5; int CC5_value; int CC_read[4] ; //Store previous values to enable hysteresis and pick-up mode for knobs int CC_bank0_lastValue[6] = {32, 32, 32, 32, 32, 32}; int CC_bank1_lastValue[6] = {32, 32, 32, 32, 32, 32}; int CC_bank2_lastValue[6] = {32, 32, 32, 32, 32, 32}; int CC_bank3_lastValue[6] = {32, 32, 32, 32, 32, 32}; int CC_bank0_value[6] = {0, 0, 0, 0, 0, 0}; int CC_bank1_value[6] = {0, 0, 0, 0, 0, 0}; int CC_bank2_value[6] = {0, 0, 0, 0, 0, 0}; int CC_bank3_value[6] = {0, 0, 0, 0, 0, 0}; void setup() { Serial.begin(115200); pinMode(LED, OUTPUT); digitalWrite(LED, HIGH); //turn this on as a system power indicator pinMode(CC_bankPin0, INPUT_PULLUP); //loop this pinMode(CC_bankPin1, INPUT_PULLUP); pinMode(CC_bankPin2, INPUT_PULLUP); pinMode(CC_bankPin3, INPUT_PULLUP); // Default Arduino I2C speed is 100 KHz, but the HT16K33 supports // 400 KHz. We can force this for faster read & refresh, but may // break compatibility with other I2C devices...so be prepared to // comment this out, or save & restore value as needed. #ifdef ARDUINO_ARCH_SAMD Wire.setClock(400000L); #endif #ifdef __AVR__ TWBR = 12; // 400 KHz I2C on 16 MHz AVR #endif trellis.begin(0x70, 0x71); for (uint8_t i=0; i<numKeys; i++) { trellis.setLED(i); trellis.writeDisplay(); delay(15); } // then turn them off for (uint8_t i=0; i<numKeys; i++) { trellis.clrLED(i); trellis.writeDisplay(); delay(15); } MIDI.begin(1); //All notes off MIDI panic if reset for(int n=0; n<128; n++){ MIDI.sendNoteOff(n, 127, 1); //DC Filter cutoff } /////////////DSP-G1 CC Parameter Settings Defaults (to be changed with knobs) MIDI.sendControlChange( 7, 119, 1); //volume MIDI.sendControlChange( 1, 24, 1); //LFO mod 24 MIDI.sendControlChange(16, 6, 1); //LFO rate 12 MIDI.sendControlChange(20, 0, 1); //LFO waveform 0-63 sine, 64-127 S/H MIDI.sendControlChange(74, 80, 1); //DC Filter cutoff MIDI.sendControlChange(71, 70, 1); //DC Filter resonance MIDI.sendControlChange(82, 32, 1); //DC Filter envelope Attack MIDI.sendControlChange(83, 38, 1); //DC Filter envelope Decay MIDI.sendControlChange(28, 64, 1); //DC Filter envelope Sustain MIDI.sendControlChange(29, 32, 1); //DC Filter envelope Release MIDI.sendControlChange(81, 57, 1); //DC Filter envelope modulation MIDI.sendControlChange(76, 100, 1); //DC Oscillator waveform* 100 MIDI.sendControlChange( 4, 0, 1); //DC Oscillator wrap MIDI.sendControlChange(21, 0, 1); //DC Oscillator range MIDI.sendControlChange(93, 0, 1); //DC Oscillator detune MIDI.sendControlChange(73, 0, 1); //DC Oscillator envelope Attack MIDI.sendControlChange(75, 12, 1); //DC Oscillator envelope Decay MIDI.sendControlChange(31, 60, 1); //DC Oscillator envelope Sustain MIDI.sendControlChange(72, 80, 1); //DC Oscillator envelope Release /*Wavforms: 0 tri, 25 squarish, 50 pulse, 75 other squarish, 100 saw */ } void loop(){ //read selector switch pins to find CC knob bank CC_bankState0 = digitalRead(CC_bankPin0);//loop this CC_bankState1 = digitalRead(CC_bankPin1); CC_bankState2 = digitalRead(CC_bankPin2); CC_bankState3 = digitalRead(CC_bankPin3); int b; //to increment through current bank state values if (CC_bankState0 == LOW){ //low means it's the selected bank for (b=0;b<6;b++){currentBank[b] = 0;} read_CC_Knobs(0); } else if (CC_bankState1 == LOW){ for (b=0;b<6;b++){currentBank[b] = 1;} read_CC_Knobs(1); } else if (CC_bankState2 == LOW){ for (b=0;b<6;b++){currentBank[b] = 2;} read_CC_Knobs(2); } else if (CC_bankState3 == LOW){ for (b=0;b<6;b++){currentBank[b] = 3;} read_CC_Knobs(3); } else { //4-7 have been picked, not connected for (b=0;b<6;b++){currentBank[b] = 4;} } //Trellis MIDI out Keyboard delay(30); // 30ms delay is required, dont remove me! if (holdMode == MOMENTARY) { if (trellis.readSwitches()) { // If a button was just pressed or released... for (uint8_t i=0; i<numKeys; i++) { // go through every button if (trellis.justPressed(i)) { // if it was pressed, map what it actually does //remap the physical button to logical button. 'p' is logical pad, i is physical pad. these names stink. int p = logicalPads[i]; // Serial.print("logical pad: "); Serial.println(p); if(p<24){ //it's a MIDI note pad, play a note int padNote = logicalPads[i]; MIDI.sendNoteOn((scalesMatrix[scaleMode][padNoteMap[padNote]] + transpose[octave]), 127, 1); //uncomment for debugging: /* Serial.print("v"); Serial.println(p); //print which button pressed trellis.setLED(i); //light stuff up Serial.print("OUT: "); //print MIDI out command Serial.print("\tChannel: "); Serial.print(1); Serial.print("\tNote: "); Serial.print(scalesMatrix[scaleMode][padNoteMap[padNote]] + transpose[octave]); Serial.print("\tValue: "); Serial.println("127"); */ } else if (p==31){ // last button on bottom row swaps hold modes holdMode = !holdMode; lastHoldMode = holdMode; //Serial.println("Hold mode switch to Latching."); for (uint8_t n=0; n<24; n++) { //clear note LEDs trellis.clrLED(n); trellis.writeDisplay(); } trellis.setLED(i); //light stuff up trellis.writeDisplay(); delay(30); } else{ Serial.println("not a note"); } } if (trellis.justReleased(i)) { // if it was released, turn it off int p = logicalPads[i]; //Serial.print("logical pad: "); Serial.println(p); if(p<24){ //it's a MIDI note pad, play a note int padNote=logicalPads[i]; MIDI.sendNoteOff((scalesMatrix[scaleMode][padNoteMap[padNote]] + transpose[octave]), 127, 1); //Serial.print("^"); Serial.println(p); for (uint8_t i=0; i<numKeys; i++) { trellis.clrLED(i); trellis.writeDisplay(); } trellis.setLED(i); //keep last one that was pressed turned on //uncomment for debugging /* Serial.print("OUT: "); Serial.print("\tChannel: "); Serial.print(1); Serial.print("\tNote: "); Serial.print(scalesMatrix[scaleMode][padNoteMap[padNote]]+ transpose[octave]); */ //Serial.print("\tValue: "); Serial.println("0"); } else if (p==31){ // last button on bottom row swaps hold modes } else{ Serial.println("not a note"); } } } trellis.writeDisplay(); // tell the trellis to set the LEDs we requested } } if (holdMode == LATCHING) { if (trellis.readSwitches()) { for (uint8_t i=0; i<numKeys; i++) { if (trellis.justPressed(i)) { int p = logicalPads[i]; //Serial.print("logical pad: "); Serial.println(p); if(p<24){ int padNote = logicalPads[i]; //Serial.print("pad note: "); Serial.println(padNote); //Serial.print("v"); Serial.println(i); if (trellis.isLED(i)){ // Alternate the button MIDI.sendNoteOff((scalesMatrix[scaleMode][padNoteMap[padNote]] + transpose[octave]), 127, 1); trellis.clrLED(i); } else{ MIDI.sendNoteOn((scalesMatrix[scaleMode][padNoteMap[padNote]] + transpose[octave]), 127, 1); trellis.setLED(i); } } else if (i==31){ // last button on bottom row swaps hold modes holdMode = !holdMode; lastHoldMode = holdMode; for(int n=0; n<128; n++){ MIDI.sendNoteOff(n, 127, 1); //DC Filter cutoff } for (uint8_t j=0; j<24; j++) { //clear all note pads trellis.clrLED(j); } trellis.clrLED(i); //clear holdMode pad trellis.writeDisplay(); //Serial.println("holdMode switch to Momentary."); delay(30); } else{ Serial.println("not a note"); } } trellis.writeDisplay(); } } } //clear key LEDs after a hold mode change if(holdMode != lastHoldMode){ //Serial.print("Hold mode: "); Serial.println(holdMode); //Serial.print("Last hold mode: "); Serial.println(lastHoldMode); for (uint8_t j=0; j<24; j++) { //clear all note pads trellis.clrLED(j); } trellis.writeDisplay(); } } void read_CC_Knobs(int CC_bank){ int AnalogPin[6] = {A0, A1, A2, A3, A4, A5}; //define the analog pins int CCKnob[6] = {0, 1, 2, 3, 4, 5}; //define knobs // choose which CC numbers are on each knob per bank // definitions are at bottom of code //Note: can set knobs to "never change" by repeating CC numbers per array int CCNumber[6]; //variable array to store the CC numbers if(CC_bank == 0){ //set the CC numbers per knob per bank //OSC int CCNumberChoice[6] = {71, //Filter resonance bottom of left knobs 74, //Filter cutoff top of left two knobs 21, //DCO range upper row 93, //DCO detune 4, //DCO wrap 76 //DCO waveform }; for(int n=0; n<6; n++){ CCNumber[n] = CCNumberChoice[n]; } } else if(CC_bank == 1){ //Envelope (for main oscillators) int CCNumberChoice[6] = {71, //Filter resonance 74, //Filter cutoff top of left two knobs 82, //VCA Attack 83, //VCA Decay 28, //VCA Sustain 29 //VCA Release }; for(int n=0; n<6; n++){ CCNumber[n] = CCNumberChoice[n]; } } else if(CC_bank == 2){ //LFO low frequency oscillator for main OSC int CCNumberChoice[6] = {71, //Filter resonance 74, //Filter cutoff top of left two knobs 1, //LFO mod 16, //LFO rate 20, //LFO waveform shape 81 //Filter mod }; for(int n=0; n<6; n++){ CCNumber[n] = CCNumberChoice[n]; } } else if(CC_bank == 3){ //Envelope (for filter) int CCNumberChoice[6] = {71, //Filter resonance 74, //Filter cutoff top of left two knobs 1, //Filter A 16, //Filter D 20, //Filter S 81 //Filter R }; for(int n=0; n<6; n++){ CCNumber[n] = CCNumberChoice[n]; } } //Knob pick-up mode -- to deal with multiple knob banks, //value doesn't get sent until knob reaches pravious ("last") position //NOTE: ugly way to do this, clean it up so a matrix is used instead //per bank loop currently //Send CC values only when they change beyond last value to avoid getting stuck between two values //thanks to Groovesizer Foxtrot code for this idea: https://groovesizer.com/foxtrot/ //thanks to Todbot for the delta hysteresis idea if(CC_bank == 0){ //first bank is selected for(int k=0; k<6; k++){ //loop through each of six pots if(currentBank[k] != lastBank[k]){ //if the current bank for current knob //digitalWrite(LED, LOW); //is different than the last bank for the current knob: //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank0_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read when we were on this bank, only send CC if value //of knob is withing a certain delta of the last value if((abs(CC_bank0_lastValue[k] - CC_bank0_value[k])) < 3){ //hysteresis for spinning knob too fast Serial.println("PICKUP ACHIEVED"); //digitalWrite(LED, HIGH); Serial.print("\nCC_bank0_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank0_value[k]); Serial.print("CC_bank0_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank0_lastValue[k]); lastBank[k] = 0; } } else if(currentBank[k] == lastBank[k]){ //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank0_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read, only send CC if value has changed since last read by a certain delta if((abs(CC_bank0_lastValue[k] - CC_bank0_value[k])) > 3){ //hysteresis for spinning knob too fast Serial.print("\nCC_bank0_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank0_value[k]); Serial.print("CC_bank0_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank0_lastValue[k]); MIDI.sendControlChange(CCNumber[k], CC_bank0_value[k], 1); //Serial.print("CC number: "); Serial.println(CCNumber[k]); CC_bank0_lastValue[k] = CC_bank0_value[k]; lastBank[k] = 0; } } } } if(CC_bank == 1){ //second bank is selected for(int k=0; k<6; k++){ //loop through each of six pots if(currentBank[k] != lastBank[k]){ //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank1_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read when we were on this bank, only send CC if value //of knob is withing a certain delta of the last value if((abs(CC_bank1_lastValue[k] - CC_bank1_value[k])) < 3){ //hysteresis for spinning knob too fast Serial.println("Pickup achieved."); Serial.print("\nCC_bank1_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank1_value[k]); Serial.print("CC_bank1_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank1_lastValue[k]); lastBank[k] = 1; } } else if(currentBank[k] == lastBank[k]){ //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank1_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read, only send CC if value has changed since last read by a certain delta if((abs(CC_bank1_lastValue[k] - CC_bank1_value[k])) > 3){ //hysteresis for spinning knob too fast Serial.print("\nCC_bank1_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank1_value[k]); Serial.print("CC_bank1_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank1_lastValue[k]); MIDI.sendControlChange(CCNumber[k], CC_bank1_value[k], 1); //Serial.print("CC number: "); Serial.println(CCNumber[k]); CC_bank1_lastValue[k] = CC_bank1_value[k]; lastBank[k] = 1; } } } } if(CC_bank == 2){ //third bank is selected for(int k=0; k<6; k++){ //loop through each of six pots if(currentBank[k] != lastBank[k]){ //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank2_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read when we were on this bank, only send CC if value //of knob is withing a certain delta of the last value if((abs(CC_bank2_lastValue[k] - CC_bank2_value[k])) < 3){ //hysteresis for spinning knob too fast Serial.println("Pickup achieved."); Serial.print("\nCC_bank2_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank2_value[k]); Serial.print("CC_bank2_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank2_lastValue[k]); lastBank[k] = 2; } } else if(currentBank[k] == lastBank[k]){ //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank2_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read, only send CC if value has changed since last read by a certain delta if((abs(CC_bank2_lastValue[k] - CC_bank2_value[k])) > 3){ //hysteresis for spinning knob too fast Serial.print("\nCC_bank2_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank2_value[k]); Serial.print("CC_bank2_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank2_lastValue[k]); MIDI.sendControlChange(CCNumber[k], CC_bank2_value[k], 1); //Serial.print("CC number: "); Serial.println(CCNumber[k]); CC_bank2_lastValue[k] = CC_bank2_value[k]; lastBank[k] = 2; } } } } if(CC_bank == 3){ //fourth bank is selected for(int k=0; k<6; k++){ //loop through each of six pots if(currentBank[k] != lastBank[k]){ //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank3_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read when we were on this bank, only send CC if value //of knob is withing a certain delta of the last value if((abs(CC_bank3_lastValue[k] - CC_bank3_value[k])) < 3){ //hysteresis for spinning knob too fast Serial.println("Pickup achieved."); Serial.print("\nCC_bank3_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank3_value[k]); Serial.print("CC_bank3_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank3_lastValue[k]); lastBank[k] = 3; } } else if(currentBank[k] == lastBank[k]){ //read CC values from potentiometers CC_read[CC_bank] = analogRead(AnalogPin[k]); CC_bank3_value[k] = map(CC_read[CC_bank], 0, 1023, 0, 127); // remap range to 0-127 //check against last read, only send CC if value has changed since last read by a certain delta if((abs(CC_bank3_lastValue[k] - CC_bank3_value[k])) > 3){ //hysteresis for spinning knob too fast Serial.print("\nCC_bank3_value for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank3_value[k]); Serial.print("CC_bank3_lastValue for knob: "); Serial.print(k); Serial.print("\t"); Serial.println(CC_bank3_lastValue[k]); MIDI.sendControlChange(CCNumber[k], CC_bank3_value[k], 1); //Serial.print("CC number: "); Serial.println(CCNumber[k]); CC_bank3_lastValue[k] = CC_bank3_value[k]; lastBank[k] = 3; } } } } }
[ "jp@jpixl.net" ]
jp@jpixl.net
41cbb19f9eba3e86abbaaf2f5d861a8e70278146
727d95073476de0623a287e27d68e9de2015cceb
/view/search_widget.h
ae42d99056dabfa3adbb26d5cd47667a29c8969f
[ "MIT" ]
permissive
Marco305/Qontainer
fdec1e44e26fc34caadd8294f9e984729d12d5b2
2325088f3b7d0d90348809586839c59e2dc98188
refs/heads/master
2021-05-17T13:51:07.267452
2020-03-28T13:51:48
2020-03-28T13:51:48
250,806,962
0
0
null
null
null
null
UTF-8
C++
false
false
1,060
h
#ifndef SEARCHWIDGET_H #define SEARCHWIDGET_H #include <QGroupBox> #include <QLineEdit> #include <QCheckBox> #include <QDateEdit> #include <view/field/type_combo_box.h> #include <view/field/gender_buttons.h> #include <view/field/birth_date_search.h> #include <view/field/spin_box_search.h> #include <view/field/double_spin_box_search.h> #include <view/field/rank_buttons.h> #include "filter.h" class SearchWidget : public QGroupBox { Q_OBJECT private: TypeComboBox* typeField; QLineEdit* nameField; GenderButtons<QCheckBox>* genderField; BirthDateSearch* birthDateField; DoubleSpinBoxSearch* taxesField; SpinBoxSearch* killsField; RankButtons<QCheckBox>* rankField; SpinBoxSearch* swordsField; SpinBoxSearch* armorsField; SpinBoxSearch* cropsField; SpinBoxSearch* livestockField; SpinBoxSearch* potionsField; DoubleSpinBoxSearch* donationsField; public: SearchWidget(QWidget* = nullptr); signals: void applyFilter(const Filter&); void removeFiltered(); }; #endif // SEARCHWIDGET_H
[ "siragna.marco@gmail.com" ]
siragna.marco@gmail.com
59e15fdf41d16c4d9a7c648a3108d200c25ef0f6
b6c1c4817858cfbd52b44ce2905461347134d743
/src/rpcmining.cpp
9e1b6798b770d2e26c3d467176937d6b1db01145
[ "MIT" ]
permissive
nubescoin/nubescoin
bf5b68bee8c0238d3b406a75d90e2124167d30eb
e576dea0fd1872520d0b169f094e92791a41e944
refs/heads/master
2021-07-15T18:32:33.316545
2017-10-19T15:47:49
2017-10-19T15:47:49
107,476,496
0
0
null
null
null
null
UTF-8
C++
false
false
21,105
cpp
// Copyright (c) 2010 Satoshi Nakamoto // Copyright (c) 2009-2012 The Bitcoin developers // Distributed under the MIT/X11 software license, see the accompanying // file COPYING or http://www.opensource.org/licenses/mit-license.php. #include "main.h" #include "db.h" #include "init.h" #include "bitcoinrpc.h" using namespace json_spirit; using namespace std; // Return average network hashes per second based on the last 'lookup' blocks, // or from the last difficulty change if 'lookup' is nonpositive. // If 'height' is nonnegative, compute the estimate at the time when a given block was found. Value GetNetworkHashPS(int lookup, int height) { CBlockIndex *pb = pindexBest; if (height >= 0 && height < nBestHeight) pb = FindBlockByHeight(height); if (pb == NULL || !pb->nHeight) return 0; // If lookup is -1, then use blocks since last difficulty change. if (lookup <= 0) lookup = pb->nHeight % 2016 + 1; // If lookup is larger than chain, then set it to chain length. if (lookup > pb->nHeight) lookup = pb->nHeight; CBlockIndex *pb0 = pb; int64 minTime = pb0->GetBlockTime(); int64 maxTime = minTime; for (int i = 0; i < lookup; i++) { pb0 = pb0->pprev; int64 time = pb0->GetBlockTime(); minTime = std::min(time, minTime); maxTime = std::max(time, maxTime); } // In case there's a situation where minTime == maxTime, we don't want a divide by zero exception. if (minTime == maxTime) return 0; uint256 workDiff = pb->nChainWork - pb0->nChainWork; int64 timeDiff = maxTime - minTime; return (boost::int64_t)(workDiff.getdouble() / timeDiff); } Value getnetworkhashps(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getnetworkhashps [blocks] [height]\n" "Returns the estimated network hashes per second based on the last 120 blocks.\n" "Pass in [blocks] to override # of blocks, -1 specifies since last difficulty change.\n" "Pass in [height] to estimate the network speed at the time when a certain block was found."); return GetNetworkHashPS(params.size() > 0 ? params[0].get_int() : 120, params.size() > 1 ? params[1].get_int() : -1); } // Key used by getwork/getblocktemplate miners. // Allocated in InitRPCMining, free'd in ShutdownRPCMining static CReserveKey* pMiningKey = NULL; void InitRPCMining() { if (!pwalletMain) return; // getwork/getblocktemplate mining rewards paid here: pMiningKey = new CReserveKey(pwalletMain); } void ShutdownRPCMining() { if (!pMiningKey) return; delete pMiningKey; pMiningKey = NULL; } Value getgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getgenerate\n" "Returns true or false."); if (!pMiningKey) return false; return GetBoolArg("-gen"); } Value setgenerate(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "setgenerate <generate> [genproclimit]\n" "<generate> is true or false to turn generation on or off.\n" "Generation is limited to [genproclimit] processors, -1 is unlimited."); bool fGenerate = true; if (params.size() > 0) fGenerate = params[0].get_bool(); if (params.size() > 1) { int nGenProcLimit = params[1].get_int(); mapArgs["-genproclimit"] = itostr(nGenProcLimit); if (nGenProcLimit == 0) fGenerate = false; } mapArgs["-gen"] = (fGenerate ? "1" : "0"); assert(pwalletMain != NULL); GenerateBitcoins(fGenerate, pwalletMain); return Value::null; } Value gethashespersec(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "gethashespersec\n" "Returns a recent hashes per second performance measurement while generating."); if (GetTimeMillis() - nHPSTimerStart > 8000) return (boost::int64_t)0; return (boost::int64_t)dHashesPerSec; } Value getmininginfo(const Array& params, bool fHelp) { if (fHelp || params.size() != 0) throw runtime_error( "getmininginfo\n" "Returns an object containing mining-related information."); Object obj; obj.push_back(Pair("blocks", (int)nBestHeight)); obj.push_back(Pair("currentblocksize",(uint64_t)nLastBlockSize)); obj.push_back(Pair("currentblocktx",(uint64_t)nLastBlockTx)); obj.push_back(Pair("difficulty", (double)GetDifficulty())); obj.push_back(Pair("errors", GetWarnings("statusbar"))); obj.push_back(Pair("generate", GetBoolArg("-gen"))); obj.push_back(Pair("genproclimit", (int)GetArg("-genproclimit", -1))); obj.push_back(Pair("hashespersec", gethashespersec(params, false))); obj.push_back(Pair("networkhashps", getnetworkhashps(params, false))); obj.push_back(Pair("pooledtx", (uint64_t)mempool.size())); obj.push_back(Pair("testnet", fTestNet)); return obj; } Value getworkex(const Array& params, bool fHelp) { if (fHelp || params.size() > 2) throw runtime_error( "getworkex [data, coinbase]\n" "If [data, coinbase] is not specified, returns extended work data.\n" ); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Nubescoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Nubescoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; static CReserveKey reservekey(pwalletMain); if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); CTransaction coinbaseTx = pblock->vtx[0]; std::vector<uint256> merkle = pblock->GetMerkleBranch(0); Object result; result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << coinbaseTx; result.push_back(Pair("coinbase", HexStr(ssTx.begin(), ssTx.end()))); Array merkle_arr; BOOST_FOREACH(uint256 merkleh, merkle) { printf("%s\n", merkleh.ToString().c_str()); merkle_arr.push_back(HexStr(BEGIN(merkleh), END(merkleh))); } result.push_back(Pair("merkle", merkle_arr)); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); vector<unsigned char> coinbase; if(params.size() == 2) coinbase = ParseHex(params[1].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; if(coinbase.size() == 0) pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; else CDataStream(coinbase, SER_NETWORK, PROTOCOL_VERSION) >> pblock->vtx[0]; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); return CheckWork(pblock, *pwalletMain, reservekey); } } Value getwork(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getwork [data]\n" "If [data] is not specified, returns formatted hash data to work on:\n" " \"midstate\" : precomputed hash state after hashing the first half of the data (DEPRECATED)\n" // deprecated " \"data\" : block data\n" " \"hash1\" : formatted hash buffer for second hash (DEPRECATED)\n" // deprecated " \"target\" : little endian hash target\n" "If [data] is specified, tries to solve the block and returns true if it was successful."); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Nubescoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Nubescoin is downloading blocks..."); typedef map<uint256, pair<CBlock*, CScript> > mapNewBlock_t; static mapNewBlock_t mapNewBlock; // FIXME: thread safety static vector<CBlockTemplate*> vNewBlockTemplate; if (params.size() == 0) { // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 60)) { if (pindexPrev != pindexBest) { // Deallocate old blocks since they're obsolete now mapNewBlock.clear(); BOOST_FOREACH(CBlockTemplate* pblocktemplate, vNewBlockTemplate) delete pblocktemplate; vNewBlockTemplate.clear(); } // Clear pindexPrev so future getworks make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block pblocktemplate = CreateNewBlockWithKey(*pMiningKey); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); vNewBlockTemplate.push_back(pblocktemplate); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; // Update nExtraNonce static unsigned int nExtraNonce = 0; IncrementExtraNonce(pblock, pindexPrev, nExtraNonce); // Save mapNewBlock[pblock->hashMerkleRoot] = make_pair(pblock, pblock->vtx[0].vin[0].scriptSig); // Pre-build hash buffers char pmidstate[32]; char pdata[128]; char phash1[64]; FormatHashBuffers(pblock, pmidstate, pdata, phash1); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); Object result; result.push_back(Pair("midstate", HexStr(BEGIN(pmidstate), END(pmidstate)))); // deprecated result.push_back(Pair("data", HexStr(BEGIN(pdata), END(pdata)))); result.push_back(Pair("hash1", HexStr(BEGIN(phash1), END(phash1)))); // deprecated result.push_back(Pair("target", HexStr(BEGIN(hashTarget), END(hashTarget)))); return result; } else { // Parse parameters vector<unsigned char> vchData = ParseHex(params[0].get_str()); if (vchData.size() != 128) throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid parameter"); CBlock* pdata = (CBlock*)&vchData[0]; // Byte reverse for (int i = 0; i < 128/4; i++) ((unsigned int*)pdata)[i] = ByteReverse(((unsigned int*)pdata)[i]); // Get saved block if (!mapNewBlock.count(pdata->hashMerkleRoot)) return false; CBlock* pblock = mapNewBlock[pdata->hashMerkleRoot].first; pblock->nTime = pdata->nTime; pblock->nNonce = pdata->nNonce; pblock->vtx[0].vin[0].scriptSig = mapNewBlock[pdata->hashMerkleRoot].second; pblock->hashMerkleRoot = pblock->BuildMerkleTree(); assert(pwalletMain != NULL); return CheckWork(pblock, *pwalletMain, *pMiningKey); } } Value getblocktemplate(const Array& params, bool fHelp) { if (fHelp || params.size() > 1) throw runtime_error( "getblocktemplate [params]\n" "Returns data needed to construct a block to work on:\n" " \"version\" : block version\n" " \"previousblockhash\" : hash of current highest block\n" " \"transactions\" : contents of non-coinbase transactions that should be included in the next block\n" " \"coinbaseaux\" : data that should be included in coinbase\n" " \"coinbasevalue\" : maximum allowable input to coinbase transaction, including the generation award and transaction fees\n" " \"target\" : hash target\n" " \"mintime\" : minimum timestamp appropriate for next block\n" " \"curtime\" : current timestamp\n" " \"mutable\" : list of ways the block template may be changed\n" " \"noncerange\" : range of valid nonces\n" " \"sigoplimit\" : limit of sigops in blocks\n" " \"sizelimit\" : limit of block size\n" " \"bits\" : compressed target of next block\n" " \"height\" : height of the next block\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); std::string strMode = "template"; if (params.size() > 0) { const Object& oparam = params[0].get_obj(); const Value& modeval = find_value(oparam, "mode"); if (modeval.type() == str_type) strMode = modeval.get_str(); else if (modeval.type() == null_type) { /* Do nothing */ } else throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); } if (strMode != "template") throw JSONRPCError(RPC_INVALID_PARAMETER, "Invalid mode"); if (vNodes.empty()) throw JSONRPCError(RPC_CLIENT_NOT_CONNECTED, "Nubescoin is not connected!"); if (IsInitialBlockDownload()) throw JSONRPCError(RPC_CLIENT_IN_INITIAL_DOWNLOAD, "Nubescoin is downloading blocks..."); // Update block static unsigned int nTransactionsUpdatedLast; static CBlockIndex* pindexPrev; static int64 nStart; static CBlockTemplate* pblocktemplate; if (pindexPrev != pindexBest || (nTransactionsUpdated != nTransactionsUpdatedLast && GetTime() - nStart > 5)) { // Clear pindexPrev so future calls make a new block, despite any failures from here on pindexPrev = NULL; // Store the pindexBest used before CreateNewBlock, to avoid races nTransactionsUpdatedLast = nTransactionsUpdated; CBlockIndex* pindexPrevNew = pindexBest; nStart = GetTime(); // Create new block if(pblocktemplate) { delete pblocktemplate; pblocktemplate = NULL; } CScript scriptDummy = CScript() << OP_TRUE; pblocktemplate = CreateNewBlock(scriptDummy); if (!pblocktemplate) throw JSONRPCError(RPC_OUT_OF_MEMORY, "Out of memory"); // Need to update only after we know CreateNewBlock succeeded pindexPrev = pindexPrevNew; } CBlock* pblock = &pblocktemplate->block; // pointer for convenience // Update nTime pblock->UpdateTime(pindexPrev); pblock->nNonce = 0; Array transactions; map<uint256, int64_t> setTxIndex; int i = 0; BOOST_FOREACH (CTransaction& tx, pblock->vtx) { uint256 txHash = tx.GetHash(); setTxIndex[txHash] = i++; if (tx.IsCoinBase()) continue; Object entry; CDataStream ssTx(SER_NETWORK, PROTOCOL_VERSION); ssTx << tx; entry.push_back(Pair("data", HexStr(ssTx.begin(), ssTx.end()))); entry.push_back(Pair("hash", txHash.GetHex())); Array deps; BOOST_FOREACH (const CTxIn &in, tx.vin) { if (setTxIndex.count(in.prevout.hash)) deps.push_back(setTxIndex[in.prevout.hash]); } entry.push_back(Pair("depends", deps)); int index_in_template = i - 1; entry.push_back(Pair("fee", pblocktemplate->vTxFees[index_in_template])); entry.push_back(Pair("sigops", pblocktemplate->vTxSigOps[index_in_template])); transactions.push_back(entry); } Object aux; aux.push_back(Pair("flags", HexStr(COINBASE_FLAGS.begin(), COINBASE_FLAGS.end()))); uint256 hashTarget = CBigNum().SetCompact(pblock->nBits).getuint256(); static Array aMutable; if (aMutable.empty()) { aMutable.push_back("time"); aMutable.push_back("transactions"); aMutable.push_back("prevblock"); } Object result; result.push_back(Pair("version", pblock->nVersion)); result.push_back(Pair("previousblockhash", pblock->hashPrevBlock.GetHex())); result.push_back(Pair("transactions", transactions)); result.push_back(Pair("coinbaseaux", aux)); result.push_back(Pair("coinbasevalue", (int64_t)pblock->vtx[0].vout[0].nValue)); result.push_back(Pair("target", hashTarget.GetHex())); result.push_back(Pair("mintime", (int64_t)pindexPrev->GetMedianTimePast()+1)); result.push_back(Pair("mutable", aMutable)); result.push_back(Pair("noncerange", "00000000ffffffff")); result.push_back(Pair("sigoplimit", (int64_t)MAX_BLOCK_SIGOPS)); result.push_back(Pair("sizelimit", (int64_t)MAX_BLOCK_SIZE)); result.push_back(Pair("curtime", (int64_t)pblock->nTime)); result.push_back(Pair("bits", HexBits(pblock->nBits))); result.push_back(Pair("height", (int64_t)(pindexPrev->nHeight+1))); return result; } Value submitblock(const Array& params, bool fHelp) { if (fHelp || params.size() < 1 || params.size() > 2) throw runtime_error( "submitblock <hex data> [optional-params-obj]\n" "[optional-params-obj] parameter is currently ignored.\n" "Attempts to submit new block to network.\n" "See https://en.bitcoin.it/wiki/BIP_0022 for full specification."); vector<unsigned char> blockData(ParseHex(params[0].get_str())); CDataStream ssBlock(blockData, SER_NETWORK, PROTOCOL_VERSION); CBlock pblock; try { ssBlock >> pblock; } catch (std::exception &e) { throw JSONRPCError(RPC_DESERIALIZATION_ERROR, "Block decode failed"); } CValidationState state; bool fAccepted = ProcessBlock(state, NULL, &pblock); if (!fAccepted) return "rejected"; // TODO: report validation state return Value::null; }
[ "nubes339@gmail.com" ]
nubes339@gmail.com
a6a3c19eb1f153ef2c78dff0e580d42c7d949c3d
387549ab27d89668e656771a19c09637612d57ed
/DRGLib UE project/Source/FSD/Private/IconGenerationCharacter.cpp
8961cf0f085d7191ab47eab8f2eb83e14bf6d445
[ "MIT" ]
permissive
SamsDRGMods/DRGLib
3b7285488ef98b7b22ab4e00fec64a4c3fb6a30a
76f17bc76dd376f0d0aa09400ac8cb4daad34ade
refs/heads/main
2023-07-03T10:37:47.196444
2023-04-07T23:18:54
2023-04-07T23:18:54
383,509,787
16
5
MIT
2023-04-07T23:18:55
2021-07-06T15:08:14
C++
UTF-8
C++
false
false
413
cpp
#include "IconGenerationCharacter.h" #include "Components/SkeletalMeshComponent.h" AIconGenerationCharacter::AIconGenerationCharacter() { this->OrigBaseMaterial = NULL; this->Mesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("CharacterMesh0")); this->BodyMesh = CreateDefaultSubobject<USkeletalMeshComponent>(TEXT("BodyMesh")); this->HairColor = NULL; this->ArmorMaterial = NULL; }
[ "samamstar@gmail.com" ]
samamstar@gmail.com
eb127af6f8b814ab03c6aea8b408341bc4a58254
a980ba973c6365b2b2f11a1af443191596ded453
/lib/Secrets/interactionrequest_p.h
1ae3480107a3b84f14ef1f3cc6dafae998e6df89
[ "LicenseRef-scancode-free-unknown", "BSD-3-Clause" ]
permissive
sailfishos/sailfish-secrets
44f724f1470e7b4bbfbd4c0ab4cb481cbc54f2e0
303687d1e4e71cf741b6aec3b35dd78c033b1ede
refs/heads/master
2023-04-07T06:44:07.878773
2023-03-21T10:41:41
2023-03-21T10:41:41
109,001,458
27
16
BSD-3-Clause
2023-08-31T14:14:11
2017-10-31T13:43:11
C++
UTF-8
C++
false
false
1,068
h
/* * Copyright (C) 2018 Jolla Ltd. * Contact: Chris Adams <chris.adams@jollamobile.com> * All rights reserved. * BSD 3-Clause License, see LICENSE. */ #ifndef LIBSAILFISHSECRETS_INTERACTIONREQUEST_P_H #define LIBSAILFISHSECRETS_INTERACTIONREQUEST_P_H #include "Secrets/secretsglobal.h" #include "Secrets/secretmanager.h" #include "Secrets/secret.h" #include <QtCore/QPointer> #include <QtCore/QScopedPointer> #include <QtCore/QString> #include <QtDBus/QDBusPendingCallWatcher> namespace Sailfish { namespace Secrets { class InteractionRequestPrivate { Q_DISABLE_COPY(InteractionRequestPrivate) public: explicit InteractionRequestPrivate(); QPointer<Sailfish::Secrets::SecretManager> m_manager; Sailfish::Secrets::InteractionParameters m_interactionParameters; QByteArray m_userInput; QScopedPointer<QDBusPendingCallWatcher> m_watcher; Sailfish::Secrets::Request::Status m_status; Sailfish::Secrets::Result m_result; }; } // namespace Secrets } // namespace Sailfish #endif // LIBSAILFISHSECRETS_INTERACTIONREQUEST_P_H
[ "chris.adams@jollamobile.com" ]
chris.adams@jollamobile.com
25cff727807c8fa7e37bd6fd7dead89c61b341ae
612d802d187d8dfe3d6fdfa160dbf334caecc72d
/RTProtocol.cpp
68223ecdb226a4acb553c8a552d87863cef895ef
[ "MIT" ]
permissive
kristianmk/qualisys_cpp_sdk
af9f9c78ffeb231e7432119fc952ad8cf4b71140
06c01cbac0f11c8438f86e37c2870687f8564dec
refs/heads/master
2020-04-17T08:10:56.141126
2019-01-15T16:38:35
2019-01-15T16:38:35
null
0
0
null
null
null
null
UTF-8
C++
false
false
155,112
cpp
#include "RTProtocol.h" #include "Markup.h" #include "Network.h" #include <float.h> #include <iphlpapi.h> #include <cctype> #include <thread> // import the internet protocol helper library. #pragma comment(lib, "IPHLPAPI.lib") #pragma warning(push) #pragma warning(disable : 4244) #include <algorithm> #pragma warning( pop ) namespace { inline void ToLower(std::string& str) { std::transform(str.begin(), str.end(), str.begin(), std::tolower); } inline void RemoveInvalidChars(std::string& str) { auto isInvalidChar = [](int c) -> int { // iscntrl: control codes (NUL, etc.), '\t', '\n', '\v', '\f', '\r', backspace (DEL) // isspace: some common checks but also 0x20 (SPACE) // return != 0 --> invalid char return std::iscntrl(c) + std::isspace(c); }; str.erase(std::remove_if(str.begin(), str.end(), isInvalidChar), str.end()); } } CRTProtocol::CRTProtocol() { mpoNetwork = new CNetwork(); mpoRTPacket = NULL; meLastEvent = CRTPacket::EventCaptureStopped; meState = CRTPacket::EventCaptureStopped; mnMajorVersion = 1; mnMinorVersion = 0; mbBigEndian = false; maErrorStr[0] = 0; mnBroadcastPort = 0; mpFileBuffer = NULL; mDataBuffSize = 65535; maDataBuff = new char[mDataBuffSize]; mbIsMaster = false; } // CRTProtocol CRTProtocol::~CRTProtocol() { if (mpoNetwork) { delete mpoNetwork; mpoNetwork = NULL; } if (mpoRTPacket) { delete mpoRTPacket; mpoRTPacket = NULL; } } // ~CRTProtocol bool CRTProtocol::Connect(const char* pServerAddr, unsigned short nPort, unsigned short* pnUDPServerPort, int nMajorVersion, int nMinorVersion, bool bBigEndian) { CRTPacket::EPacketType eType; char tTemp[100]; char pResponseStr[256]; mbBigEndian = bBigEndian; mbIsMaster = false; mnMajorVersion = 1; if ((nMajorVersion == 1) && (nMinorVersion == 0)) { mnMinorVersion = 0; } else { mnMinorVersion = 1; if (mbBigEndian) { nPort += 2; } else { nPort += 1; } } if (mpoRTPacket) { delete mpoRTPacket; } mpoRTPacket = new CRTPacket(nMajorVersion, nMinorVersion, bBigEndian); if (mpoRTPacket == NULL) { sprintf_s(maErrorStr, sizeof(maErrorStr), "Could not allocate data packet."); return false; } if (mpoNetwork->Connect(pServerAddr, nPort)) { if (pnUDPServerPort != NULL) { if (mpoNetwork->CreateUDPSocket(*pnUDPServerPort) == false) { sprintf_s(maErrorStr, sizeof(maErrorStr), "CreateUDPSocket failed. %s", mpoNetwork->GetErrorString()); Disconnect(); return false; } } // Welcome message if (ReceiveRTPacket(eType, true) > 0) { if (eType == CRTPacket::PacketError) { strcpy_s(maErrorStr, sizeof(maErrorStr), mpoRTPacket->GetErrorString()); Disconnect(); return false; } if (eType == CRTPacket::PacketCommand) { if (strcmp("QTM RT Interface connected", mpoRTPacket->GetCommandString()) == 0) { // Set protocol version if (SetVersion(nMajorVersion, nMinorVersion)) { // Set byte order. // Unless we use protocol version 1.0, we have set the byte order by selecting the correct port. if ((mnMajorVersion == 1) && (mnMinorVersion == 0)) { if (mbBigEndian) { sprintf_s(tTemp, sizeof(tTemp), "ByteOrder BigEndian"); } else { sprintf_s(tTemp, sizeof(tTemp), "ByteOrder LittleEndian"); } if (SendCommand(tTemp, pResponseStr, sizeof(pResponseStr))) { return true; } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Set byte order failed."); } } else { GetState(meState, true); return true; } } Disconnect(); return false; } } } sprintf_s(maErrorStr, sizeof(maErrorStr), "Missing QTM server welcome message."); Disconnect(); } else { if (mpoNetwork->GetError() == 10061) { sprintf_s(maErrorStr, sizeof(maErrorStr), "Check if QTM is running on target machine."); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s", mpoNetwork->GetErrorString()); } } return false; } // Connect unsigned short CRTProtocol::GetUdpServerPort() { if (mpoNetwork) { return mpoNetwork->GetUdpServerPort(); } return 0; } void CRTProtocol::Disconnect() { mpoNetwork->Disconnect(); mnBroadcastPort = 0; if (mpoRTPacket) { delete mpoRTPacket; mpoRTPacket = NULL; } mbIsMaster = false; } // Disconnect bool CRTProtocol::Connected() { return mpoNetwork->Connected(); } bool CRTProtocol::SetVersion(int nMajorVersion, int nMinorVersion) { char tTemp[256]; char pResponseStr[256]; sprintf_s(tTemp, sizeof(tTemp), "Version %u.%u", nMajorVersion, nMinorVersion); if (SendCommand(tTemp, pResponseStr, sizeof(pResponseStr))) { sprintf_s(tTemp, sizeof(tTemp), "Version set to %u.%u", nMajorVersion, nMinorVersion); if (strcmp(pResponseStr, tTemp) == 0) { mnMajorVersion = nMajorVersion; mnMinorVersion = nMinorVersion; mpoRTPacket->SetVersion(mnMajorVersion, mnMinorVersion); return true; } if (pResponseStr) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Set Version failed."); } } else { strcpy_s(tTemp, sizeof(tTemp), maErrorStr); sprintf_s(maErrorStr, sizeof(maErrorStr), "Send Version failed. %s.", tTemp); } return false; } bool CRTProtocol::GetVersion(unsigned int &nMajorVersion, unsigned int &nMinorVersion) { if (!Connected()) { return false; } nMajorVersion = mnMajorVersion; nMinorVersion = mnMinorVersion; return true; } bool CRTProtocol::GetQTMVersion(char* pVersion, unsigned int nVersionLen) { if (SendCommand("QTMVersion", pVersion, nVersionLen)) { return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "Get QTM Version failed."); return false; } bool CRTProtocol::GetByteOrder(bool &bBigEndian) { char pResponseStr[256]; if (SendCommand("ByteOrder", pResponseStr, sizeof(pResponseStr))) { bBigEndian = (strcmp(pResponseStr, "Byte order is big endian") == 0); return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "Get Byte order failed."); return false; } bool CRTProtocol::CheckLicense(const char* pLicenseCode) { char tTemp[100]; char pResponseStr[256]; if (strlen(pLicenseCode) <= 85) { sprintf_s(tTemp, sizeof(tTemp), "CheckLicense %s", pLicenseCode); if (SendCommand(tTemp, pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "License pass") == 0) { return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "Wrong license code."); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "CheckLicense failed."); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "License code too long."); } return false; } bool CRTProtocol::DiscoverRTServer(unsigned short nServerPort, bool bNoLocalResponses, unsigned short nDiscoverPort) { char pData[10]; SDiscoverResponse sResponse; if (mnBroadcastPort > 0 || mpoNetwork->CreateUDPSocket(nServerPort, true)) { if (mnBroadcastPort == 0) { mnBroadcastPort = nServerPort; } else { nServerPort = mnBroadcastPort; } *((unsigned int*)pData) = (unsigned int)10; *((unsigned int*)(pData + 4)) = (unsigned int)CRTPacket::PacketDiscover; *((unsigned short*)(pData + 8)) = htons(nServerPort); if (mpoNetwork->SendUDPBroadcast(pData, 10, nDiscoverPort)) { int nReceived; unsigned int nAddr; mvsDiscoverResponseList.clear(); do { nReceived = mpoNetwork->Receive(maDataBuff, mDataBuffSize, false, 100000, &nAddr); if (nReceived != -1 && nReceived != -2 && nReceived > 8) { char* pResponseStr; if (CRTPacket::GetType(maDataBuff) == CRTPacket::PacketCommand) { pResponseStr = CRTPacket::GetCommandString(maDataBuff); sResponse.nAddr = nAddr; sResponse.nBasePort = CRTPacket::GetDiscoverResponseBasePort(maDataBuff); if (pResponseStr && (!bNoLocalResponses || !mpoNetwork->IsLocalAddress(nAddr))) { strcpy_s(sResponse.pMessage, sizeof(sResponse.pMessage), pResponseStr); mvsDiscoverResponseList.push_back(sResponse); } } } } while (nReceived != -1 && nReceived != -2 && nReceived > 8); // Keep reading until no more responses. return true; } } return false; } int CRTProtocol::GetNumberOfDiscoverResponses() { return (int)mvsDiscoverResponseList.size(); } bool CRTProtocol::GetDiscoverResponse(unsigned int nIndex, unsigned int &nAddr, unsigned short &nBasePort, char* pMessage, int nMessageLen) { if (nIndex < mvsDiscoverResponseList.size()) { nAddr = mvsDiscoverResponseList[nIndex].nAddr; nBasePort = mvsDiscoverResponseList[nIndex].nBasePort; strcpy_s(pMessage, nMessageLen, mvsDiscoverResponseList[nIndex].pMessage); return true; } return false; } bool CRTProtocol::GetCurrentFrame(unsigned int nComponentType, const SComponentOptions& componentOptions) { char pCommandStr[256]; sprintf_s(pCommandStr, sizeof(pCommandStr), "GetCurrentFrame "); std::string::size_type nCommandStrSize = strlen(pCommandStr); if (GetComponentString(pCommandStr + (int)nCommandStrSize, sizeof(pCommandStr) - (int)nCommandStrSize, nComponentType, componentOptions)) { if (SendCommand(pCommandStr)) { return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "GetCurrentFrame failed."); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "DataComponent missing."); } return false; } bool CRTProtocol::StreamFrames(EStreamRate eRate, unsigned int nRateArg, unsigned short nUDPPort, const char* pUDPAddr, unsigned int nComponentType, const SComponentOptions& componentOptions) { char pCommandStr[256]; if (eRate == RateFrequencyDivisor) { sprintf_s(pCommandStr, sizeof(pCommandStr), "StreamFrames FrequencyDivisor:%d ", nRateArg); } else if (eRate == RateFrequency) { sprintf_s(pCommandStr, sizeof(pCommandStr), "StreamFrames Frequency:%d ", nRateArg); } else if (eRate == RateAllFrames) { sprintf_s(pCommandStr, sizeof(pCommandStr), "StreamFrames AllFrames "); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "No valid rate."); return false; } if (nUDPPort > 0) { if (pUDPAddr != NULL && strlen(pUDPAddr) > 64) { sprintf_s(maErrorStr, sizeof(maErrorStr), "UDP address string too long."); return false; } sprintf_s(pCommandStr, sizeof(pCommandStr), "%s UDP%s%s:%d ", pCommandStr, pUDPAddr != NULL ? ":" : "", pUDPAddr != NULL ? pUDPAddr : "", nUDPPort); } std::string::size_type nCommandStrSize = strlen(pCommandStr); if (GetComponentString(pCommandStr + (int)nCommandStrSize, sizeof(pCommandStr) - (int)nCommandStrSize, nComponentType, componentOptions)) { if (SendCommand(pCommandStr)) { return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "StreamFrames failed."); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "DataComponent missing."); } return false; } bool CRTProtocol::StreamFramesStop() { if (SendCommand("StreamFrames Stop")) { return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "StreamFrames Stop failed."); return false; } bool CRTProtocol::GetState(CRTPacket::EEvent &eEvent, bool bUpdate, int nTimeout) { CRTPacket::EPacketType eType; if (bUpdate) { bool result; if (mnMajorVersion > 1 || mnMinorVersion > 9) { result = SendCommand("GetState"); } else { result = SendCommand("GetLastEvent"); } if (result) { int nReceived; do { nReceived = ReceiveRTPacket(eType, false, nTimeout); if (nReceived > 0) { if (mpoRTPacket->GetEvent(eEvent)) { return true; } } } while (nReceived > 0); } sprintf_s(maErrorStr, sizeof(maErrorStr), "GetLastEvent failed."); } else { eEvent = meState; return true; } return false; } bool CRTProtocol::GetCapture(const char* pFileName, bool bC3D) { CRTPacket::EPacketType eType; char pResponseStr[256]; if (fopen_s(&mpFileBuffer, pFileName, "wb") == 0) { if (bC3D) { // C3D file if (SendCommand((mnMajorVersion > 1 || mnMinorVersion > 7) ? "GetCaptureC3D" : "GetCapture", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Sending capture") == 0) { if (ReceiveRTPacket(eType, true, 5000000) > 0) // Wait for C3D file in 5 seconds. { if (eType == CRTPacket::PacketC3DFile) { if (mpFileBuffer != NULL) { fclose(mpFileBuffer); return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "Writing C3D file failed."); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Wrong packet type received."); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "No packet received."); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s failed.", (mnMajorVersion > 1 || mnMinorVersion > 7) ? "GetCaptureC3D" : "GetCapture"); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s failed.", (mnMajorVersion > 1 || mnMinorVersion > 7) ? "GetCaptureC3D" : "GetCapture"); } } else { // QTM file if (SendCommand("GetCaptureQTM", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Sending capture") == 0) { if (ReceiveRTPacket(eType, true, 5000000) > 0) // Wait for QTM file in 5 seconds. { if (eType == CRTPacket::PacketQTMFile) { if (mpFileBuffer != NULL) { fclose(mpFileBuffer); return true; } sprintf_s(maErrorStr, sizeof(maErrorStr), "Writing QTM file failed."); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Wrong packet type received."); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "No packet received. %s.", maErrorStr); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetCaptureQTM failed."); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetCaptureQTM failed."); } } } if (mpFileBuffer) { fclose(mpFileBuffer); } return false; } bool CRTProtocol::SendTrig() { char pResponseStr[256]; if (SendCommand("Trig", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Trig ok") == 0) { return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Trig failed."); } return false; } bool CRTProtocol::SetQTMEvent(const char* pLabel) { char tTemp[100]; char pResponseStr[256]; if (strlen(pLabel) <= 92) { sprintf_s(tTemp, sizeof(tTemp), "%s %s", (mnMajorVersion > 1 || mnMinorVersion > 7) ? "SetQTMEvent" : "Event", pLabel); if (SendCommand(tTemp, pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Event set") == 0) { return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s failed.", (mnMajorVersion > 1 || mnMinorVersion > 7) ? "SetQTMEvent" : "Event"); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Event label too long."); } return false; } bool CRTProtocol::TakeControl(const char* pPassword) { char pResponseStr[256]; char pCmd[64]; sprintf_s(pCmd, sizeof(pCmd), "TakeControl"); if (pPassword != NULL) { // Add password if (pPassword[0] != 0) { strcat_s(pCmd, sizeof(pCmd), " "); strcat_s(pCmd, sizeof(pCmd), pPassword); } } if (SendCommand(pCmd, pResponseStr, sizeof(pResponseStr))) { if (strcmp("You are now master", pResponseStr) == 0 || strcmp("You are already master", pResponseStr) == 0) { mbIsMaster = true; return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "TakeControl failed."); } mbIsMaster = false; return false; } // TakeControl bool CRTProtocol::ReleaseControl() { char pResponseStr[256]; if (SendCommand("ReleaseControl", pResponseStr, sizeof(pResponseStr))) { if (strcmp("You are now a regular client", pResponseStr) == 0 || strcmp("You are already a regular client", pResponseStr) == 0) { mbIsMaster = false; return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "ReleaseControl failed."); } return false; } // ReleaseControl bool CRTProtocol::IsControlling() { return mbIsMaster; } bool CRTProtocol::NewMeasurement() { char pResponseStr[256]; if (SendCommand("New", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Creating new connection") == 0 || strcmp(pResponseStr, "Already connected") == 0) { return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "New failed."); } return false; } bool CRTProtocol::CloseMeasurement() { char pResponseStr[256]; if (SendCommand("Close", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Closing connection") == 0 || strcmp(pResponseStr, "File closed") == 0 || strcmp(pResponseStr, "Closing file") == 0 || strcmp(pResponseStr, "No connection to close") == 0) { return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Close failed."); } return false; } bool CRTProtocol::StartCapture() { char pResponseStr[256]; if (SendCommand("Start", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Starting measurement") == 0) { return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Start failed."); } return false; } bool CRTProtocol::StartRTOnFile() { char pResponseStr[256]; if (SendCommand("Start rtfromfile", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Starting RT from file") == 0) { return true; } } if (pResponseStr) { if (strcmp(pResponseStr, "RT from file already running") == 0) { return true; } sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Starting RT from file failed."); } return false; } bool CRTProtocol::StopCapture() { char pResponseStr[256]; if (SendCommand("Stop", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Stopping measurement") == 0) { return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Stop failed."); } return false; } bool CRTProtocol::LoadCapture(const char* pFileName) { char tTemp[100]; char pResponseStr[256]; if (strlen(pFileName) <= 94) { sprintf_s(tTemp, sizeof(tTemp), "Load %s", pFileName); if (SendCommand(tTemp, pResponseStr, sizeof(pResponseStr), 20000000)) // Set timeout to 20 s for Load command. { if (strcmp(pResponseStr, "Measurement loaded") == 0) { return true; } } if (strlen(pResponseStr) > 0) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Load failed."); } } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "File name too long."); } return false; } bool CRTProtocol::SaveCapture(const char* pFileName, bool bOverwrite, char* pNewFileName, int nSizeOfNewFileName) { char tTemp[100]; char pResponseStr[256]; char tNewFileNameTmp[300]; tNewFileNameTmp[0] = 0; if (strlen(pFileName) <= 94) { sprintf_s(tTemp, sizeof(tTemp), "Save %s%s", pFileName, bOverwrite ? " Overwrite" : ""); if (SendCommand(tTemp, pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Measurement saved") == 0) { if (pNewFileName && nSizeOfNewFileName > 0) { pNewFileName[0] = 0; } return true; } if (sscanf_s(pResponseStr, "Measurement saved as '%[^']'", tNewFileNameTmp, (int)sizeof(tNewFileNameTmp)) == 1) { if (pNewFileName) { strcpy_s(pNewFileName, nSizeOfNewFileName, tNewFileNameTmp); } return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Save failed."); } } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "File name too long."); } return false; } bool CRTProtocol::LoadProject(const char* pFileName) { char tTemp[100]; char pResponseStr[256]; if (strlen(pFileName) <= 94) { sprintf_s(tTemp, sizeof(tTemp), "LoadProject %s", pFileName); if (SendCommand(tTemp, pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Project loaded") == 0) { return true; } } if (pResponseStr) { sprintf_s (maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Load project failed."); } } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "File name too long."); } return false; } bool CRTProtocol::Reprocess() { char pResponseStr[256]; if (SendCommand("Reprocess", pResponseStr, sizeof(pResponseStr))) { if (strcmp(pResponseStr, "Reprocessing file") == 0) { return true; } } if (pResponseStr) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", pResponseStr); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Reprocess failed."); } return false; } bool CRTProtocol::GetEventString(CRTPacket::EEvent eEvent, char* pStr, int nStrLen) { switch (eEvent) { case CRTPacket::EventConnected: sprintf_s(pStr, nStrLen, "Connected"); break; case CRTPacket::EventConnectionClosed: sprintf_s(pStr, nStrLen, "Connection Closed"); break; case CRTPacket::EventCaptureStarted: sprintf_s(pStr, nStrLen, "Capture Started"); break; case CRTPacket::EventCaptureStopped: sprintf_s(pStr, nStrLen, "Capture Stopped"); break; case CRTPacket::EventCaptureFetchingFinished: sprintf_s(pStr, nStrLen, "Fetching Finished"); break; case CRTPacket::EventCalibrationStarted: sprintf_s(pStr, nStrLen, "Calibration Started"); break; case CRTPacket::EventCalibrationStopped: sprintf_s(pStr, nStrLen, "Calibration Finished"); break; case CRTPacket::EventRTfromFileStarted: sprintf_s(pStr, nStrLen, "RT From File Started"); break; case CRTPacket::EventRTfromFileStopped: sprintf_s(pStr, nStrLen, "RT From File Stopped"); break; case CRTPacket::EventWaitingForTrigger: sprintf_s(pStr, nStrLen, "Waiting For Trigger"); break; case CRTPacket::EventCameraSettingsChanged: sprintf_s(pStr, nStrLen, "Camera Settings Changed"); break; case CRTPacket::EventQTMShuttingDown: sprintf_s(pStr, nStrLen, "QTM Shutting Down"); break; case CRTPacket::EventCaptureSaved: sprintf_s(pStr, nStrLen, "Capture Saved"); break; case CRTPacket::EventReprocessingStarted: sprintf_s(pStr, nStrLen, "Reprocessing Started"); break; case CRTPacket::EventReprocessingStopped: sprintf_s(pStr, nStrLen, "Reprocessing Stopped"); break; case CRTPacket::EventTrigger: sprintf_s(pStr, nStrLen, "Trigger"); break; default: return false; } return true; } bool CRTProtocol::ConvertRateString(const char* pRate, EStreamRate &eRate, unsigned int &nRateArg) { std::string rateString; rateString.assign(pRate); std::transform(rateString.begin(), rateString.end(), rateString.begin(), ::tolower); eRate = RateNone; if (rateString.compare(0, 9, _T("allframes"), 9) == 0) { eRate = RateAllFrames; } else if (rateString.compare(0, 10, _T("frequency:")) == 0) { nRateArg = atoi(rateString.substr(10).c_str()); if (nRateArg > 0) { eRate = RateFrequency; } } else if (rateString.compare(0, 17, _T("frequencydivisor:")) == 0) { nRateArg = atoi(rateString.substr(17).c_str()); if (nRateArg > 0) { eRate = RateFrequencyDivisor; } } return eRate != RateNone; } unsigned int CRTProtocol::ConvertComponentString(const char* pComponentType) { std::string componentString; unsigned int componentTypes = 0; componentString.assign(pComponentType); // Make string lower case. std::transform(componentString.begin(), componentString.end(), componentString.begin(), ::tolower); if (componentString.find(_T("2d")) != std::string::npos) { componentTypes += CRTProtocol::cComponent2d; } if (componentString.find(_T("2dlin")) != std::string::npos) { componentTypes += CRTProtocol::cComponent2dLin; } if (componentString.find(_T("3d")) != std::string::npos) { componentTypes += CRTProtocol::cComponent3d; } if (componentString.find(_T("3dres")) != std::string::npos) { componentTypes += CRTProtocol::cComponent3dRes; } if (componentString.find(_T("3dnolabels")) != std::string::npos) { componentTypes += CRTProtocol::cComponent3dNoLabels; } if (componentString.find(_T("3dnolabelsres")) != std::string::npos) { componentTypes += CRTProtocol::cComponent3dNoLabelsRes; } if (componentString.find(_T("analog")) != std::string::npos) { componentTypes += CRTProtocol::cComponentAnalog; } if (componentString.find(_T("analogsingle")) != std::string::npos) { componentTypes += CRTProtocol::cComponentAnalogSingle; } if (componentString.find(_T("force")) != std::string::npos) { componentTypes += CRTProtocol::cComponentForce; } if (componentString.find(_T("forcesingle")) != std::string::npos) { componentTypes += CRTProtocol::cComponentForceSingle; } if (componentString.find(_T("6d")) != std::string::npos) { componentTypes += CRTProtocol::cComponent6d; } if (componentString.find(_T("6dres")) != std::string::npos) { componentTypes += CRTProtocol::cComponent6dRes; } if (componentString.find(_T("6deuler")) != std::string::npos) { componentTypes += CRTProtocol::cComponent6dEuler; } if (componentString.find(_T("6deulerres")) != std::string::npos) { componentTypes += CRTProtocol::cComponent6dEulerRes; } if (componentString.find(_T("image")) != std::string::npos) { componentTypes += CRTProtocol::cComponentImage; } if (componentString.find(_T("gazevector")) != std::string::npos) { componentTypes += CRTProtocol::cComponentGazeVector; } if (componentString.find(_T("timecode")) != std::string::npos) { componentTypes += CRTProtocol::cComponentTimecode; } if (componentString.find(_T("skeleton")) != std::string::npos) { componentTypes += CRTProtocol::cComponentSkeleton; } return componentTypes; } bool CRTProtocol::GetComponentString(char* pComponentStr, int nComponentStrLen, unsigned int nComponentType, const SComponentOptions& options) { pComponentStr[0] = 0; if (nComponentType & cComponent2d) { strcat_s(pComponentStr, nComponentStrLen, "2D "); } if (nComponentType & cComponent2dLin) { strcat_s(pComponentStr, nComponentStrLen, "2DLin "); } if (nComponentType & cComponent3d) { strcat_s(pComponentStr, nComponentStrLen, "3D "); } if (nComponentType & cComponent3dRes) { strcat_s(pComponentStr, nComponentStrLen, "3DRes "); } if (nComponentType & cComponent3dNoLabels) { strcat_s(pComponentStr, nComponentStrLen, "3DNoLabels "); } if (nComponentType & cComponent3dNoLabelsRes) { strcat_s(pComponentStr, nComponentStrLen, "3DNoLabelsRes "); } if (nComponentType & cComponent6d) { strcat_s(pComponentStr, nComponentStrLen, "6D "); } if (nComponentType & cComponent6dRes) { strcat_s(pComponentStr, nComponentStrLen, "6DRes "); } if (nComponentType & cComponent6dEuler) { strcat_s(pComponentStr, nComponentStrLen, "6DEuler "); } if (nComponentType & cComponent6dEulerRes) { strcat_s(pComponentStr, nComponentStrLen, "6DEulerRes "); } if (nComponentType & cComponentAnalog) { strcat_s(pComponentStr, nComponentStrLen, "Analog"); if (options.mAnalogChannels != nullptr) { strcat_s(pComponentStr, nComponentStrLen, ":"); strcat_s(pComponentStr, nComponentStrLen, options.mAnalogChannels); } strcat_s(pComponentStr, nComponentStrLen, " "); } if (nComponentType & cComponentAnalogSingle) { strcat_s(pComponentStr, nComponentStrLen, "AnalogSingle"); if (options.mAnalogChannels != nullptr) { strcat_s(pComponentStr, nComponentStrLen, ":"); strcat_s(pComponentStr, nComponentStrLen, options.mAnalogChannels); } strcat_s(pComponentStr, nComponentStrLen, " "); } if (nComponentType & cComponentForce) { strcat_s(pComponentStr, nComponentStrLen, "Force "); } if (nComponentType & cComponentForceSingle) { strcat_s(pComponentStr, nComponentStrLen, "ForceSingle "); } if (nComponentType & cComponentGazeVector) { strcat_s(pComponentStr, nComponentStrLen, "GazeVector "); } if (nComponentType & cComponentImage) { strcat_s(pComponentStr, nComponentStrLen, "Image "); } if (nComponentType & cComponentTimecode) { strcat_s(pComponentStr, nComponentStrLen, "Timecode "); } if (nComponentType & cComponentSkeleton) { strcat_s(pComponentStr, nComponentStrLen, "Skeleton"); if (options.mSkeletonGlobalData) { strcat_s(pComponentStr, nComponentStrLen, ":global"); } strcat_s(pComponentStr, nComponentStrLen, " "); } return (pComponentStr[0] != 0); } int CRTProtocol::ReceiveRTPacket(CRTPacket::EPacketType &eType, bool bSkipEvents, int nTimeout) { int nRecved = 0; unsigned int nRecvedTotal = 0; unsigned int nFrameSize; eType = CRTPacket::PacketNone; do { nRecved = 0; nRecvedTotal = 0; nRecved = mpoNetwork->Receive(maDataBuff, mDataBuffSize, true, nTimeout); if (nRecved == 0) { // Receive timeout. sprintf_s(maErrorStr, sizeof(maErrorStr), "Data receive timeout."); return 0; } if (nRecved < sizeof(int) * 2) { // QTM header not received. sprintf_s (maErrorStr, sizeof(maErrorStr), "Couldn't read header bytes."); return -1; } if (nRecved == -1) { sprintf_s (maErrorStr, sizeof(maErrorStr), "Socket Error."); return -1; } if (nRecved == -2) { sprintf_s(maErrorStr, sizeof(maErrorStr), "Disconnected from server."); return -1; } nRecvedTotal += nRecved; bool bBigEndian = (mbBigEndian || (mnMajorVersion == 1 && mnMinorVersion == 0)); nFrameSize = mpoRTPacket->GetSize(maDataBuff, bBigEndian); eType = mpoRTPacket->GetType(maDataBuff, bBigEndian); unsigned int nReadSize; if (eType == CRTPacket::PacketC3DFile || eType == CRTPacket::PacketQTMFile) { if (mpFileBuffer != NULL) { rewind(mpFileBuffer); // Start from the beginning if (fwrite(maDataBuff + sizeof(int) * 2, 1, nRecvedTotal - sizeof(int) * 2, mpFileBuffer) != nRecvedTotal - sizeof(int) * 2) { sprintf_s (maErrorStr, sizeof(maErrorStr), "Failed to write file to disk."); fclose(mpFileBuffer); mpFileBuffer = NULL; return -1; } // Receive more data until we have read the whole packet while (nRecvedTotal < nFrameSize) { nReadSize = nFrameSize - nRecvedTotal; if (nFrameSize > mDataBuffSize) { nReadSize = mDataBuffSize; } // As long as we haven't received enough data, wait for more nRecved = mpoNetwork->Receive(&(maDataBuff[sizeof(int) * 2]), nReadSize, false, nTimeout); if (nRecved <= 0) { if (nRecved == -2) { sprintf_s(maErrorStr, sizeof(maErrorStr), "Disconnected from server."); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Socket Error."); } fclose(mpFileBuffer); mpFileBuffer = NULL; return -1; } if (fwrite(maDataBuff + sizeof(int) * 2, 1, nRecved, mpFileBuffer) != (size_t)nRecved) { sprintf_s (maErrorStr, sizeof(maErrorStr), "Failed to write file to disk."); fclose(mpFileBuffer); mpFileBuffer = NULL; return -1; } nRecvedTotal += nRecved; } } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Receive file buffer not opened."); if (mpFileBuffer) { fclose(mpFileBuffer); } mpFileBuffer = NULL; return -1; } } else { if (nFrameSize > mDataBuffSize) { char* buf = new char[nFrameSize]; memcpy(buf, maDataBuff, mDataBuffSize); delete maDataBuff; maDataBuff = buf; mDataBuffSize = nFrameSize; } // Receive more data until we have read the whole packet while (nRecvedTotal < nFrameSize) { // As long as we haven't received enough data, wait for more nRecved = mpoNetwork->Receive(&(maDataBuff[nRecvedTotal]), nFrameSize - nRecvedTotal, false, nTimeout); if (nRecved <= 0) { if (nRecved == -2) { sprintf_s(maErrorStr, sizeof(maErrorStr), "Disconnected from server."); } else { sprintf_s (maErrorStr, sizeof(maErrorStr), "Socket Error."); } return -1; } nRecvedTotal += nRecved; } } mpoRTPacket->SetData(maDataBuff); if (mpoRTPacket->GetEvent(meLastEvent)) // Update last event if there is an event { if (meLastEvent != CRTPacket::EventCameraSettingsChanged) { meState = meLastEvent; } } } while (bSkipEvents && eType == CRTPacket::PacketEvent); if (nRecvedTotal == nFrameSize) { return nRecvedTotal; } sprintf_s(maErrorStr, sizeof(maErrorStr), "Packet truncated."); return -1; } // ReceiveRTPacket CRTPacket* CRTProtocol::GetRTPacket() { return mpoRTPacket; }; bool CRTProtocol::ReadXmlBool(CMarkup& xml, const std::string& element, bool& value) const { if (!xml.FindChildElem(element.c_str())) { return false; } auto str = xml.GetChildData(); RemoveInvalidChars(str); ToLower(str); if (str == "true") { value = true; } else if (str == "false") { value = false; } else { // Don't change value, just report error. return false; } return true; } bool CRTProtocol::ReadCameraSystemSettings() { CRTPacket::EPacketType eType; CMarkup oXML; std::string tStr; msGeneralSettings.vsCameras.clear(); if (!SendCommand("GetParameters General")) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters General failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters General returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); // ==================== General ==================== if (!oXML.FindChildElem("General")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Frequency")) { return false; } msGeneralSettings.nCaptureFrequency = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Capture_Time")) { return false; } msGeneralSettings.fCaptureTime = (float)atof(oXML.GetChildData().c_str()); // Refactored variant of all this copy/paste code. TODO: Refactor everything else. if (!ReadXmlBool(oXML, "Start_On_External_Trigger", msGeneralSettings.bStartOnExternalTrigger)) { return false; } if (mnMajorVersion > 1 || mnMinorVersion > 14) { if (!ReadXmlBool(oXML, "Start_On_Trigger_NO", msGeneralSettings.bStartOnTrigNO)) { return false; } if (!ReadXmlBool(oXML, "Start_On_Trigger_NC", msGeneralSettings.bStartOnTrigNC)) { return false; } if (!ReadXmlBool(oXML, "Start_On_Trigger_Software", msGeneralSettings.bStartOnTrigSoftware)) { return false; } } // ==================== External time base ==================== if (!oXML.FindChildElem("External_Time_Base")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Enabled")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); msGeneralSettings.sExternalTimebase.bEnabled = (tStr == "true"); if (!oXML.FindChildElem("Signal_Source")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "control port") { msGeneralSettings.sExternalTimebase.eSignalSource = SourceControlPort; } else if (tStr == "ir receiver") { msGeneralSettings.sExternalTimebase.eSignalSource = SourceIRReceiver; } else if (tStr == "smpte") { msGeneralSettings.sExternalTimebase.eSignalSource = SourceSMPTE; } else if (tStr == "irig") { msGeneralSettings.sExternalTimebase.eSignalSource = SourceIRIG; } else if (tStr == "video sync") { msGeneralSettings.sExternalTimebase.eSignalSource = SourceVideoSync; } else { return false; } if (!oXML.FindChildElem("Signal_Mode")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "periodic") { msGeneralSettings.sExternalTimebase.bSignalModePeriodic = true; } else if (tStr == "non-periodic") { msGeneralSettings.sExternalTimebase.bSignalModePeriodic = false; } else { return false; } if (!oXML.FindChildElem("Frequency_Multiplier")) { return false; } unsigned int nMultiplier; tStr = oXML.GetChildData(); if (sscanf_s(tStr.c_str(), "%d", &nMultiplier) == 1) { msGeneralSettings.sExternalTimebase.nFreqMultiplier = nMultiplier; } else { return false; } if (!oXML.FindChildElem("Frequency_Divisor")) { return false; } unsigned int nDivisor; tStr = oXML.GetChildData(); if (sscanf_s(tStr.c_str(), "%d", &nDivisor) == 1) { msGeneralSettings.sExternalTimebase.nFreqDivisor = nDivisor; } else { return false; } if (!oXML.FindChildElem("Frequency_Tolerance")) { return false; } unsigned int nTolerance; tStr = oXML.GetChildData(); if (sscanf_s(tStr.c_str(), "%d", &nTolerance) == 1) { msGeneralSettings.sExternalTimebase.nFreqTolerance = nTolerance; } else { return false; } if (!oXML.FindChildElem("Nominal_Frequency")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "none") { msGeneralSettings.sExternalTimebase.fNominalFrequency = -1; // -1 = disabled } else { float fFrequency; if (sscanf_s(tStr.c_str(), "%f", &fFrequency) == 1) { msGeneralSettings.sExternalTimebase.fNominalFrequency = fFrequency; } else { return false; } } if (!oXML.FindChildElem("Signal_Edge")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "negative") { msGeneralSettings.sExternalTimebase.bNegativeEdge = true; } else if (tStr == "positive") { msGeneralSettings.sExternalTimebase.bNegativeEdge = false; } else { return false; } if (!oXML.FindChildElem("Signal_Shutter_Delay")) { return false; } unsigned int nDelay; tStr = oXML.GetChildData(); if (sscanf_s(tStr.c_str(), "%d", &nDelay) == 1) { msGeneralSettings.sExternalTimebase.nSignalShutterDelay = nDelay; } else { return false; } if (!oXML.FindChildElem("Non_Periodic_Timeout")) { return false; } float fTimeout; tStr = oXML.GetChildData(); if (sscanf_s(tStr.c_str(), "%f", &fTimeout) == 1) { msGeneralSettings.sExternalTimebase.fNonPeriodicTimeout = fTimeout; } else { return false; } oXML.OutOfElem(); // External_Time_Base _TCHAR* processings[3] = { "Processing_Actions", "RealTime_Processing_Actions", "Reprocessing_Actions" }; EProcessingActions* processingActions[3] = { &msGeneralSettings.eProcessingActions, &msGeneralSettings.eRtProcessingActions, &msGeneralSettings.eReprocessingActions }; auto actionsCount = (mnMajorVersion > 1 || mnMinorVersion > 13) ? 3 : 1; for (auto i = 0; i < actionsCount; i++) { // ==================== Processing actions ==================== if (!oXML.FindChildElem(processings[i])) { return false; } oXML.IntoElem(); *processingActions[i] = ProcessingNone; if (mnMajorVersion > 1 || mnMinorVersion > 13) { if (!oXML.FindChildElem("PreProcessing2D")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingPreProcess2D); } } if (!oXML.FindChildElem("Tracking")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "3d") { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingTracking3D); } else if (tStr == "2d" && i != 1) // i != 1 => Not RtProcessingSettings { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingTracking2D); } if (i != 1) //Not RtProcessingSettings { if (!oXML.FindChildElem("TwinSystemMerge")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingTwinSystemMerge); } if (!oXML.FindChildElem("SplineFill")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingSplineFill); } } if (!oXML.FindChildElem("AIM")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingAIM); } if (!oXML.FindChildElem("Track6DOF")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + Processing6DOFTracking); } if (!oXML.FindChildElem("ForceData")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingForceData); } if (mnMajorVersion > 1 || mnMinorVersion > 11) { if (!oXML.FindChildElem("GazeVector")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingGazeVector); } } if (i != 1) //Not RtProcessingSettings { if (!oXML.FindChildElem("ExportTSV")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingExportTSV); } if (!oXML.FindChildElem("ExportC3D")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingExportC3D); } if (!oXML.FindChildElem("ExportMatlabFile")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingExportMatlabFile); } if (mnMajorVersion > 1 || mnMinorVersion > 11) { if (!oXML.FindChildElem("ExportAviFile")) { return false; } if (CompareNoCase(oXML.GetChildData(), "true")) { *processingActions[i] = (EProcessingActions)(*processingActions[i] + ProcessingExportAviFile); } } } oXML.OutOfElem(); // Processing_Actions } // ==================== Camera ==================== msGeneralSettings.sCameraSystem.eType = ECameraSystemType::Unknown; if (oXML.FindChildElem("Camera_System") && oXML.IntoElem()) { if (oXML.FindChildElem("Type")) { tStr = oXML.GetChildData(); if (CompareNoCase(tStr, "oqus")) { msGeneralSettings.sCameraSystem.eType = ECameraSystemType::Oqus; } else if (CompareNoCase(tStr, "miqus")) { msGeneralSettings.sCameraSystem.eType = ECameraSystemType::Miqus; } } oXML.OutOfElem(); } SSettingsGeneralCamera sCameraSettings; while (oXML.FindChildElem("Camera")) { oXML.IntoElem(); if (!oXML.FindChildElem("ID")) { return false; } sCameraSettings.nID = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Model")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "macreflex") { sCameraSettings.eModel = ModelMacReflex; } else if (tStr == "proreflex 120") { sCameraSettings.eModel = ModelProReflex120; } else if (tStr == "proreflex 240") { sCameraSettings.eModel = ModelProReflex240; } else if (tStr == "proreflex 500") { sCameraSettings.eModel = ModelProReflex500; } else if (tStr == "proreflex 1000") { sCameraSettings.eModel = ModelProReflex1000; } else if (tStr == "oqus 100") { sCameraSettings.eModel = ModelOqus100; } else if (tStr == "oqus 200" || tStr == "oqus 200 c") { sCameraSettings.eModel = ModelOqus200C; } else if (tStr == "oqus 300") { sCameraSettings.eModel = ModelOqus300; } else if (tStr == "oqus 300 plus") { sCameraSettings.eModel = ModelOqus300Plus; } else if (tStr == "oqus 400") { sCameraSettings.eModel = ModelOqus400; } else if (tStr == "oqus 500") { sCameraSettings.eModel = ModelOqus500; } else if (tStr == "oqus 500 plus") { sCameraSettings.eModel = ModelOqus500Plus; } else if (tStr == "oqus 700") { sCameraSettings.eModel = ModelOqus700; } else if (tStr == "oqus 700 plus") { sCameraSettings.eModel = ModelOqus700Plus; } else if (tStr == "oqus 600 plus") { sCameraSettings.eModel = ModelOqus600Plus; } else if (tStr == "miqus m1") { sCameraSettings.eModel = ModelMiqusM1; } else if (tStr == "miqus m3") { sCameraSettings.eModel = ModelMiqusM3; } else if (tStr == "miqus m5") { sCameraSettings.eModel = ModelMiqusM5; } else if (tStr == "miqus sync unit") { sCameraSettings.eModel = ModelMiqusSyncUnit; } else if (tStr == "miqus video") { sCameraSettings.eModel = ModelMiqusVideo; } else if (tStr == "miqus video color") { sCameraSettings.eModel = ModelMiqusVideoColor; } else { return false; } // Only available from protocol version 1.10 and later. if (oXML.FindChildElem("Underwater")) { tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); sCameraSettings.bUnderwater = (tStr == "true"); } if (oXML.FindChildElem("Supports_HW_Sync")) { tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); sCameraSettings.bSupportsHwSync = (tStr == "true"); } if (!oXML.FindChildElem("Serial")) { return false; } sCameraSettings.nSerial = atoi(oXML.GetChildData().c_str()); // ==================== Camera Mode ==================== if (!oXML.FindChildElem("Mode")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "marker") { sCameraSettings.eMode = ModeMarker; } else if (tStr == "marker intensity") { sCameraSettings.eMode = ModeMarkerIntensity; } else if (tStr == "video") { sCameraSettings.eMode = ModeVideo; } else { return false; } if (mnMajorVersion > 1 || mnMinorVersion > 11) { // ==================== Video frequency ==================== if (!oXML.FindChildElem("Video_Frequency")) { return false; } sCameraSettings.nVideoFrequency = atoi(oXML.GetChildData().c_str()); } // ==================== Video Resolution ==================== if (oXML.FindChildElem("Video_Resolution")) { tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "1080p") { sCameraSettings.eVideoResolution = VideoResolution1080p; } else if (tStr == "720p") { sCameraSettings.eVideoResolution = VideoResolution720p; } else if (tStr == "540p") { sCameraSettings.eVideoResolution = VideoResolution540p; } else if (tStr == "480p") { sCameraSettings.eVideoResolution = VideoResolution480p; } } else { sCameraSettings.eVideoResolution = VideoResolutionNone; } // ==================== Video AspectRatio ==================== if (oXML.FindChildElem("Video_Aspect_Ratio")) { tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "16x9") { sCameraSettings.eVideoAspectRatio = VideoAspectRatio16x9; } else if (tStr == "4x3") { sCameraSettings.eVideoAspectRatio = VideoAspectRatio4x3; } else if (tStr == "1x1") { sCameraSettings.eVideoAspectRatio = VideoAspectRatio1x1; } } else { sCameraSettings.eVideoAspectRatio = VideoAspectRatioNone; } // ==================== Video exposure ==================== if (!oXML.FindChildElem("Video_Exposure")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Current")) { return false; } sCameraSettings.nVideoExposure = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Min")) { return false; } sCameraSettings.nVideoExposureMin = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Max")) { return false; } sCameraSettings.nVideoExposureMax = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Video_Exposure // ==================== Video flash time ==================== if (!oXML.FindChildElem("Video_Flash_Time")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Current")) { return false; } sCameraSettings.nVideoFlashTime = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Min")) { return false; } sCameraSettings.nVideoFlashTimeMin = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Max")) { return false; } sCameraSettings.nVideoFlashTimeMax = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Video_Flash_Time // ==================== Marker exposure ==================== if (!oXML.FindChildElem("Marker_Exposure")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Current")) { return false; } sCameraSettings.nMarkerExposure = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Min")) { return false; } sCameraSettings.nMarkerExposureMin = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Max")) { return false; } sCameraSettings.nMarkerExposureMax = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Marker_Exposure // ==================== Marker threshold ==================== if (!oXML.FindChildElem("Marker_Threshold")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Current")) { return false; } sCameraSettings.nMarkerThreshold = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Min")) { return false; } sCameraSettings.nMarkerThresholdMin = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Max")) { return false; } sCameraSettings.nMarkerThresholdMax = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Marker_Threshold // ==================== Position ==================== if (!oXML.FindChildElem("Position")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("X")) { return false; } sCameraSettings.fPositionX = (float)atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Y")) { return false; } sCameraSettings.fPositionY = (float)atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Z")) { return false; } sCameraSettings.fPositionZ = (float)atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_1_1")) { return false; } sCameraSettings.fPositionRotMatrix[0][0] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_2_1")) { return false; } sCameraSettings.fPositionRotMatrix[1][0] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_3_1")) { return false; } sCameraSettings.fPositionRotMatrix[2][0] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_1_2")) { return false; } sCameraSettings.fPositionRotMatrix[0][1] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_2_2")) { return false; } sCameraSettings.fPositionRotMatrix[1][1] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_3_2")) { return false; } sCameraSettings.fPositionRotMatrix[2][1] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_1_3")) { return false; } sCameraSettings.fPositionRotMatrix[0][2] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_2_3")) { return false; } sCameraSettings.fPositionRotMatrix[1][2] = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Rot_3_3")) { return false; } sCameraSettings.fPositionRotMatrix[2][2] = (float)atof(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Position if (!oXML.FindChildElem("Orientation")) { return false; } sCameraSettings.nOrientation = atoi(oXML.GetChildData().c_str()); // ==================== Marker exposure ==================== if (!oXML.FindChildElem("Marker_Res")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Width")) { return false; } sCameraSettings.nMarkerResolutionWidth = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Height")) { return false; } sCameraSettings.nMarkerResolutionHeight = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Marker_Res // ==================== Marker resolution ==================== if (!oXML.FindChildElem("Video_Res")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Width")) { return false; } sCameraSettings.nVideoResolutionWidth = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Height")) { return false; } sCameraSettings.nVideoResolutionHeight = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Video_Res // ==================== Marker FOV ==================== if (!oXML.FindChildElem("Marker_FOV")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Left")) { return false; } sCameraSettings.nMarkerFOVLeft = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Top")) { return false; } sCameraSettings.nMarkerFOVTop = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Right")) { return false; } sCameraSettings.nMarkerFOVRight = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Bottom")) { return false; } sCameraSettings.nMarkerFOVBottom = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Marker_FOV // ==================== Video FOV ==================== if (!oXML.FindChildElem("Video_FOV")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Left")) { return false; } sCameraSettings.nVideoFOVLeft = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Top")) { return false; } sCameraSettings.nVideoFOVTop = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Right")) { return false; } sCameraSettings.nVideoFOVRight = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Bottom")) { return false; } sCameraSettings.nVideoFOVBottom = atoi(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Video_FOV // ==================== Sync out ==================== // Only available from protocol version 1.10 and later. for (int port = 0; port < 3; port++) { char syncOutStr[16]; sprintf_s(syncOutStr, 16, "Sync_Out%s", port == 0 ? "" : (port == 1 ? "2" : "_MT")); if (oXML.FindChildElem(syncOutStr)) { oXML.IntoElem(); if (port < 2) { if (!oXML.FindChildElem("Mode")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "shutter out") { sCameraSettings.eSyncOutMode[port] = ModeShutterOut; } else if (tStr == "multiplier") { sCameraSettings.eSyncOutMode[port] = ModeMultiplier; } else if (tStr == "divisor") { sCameraSettings.eSyncOutMode[port] = ModeDivisor; } else if (tStr == "camera independent") { sCameraSettings.eSyncOutMode[port] = ModeActualFreq; } else if (tStr == "measurement time") { sCameraSettings.eSyncOutMode[port] = ModeMeasurementTime; } else if (tStr == "continuous 100hz") { sCameraSettings.eSyncOutMode[port] = ModeFixed100Hz; } else { return false; } if (sCameraSettings.eSyncOutMode[port] == ModeMultiplier || sCameraSettings.eSyncOutMode[port] == ModeDivisor || sCameraSettings.eSyncOutMode[port] == ModeActualFreq) { if (!oXML.FindChildElem("Value")) { return false; } sCameraSettings.nSyncOutValue[port] = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Duty_Cycle")) { return false; } sCameraSettings.fSyncOutDutyCycle[port] = (float)atof(oXML.GetChildData().c_str()); } } if (port == 2 || (sCameraSettings.eSyncOutMode[port] != ModeFixed100Hz)) { if (!oXML.FindChildElem("Signal_Polarity")) { return false; } if (CompareNoCase(oXML.GetChildData(), "negative")) { sCameraSettings.bSyncOutNegativePolarity[port] = true; } else { sCameraSettings.bSyncOutNegativePolarity[port] = false; } } oXML.OutOfElem(); // Sync_Out } else { sCameraSettings.eSyncOutMode[port] = ModeActualFreq; sCameraSettings.nSyncOutValue[port] = 0; sCameraSettings.fSyncOutDutyCycle[port] = 0; sCameraSettings.bSyncOutNegativePolarity[port] = false; } } if (oXML.FindChildElem("LensControl")) { oXML.IntoElem(); if (oXML.FindChildElem("Focus")) { oXML.IntoElem(); float focus; if (sscanf_s(oXML.GetAttrib("Value").c_str(), "%f", &focus) == 1) { sCameraSettings.fFocus = focus; } oXML.OutOfElem(); } if (oXML.FindChildElem("Aperture")) { oXML.IntoElem(); float aperture; if (sscanf_s(oXML.GetAttrib("Value").c_str(), "%f", &aperture) == 1) { sCameraSettings.fAperture = aperture; } oXML.OutOfElem(); } oXML.OutOfElem(); } else { sCameraSettings.fFocus = std::numeric_limits<float>::quiet_NaN(); sCameraSettings.fAperture = std::numeric_limits<float>::quiet_NaN(); } if (oXML.FindChildElem("AutoExposure")) { oXML.IntoElem(); if (CompareNoCase(oXML.GetAttrib("Enabled"), "true")) { sCameraSettings.autoExposureEnabled = true; } float autoExposureCompensation; if (sscanf_s(oXML.GetAttrib("Compensation").c_str(), "%f", &autoExposureCompensation) == 1) { sCameraSettings.autoExposureCompensation = autoExposureCompensation; } oXML.OutOfElem(); } else { sCameraSettings.autoExposureEnabled = false; sCameraSettings.autoExposureCompensation = std::numeric_limits<float>::quiet_NaN(); } if (oXML.FindChildElem("AutoWhiteBalance")) { sCameraSettings.autoWhiteBalance = CompareNoCase(oXML.GetChildData().c_str(), "true") ? 1 : 0; } else { sCameraSettings.autoWhiteBalance = -1; } oXML.OutOfElem(); // Camera msGeneralSettings.vsCameras.push_back(sCameraSettings); } return true; } // ReadGeneralSettings bool CRTProtocol::Read3DSettings(bool &bDataAvailable) { CRTPacket::EPacketType eType; CMarkup oXML; std::string tStr; bDataAvailable = false; ms3DSettings.s3DLabels.clear(); ms3DSettings.pCalibrationTime[0] = 0; if (!SendCommand("GetParameters 3D")) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters 3D failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters 3D returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); if (!oXML.FindChildElem("The_3D")) { // No 3D data available. return true; } oXML.IntoElem(); if (!oXML.FindChildElem("AxisUpwards")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "+x") { ms3DSettings.eAxisUpwards = XPos; } else if (tStr == "-x") { ms3DSettings.eAxisUpwards = XNeg; } else if (tStr == "+y") { ms3DSettings.eAxisUpwards = YPos; } else if (tStr == "-y") { ms3DSettings.eAxisUpwards = YNeg; } else if (tStr == "+z") { ms3DSettings.eAxisUpwards = ZPos; } else if (tStr == "-z") { ms3DSettings.eAxisUpwards = ZNeg; } else { return false; } if (!oXML.FindChildElem("CalibrationTime")) { return false; } tStr = oXML.GetChildData(); strcpy_s(ms3DSettings.pCalibrationTime, sizeof(ms3DSettings.pCalibrationTime), tStr.c_str()); if (!oXML.FindChildElem("Labels")) { return false; } unsigned int nNumberOfLabels = atoi(oXML.GetChildData().c_str()); ms3DSettings.s3DLabels.resize(nNumberOfLabels); SSettings3DLabel sLabel; for (unsigned int iLabel = 0; iLabel < nNumberOfLabels; iLabel++) { if (oXML.FindChildElem("Label")) { oXML.IntoElem(); if (oXML.FindChildElem("Name")) { sLabel.oName = oXML.GetChildData(); if (oXML.FindChildElem("RGBColor")) { sLabel.nRGBColor = atoi(oXML.GetChildData().c_str()); } ms3DSettings.s3DLabels[iLabel] = sLabel; } oXML.OutOfElem(); } else { return false; } } ms3DSettings.sBones.clear(); if (oXML.FindChildElem("Bones")) { oXML.IntoElem(); while (oXML.FindChildElem("Bone")) { oXML.IntoElem(); SSettingsBone bone; bone.fromName = oXML.GetAttrib("From").c_str(); bone.toName = oXML.GetAttrib("To").c_str(); bone.color = RGB(246, 249, 124); auto colorString = oXML.GetAttrib("Color"); if (!colorString.empty()) { bone.color = atoi(colorString.c_str()); } ms3DSettings.sBones.push_back(bone); oXML.OutOfElem(); } oXML.OutOfElem(); } bDataAvailable = true; return true; } // Read3DSettings bool CRTProtocol::Read6DOFSettings(bool &bDataAvailable) { CRTPacket::EPacketType eType; CMarkup oXML; bDataAvailable = false; mvs6DOFSettings.bodySettings.clear(); if (!SendCommand("GetParameters 6D")) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters 6D failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters 6DOF returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); // // Read 6DOF bodies // if (!oXML.FindChildElem("The_6D")) { return true; // NO 6DOF data available. } oXML.IntoElem(); if (!oXML.FindChildElem("Bodies")) { return false; } int nBodies = atoi(oXML.GetChildData().c_str()); SSettings6DOFBody s6DOFBodySettings; SPoint sPoint; for (int iBody = 0; iBody < nBodies; iBody++) { if (!oXML.FindChildElem("Body")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Name")) { return false; } s6DOFBodySettings.oName = oXML.GetChildData(); if (!oXML.FindChildElem("RGBColor")) { return false; } s6DOFBodySettings.vsPoints.clear(); s6DOFBodySettings.nRGBColor = atoi(oXML.GetChildData().c_str()); while (oXML.FindChildElem("Point")) { oXML.IntoElem(); if (!oXML.FindChildElem("X")) { return false; } sPoint.fX = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Y")) { return false; } sPoint.fY = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Z")) { return false; } sPoint.fZ = (float)atof(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Point s6DOFBodySettings.vsPoints.push_back(sPoint); } mvs6DOFSettings.bodySettings.push_back(s6DOFBodySettings); oXML.OutOfElem(); // Body } if (mnMajorVersion > 1 || mnMinorVersion > 15) { if (oXML.FindChildElem("Euler")) { oXML.IntoElem(); if (!oXML.FindChildElem("First")) { return false; } mvs6DOFSettings.eulerFirst = oXML.GetChildData(); if (!oXML.FindChildElem("Second")) { return false; } mvs6DOFSettings.eulerSecond = oXML.GetChildData(); if (!oXML.FindChildElem("Third")) { return false; } mvs6DOFSettings.eulerThird = oXML.GetChildData(); oXML.OutOfElem(); // Euler } } bDataAvailable = true; return true; } // Read6DOFSettings bool CRTProtocol::ReadGazeVectorSettings(bool &bDataAvailable) { CRTPacket::EPacketType eType; CMarkup oXML; bDataAvailable = false; mvsGazeVectorSettings.clear(); if (!SendCommand("GetParameters GazeVector")) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters GazeVector failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters GazeVector returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); // // Read gaze vectors // if (!oXML.FindChildElem("Gaze_Vector")) { return true; // NO gaze vector data available. } oXML.IntoElem(); std::string tGazeVectorName; int nGazeVectorCount = 0; while (oXML.FindChildElem("Vector")) { oXML.IntoElem(); if (!oXML.FindChildElem("Name")) { return false; } tGazeVectorName = oXML.GetChildData(); float frequency = 0; if (oXML.FindChildElem("Frequency")) { frequency = (float)atof(oXML.GetChildData().c_str()); } mvsGazeVectorSettings.push_back({ tGazeVectorName, frequency }); nGazeVectorCount++; oXML.OutOfElem(); // Vector } bDataAvailable = true; return true; } // ReadGazeVectorSettings bool CRTProtocol::ReadAnalogSettings(bool &bDataAvailable) { CRTPacket::EPacketType eType; CMarkup oXML; bDataAvailable = false; mvsAnalogDeviceSettings.clear(); if (!SendCommand("GetParameters Analog")) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters Analog failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters Analog returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); if (!oXML.FindChildElem("Analog")) { // No analog data available. return true; } SAnalogDevice sAnalogDevice; oXML.IntoElem(); if (mnMajorVersion == 1 && mnMinorVersion == 0) { sAnalogDevice.nDeviceID = 1; // Always channel 1 sAnalogDevice.oName = "AnalogDevice"; if (!oXML.FindChildElem("Channels")) { return false; } sAnalogDevice.nChannels = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Frequency")) { return false; } sAnalogDevice.nFrequency = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Unit")) { return false; } sAnalogDevice.oUnit = oXML.GetChildData(); if (!oXML.FindChildElem("Range")) { return false; } oXML.IntoElem(); if (!oXML.FindChildElem("Min")) { return false; } sAnalogDevice.fMinRange = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Max")) { return false; } sAnalogDevice.fMaxRange = (float)atof(oXML.GetChildData().c_str()); mvsAnalogDeviceSettings.push_back(sAnalogDevice); bDataAvailable = true; return true; } else { while (oXML.FindChildElem("Device")) { sAnalogDevice.voLabels.clear(); sAnalogDevice.voUnits.clear(); oXML.IntoElem(); if (!oXML.FindChildElem("Device_ID")) { oXML.OutOfElem(); // Device continue; } sAnalogDevice.nDeviceID = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Device_Name")) { oXML.OutOfElem(); // Device continue; } sAnalogDevice.oName = oXML.GetChildData(); if (!oXML.FindChildElem("Channels")) { oXML.OutOfElem(); // Device continue; } sAnalogDevice.nChannels = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Frequency")) { oXML.OutOfElem(); // Device continue; } sAnalogDevice.nFrequency = atoi(oXML.GetChildData().c_str()); if (mnMajorVersion == 1 && mnMinorVersion < 11) { if (!oXML.FindChildElem("Unit")) { oXML.OutOfElem(); // Device continue; } sAnalogDevice.oUnit = oXML.GetChildData(); } if (!oXML.FindChildElem("Range")) { oXML.OutOfElem(); // Device continue; } oXML.IntoElem(); if (!oXML.FindChildElem("Min")) { oXML.OutOfElem(); // Device oXML.OutOfElem(); // Range continue; } sAnalogDevice.fMinRange = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Max")) { oXML.OutOfElem(); // Device oXML.OutOfElem(); // Range continue; } sAnalogDevice.fMaxRange = (float)atof(oXML.GetChildData().c_str()); oXML.OutOfElem(); // Range if (mnMajorVersion == 1 && mnMinorVersion < 11) { for (unsigned int i = 0; i < sAnalogDevice.nChannels; i++) { if (oXML.FindChildElem("Label")) { sAnalogDevice.voLabels.push_back(oXML.GetChildData()); } } if (sAnalogDevice.voLabels.size() != sAnalogDevice.nChannels) { oXML.OutOfElem(); // Device continue; } } else { while (oXML.FindChildElem("Channel")) { oXML.IntoElem(); if (oXML.FindChildElem("Label")) { sAnalogDevice.voLabels.push_back(oXML.GetChildData()); } if (oXML.FindChildElem("Unit")) { sAnalogDevice.voUnits.push_back(oXML.GetChildData()); } oXML.OutOfElem(); // Channel } if (sAnalogDevice.voLabels.size() != sAnalogDevice.nChannels || sAnalogDevice.voUnits.size() != sAnalogDevice.nChannels) { oXML.OutOfElem(); // Device continue; } } oXML.OutOfElem(); // Device mvsAnalogDeviceSettings.push_back(sAnalogDevice); bDataAvailable = true; } } return true; } // ReadAnalogSettings bool CRTProtocol::ReadForceSettings(bool &bDataAvailable) { CRTPacket::EPacketType eType; CMarkup oXML; bDataAvailable = false; msForceSettings.vsForcePlates.clear(); if (!SendCommand("GetParameters Force")) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters Force failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters Force returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); // // Read some force plate parameters // if (!oXML.FindChildElem("Force")) { return true; } oXML.IntoElem(); SForcePlate sForcePlate; sForcePlate.bValidCalibrationMatrix = false; sForcePlate.nCalibrationMatrixRows = 6; sForcePlate.nCalibrationMatrixColumns = 6; if (!oXML.FindChildElem("Unit_Length")) { return false; } msForceSettings.oUnitLength = oXML.GetChildData(); if (!oXML.FindChildElem("Unit_Force")) { return false; } msForceSettings.oUnitForce = oXML.GetChildData(); int iPlate = 1; while (oXML.FindChildElem("Plate")) { // // Get name and type of the plates // oXML.IntoElem(); // "Plate" if (oXML.FindChildElem("Force_Plate_Index")) // Version 1.7 and earlier. { sForcePlate.nID = atoi(oXML.GetChildData().c_str()); } else if (oXML.FindChildElem("Plate_ID")) // Version 1.8 and later. { sForcePlate.nID = atoi(oXML.GetChildData().c_str()); } else { return false; } if (oXML.FindChildElem("Analog_Device_ID")) { sForcePlate.nAnalogDeviceID = atoi(oXML.GetChildData().c_str()); } else { sForcePlate.nAnalogDeviceID = 0; } if (!oXML.FindChildElem("Frequency")) { return false; } sForcePlate.nFrequency = atoi(oXML.GetChildData().c_str()); if (oXML.FindChildElem("Type")) { sForcePlate.oType = oXML.GetChildData(); } else { sForcePlate.oType = "unknown"; } if (oXML.FindChildElem("Name")) { sForcePlate.oName = oXML.GetChildData(); } else { sForcePlate.oName = Format("#%d", iPlate); } if (oXML.FindChildElem("Length")) { sForcePlate.fLength = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Width")) { sForcePlate.fWidth = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Location")) { oXML.IntoElem(); if (oXML.FindChildElem("Corner1")) { oXML.IntoElem(); if (oXML.FindChildElem("X")) { sForcePlate.asCorner[0].fX = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Y")) { sForcePlate.asCorner[0].fY = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Z")) { sForcePlate.asCorner[0].fZ = (float)atof(oXML.GetChildData().c_str()); } oXML.OutOfElem(); } if (oXML.FindChildElem("Corner2")) { oXML.IntoElem(); if (oXML.FindChildElem("X")) { sForcePlate.asCorner[1].fX = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Y")) { sForcePlate.asCorner[1].fY = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Z")) { sForcePlate.asCorner[1].fZ = (float)atof(oXML.GetChildData().c_str()); } oXML.OutOfElem(); } if (oXML.FindChildElem("Corner3")) { oXML.IntoElem(); if (oXML.FindChildElem("X")) { sForcePlate.asCorner[2].fX = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Y")) { sForcePlate.asCorner[2].fY = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Z")) { sForcePlate.asCorner[2].fZ = (float)atof(oXML.GetChildData().c_str()); } oXML.OutOfElem(); } if (oXML.FindChildElem("Corner4")) { oXML.IntoElem(); if (oXML.FindChildElem("X")) { sForcePlate.asCorner[3].fX = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Y")) { sForcePlate.asCorner[3].fY = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Z")) { sForcePlate.asCorner[3].fZ = (float)atof(oXML.GetChildData().c_str()); } oXML.OutOfElem(); } oXML.OutOfElem(); } if (oXML.FindChildElem("Origin")) { oXML.IntoElem(); if (oXML.FindChildElem("X")) { sForcePlate.sOrigin.fX = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Y")) { sForcePlate.sOrigin.fY = (float)atof(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("Z")) { sForcePlate.sOrigin.fZ = (float)atof(oXML.GetChildData().c_str()); } oXML.OutOfElem(); } sForcePlate.vChannels.clear(); if (oXML.FindChildElem("Channels")) { oXML.IntoElem(); SForceChannel sForceChannel; while (oXML.FindChildElem("Channel")) { oXML.IntoElem(); if (oXML.FindChildElem("Channel_No")) { sForceChannel.nChannelNumber = atoi(oXML.GetChildData().c_str()); } if (oXML.FindChildElem("ConversionFactor")) { sForceChannel.fConversionFactor = (float)atof(oXML.GetChildData().c_str()); } sForcePlate.vChannels.push_back(sForceChannel); oXML.OutOfElem(); } oXML.OutOfElem(); } if (oXML.FindChildElem("Calibration_Matrix")) { oXML.IntoElem(); int nRow = 0; if (mnMajorVersion == 1 && mnMinorVersion < 12) { char strRow[16]; char strCol[16]; sprintf_s(strRow, sizeof(strRow), "Row%d", nRow + 1); while (oXML.FindChildElem(strRow)) { oXML.IntoElem(); int nCol = 0; sprintf_s(strCol, sizeof(strCol), "Col%d", nCol + 1); while (oXML.FindChildElem(strCol)) { sForcePlate.afCalibrationMatrix[nRow][nCol] = (float)atof(oXML.GetChildData().c_str()); nCol++; sprintf_s(strCol, sizeof(strCol), "Col%d", nCol + 1); } sForcePlate.nCalibrationMatrixColumns = nCol; nRow++; sprintf_s(strRow, sizeof(strRow), "Row%d", nRow + 1); oXML.OutOfElem(); // RowX } } else { //<Rows> if (oXML.FindChildElem(_T("Rows"))) { oXML.IntoElem(); while (oXML.FindChildElem(_T("Row"))) { oXML.IntoElem(); //<Columns> if (oXML.FindChildElem(_T("Columns"))) { oXML.IntoElem(); int nCol = 0; while (oXML.FindChildElem(_T("Column"))) { sForcePlate.afCalibrationMatrix[nRow][nCol] = (float)atof(oXML.GetChildData().c_str()); nCol++; } sForcePlate.nCalibrationMatrixColumns = nCol; nRow++; oXML.OutOfElem(); // Columns } oXML.OutOfElem(); // Row } oXML.OutOfElem(); // Rows } } sForcePlate.nCalibrationMatrixRows = nRow; sForcePlate.bValidCalibrationMatrix = true; oXML.OutOfElem(); // "Calibration_Matrix" } oXML.OutOfElem(); // "Plate" bDataAvailable = true; msForceSettings.vsForcePlates.push_back(sForcePlate); } return true; } // Read force settings bool CRTProtocol::ReadImageSettings(bool &bDataAvailable) { CRTPacket::EPacketType eType; CMarkup oXML; bDataAvailable = false; mvsImageSettings.clear(); if (!SendCommand("GetParameters Image")) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters 6D failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters Image returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); // // Read some Image parameters // if (!oXML.FindChildElem("Image")) { return true; } oXML.IntoElem(); while (oXML.FindChildElem("Camera")) { oXML.IntoElem(); SImageCamera sImageCamera; if (!oXML.FindChildElem("ID")) { return false; } sImageCamera.nID = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Enabled")) { return false; } std::string tStr; tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "true") { sImageCamera.bEnabled = true; } else { sImageCamera.bEnabled = false; } if (!oXML.FindChildElem("Format")) { return false; } tStr = oXML.GetChildData(); std::transform(tStr.begin(), tStr.end(), tStr.begin(), ::tolower); if (tStr == "rawgrayscale") { sImageCamera.eFormat = CRTPacket::FormatRawGrayscale; } else if (tStr == "rawbgr") { sImageCamera.eFormat = CRTPacket::FormatRawBGR; } else if (tStr == "jpg") { sImageCamera.eFormat = CRTPacket::FormatJPG; } else if (tStr == "png") { sImageCamera.eFormat = CRTPacket::FormatPNG; } else { return false; } if (!oXML.FindChildElem("Width")) { return false; } sImageCamera.nWidth = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Height")) { return false; } sImageCamera.nHeight = atoi(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Left_Crop")) { return false; } sImageCamera.fCropLeft = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Top_Crop")) { return false; } sImageCamera.fCropTop = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Right_Crop")) { return false; } sImageCamera.fCropRight = (float)atof(oXML.GetChildData().c_str()); if (!oXML.FindChildElem("Bottom_Crop")) { return false; } sImageCamera.fCropBottom = (float)atof(oXML.GetChildData().c_str()); oXML.OutOfElem(); // "Camera" mvsImageSettings.push_back(sImageCamera); bDataAvailable = true; } return true; } // ReadImageSettings bool CRTProtocol::ReadSkeletonSettings(bool &bDataAvailable, bool skeletonGlobalData) { CRTPacket::EPacketType eType; CMarkup oXML; bDataAvailable = false; mSkeletonSettings.clear(); std::string cmd("GetParameters Skeleton"); if (skeletonGlobalData) { cmd += ":global"; } if (!SendCommand(cmd.c_str())) { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters Skeleton failed"); return false; } auto received = ReceiveRTPacket(eType, true); if (received <= 0) { if (received == 0) { // Receive timeout. strcat_s(maErrorStr, sizeof(maErrorStr), " Expected XML packet."); } return false; } if (eType != CRTPacket::PacketXML) { if (eType == CRTPacket::PacketError) { sprintf_s(maErrorStr, sizeof(maErrorStr), "%s.", mpoRTPacket->GetErrorString()); } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "GetParameters Skeleton returned wrong packet type. Got type %d expected type 2.", eType); } return false; } oXML.SetDoc(mpoRTPacket->GetXMLString()); if (!oXML.FindChildElem("Skeletons")) { return true; } oXML.IntoElem(); std::string skeletonName; int segmentIndex; std::map<int, int> segmentIdIndexMap; while (oXML.FindChildElem("Skeleton")) { SSettingsSkeleton skeleton; segmentIndex = 0; oXML.IntoElem(); skeleton.name = oXML.GetAttrib("Name"); while (oXML.FindChildElem("Segment")) { oXML.IntoElem(); SSettingsSkeletonSegment segment; segment.name = oXML.GetAttrib("Name"); if (segment.name.size() == 0 || sscanf_s(oXML.GetAttrib("ID").c_str(), "%d", &segment.id) != 1) { return false; } segmentIdIndexMap[segment.id] = segmentIndex++; int parentId; if (sscanf_s(oXML.GetAttrib("Parent_ID").c_str(), "%d", &parentId) != 1) { segment.parentId = -1; segment.parentIndex = -1; } else if (segmentIdIndexMap.count(parentId) > 0) { segment.parentId = parentId; segment.parentIndex = segmentIdIndexMap[parentId]; } if (oXML.FindChildElem("Position")) { oXML.IntoElem(); float x, y, z; if (sscanf_s(oXML.GetAttrib("X").c_str(), "%f", &x) == 1) { segment.positionX = x; } if (sscanf_s(oXML.GetAttrib("Y").c_str(), "%f", &y) == 1) { segment.positionY = y; } if (sscanf_s(oXML.GetAttrib("Z").c_str(), "%f", &z) == 1) { segment.positionZ = z; } oXML.OutOfElem(); } if (oXML.FindChildElem("Rotation")) { oXML.IntoElem(); float x, y, z, w; if (sscanf_s(oXML.GetAttrib("X").c_str(), "%f", &x) == 1) { segment.rotationX = x; } if (sscanf_s(oXML.GetAttrib("Y").c_str(), "%f", &y) == 1) { segment.rotationY = y; } if (sscanf_s(oXML.GetAttrib("Z").c_str(), "%f", &z) == 1) { segment.rotationZ = z; } if (sscanf_s(oXML.GetAttrib("W").c_str(), "%f", &w) == 1) { segment.rotationW = w; } oXML.OutOfElem(); } skeleton.segments.push_back(segment); oXML.OutOfElem(); // Segment } mSkeletonSettings.push_back(skeleton); oXML.OutOfElem(); // Skeleton } oXML.OutOfElem(); // Skeletons bDataAvailable = true; return true; } // ReadSkeletonSettings void CRTProtocol::GetSystemSettings( unsigned int &nCaptureFrequency, float &fCaptureTime, bool& bStartOnExtTrig, bool& startOnTrigNO, bool& startOnTrigNC, bool& startOnTrigSoftware, EProcessingActions &eProcessingActions, EProcessingActions &eRtProcessingActions, EProcessingActions &eReprocessingActions) const { nCaptureFrequency = msGeneralSettings.nCaptureFrequency; fCaptureTime = msGeneralSettings.fCaptureTime; bStartOnExtTrig = msGeneralSettings.bStartOnExternalTrigger; startOnTrigNO = msGeneralSettings.bStartOnTrigNO; startOnTrigNC = msGeneralSettings.bStartOnTrigNC; startOnTrigSoftware = msGeneralSettings.bStartOnTrigSoftware; eProcessingActions = msGeneralSettings.eProcessingActions; eRtProcessingActions = msGeneralSettings.eRtProcessingActions; eReprocessingActions = msGeneralSettings.eReprocessingActions; } // External time base settings only available in version 1.10 of the rt protocol and later void CRTProtocol::GetExtTimeBaseSettings( bool &bEnabled, ESignalSource &eSignalSource, bool &bSignalModePeriodic, unsigned int &nFreqMultiplier, unsigned int &nFreqDivisor, unsigned int &nFreqTolerance, float &fNominalFrequency, bool &bNegativeEdge, unsigned int &nSignalShutterDelay, float &fNonPeriodicTimeout) const { bEnabled = msGeneralSettings.sExternalTimebase.bEnabled; eSignalSource = msGeneralSettings.sExternalTimebase.eSignalSource; bSignalModePeriodic = msGeneralSettings.sExternalTimebase.bSignalModePeriodic; nFreqMultiplier = msGeneralSettings.sExternalTimebase.nFreqMultiplier; nFreqDivisor = msGeneralSettings.sExternalTimebase.nFreqDivisor; nFreqTolerance = msGeneralSettings.sExternalTimebase.nFreqTolerance; fNominalFrequency = msGeneralSettings.sExternalTimebase.fNominalFrequency; bNegativeEdge = msGeneralSettings.sExternalTimebase.bNegativeEdge; nSignalShutterDelay = msGeneralSettings.sExternalTimebase.nSignalShutterDelay; fNonPeriodicTimeout = msGeneralSettings.sExternalTimebase.fNonPeriodicTimeout; } unsigned int CRTProtocol::GetCameraCount() const { return (unsigned int)msGeneralSettings.vsCameras.size(); } bool CRTProtocol::GetCameraSettings( unsigned int nCameraIndex, unsigned int &nID, ECameraModel &eModel, bool &bUnderwater, bool &bSupportsHwSync, unsigned int &nSerial, ECameraMode &eMode) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { nID = msGeneralSettings.vsCameras[nCameraIndex].nID; eModel = msGeneralSettings.vsCameras[nCameraIndex].eModel; bUnderwater = msGeneralSettings.vsCameras[nCameraIndex].bUnderwater; bSupportsHwSync = msGeneralSettings.vsCameras[nCameraIndex].bSupportsHwSync; nSerial = msGeneralSettings.vsCameras[nCameraIndex].nSerial; eMode = msGeneralSettings.vsCameras[nCameraIndex].eMode; return true; } return false; } bool CRTProtocol::GetCameraMarkerSettings( unsigned int nCameraIndex, unsigned int &nCurrentExposure, unsigned int &nMinExposure, unsigned int &nMaxExposure, unsigned int &nCurrentThreshold, unsigned int &nMinThreshold, unsigned int &nMaxThreshold) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { nCurrentExposure = msGeneralSettings.vsCameras[nCameraIndex].nMarkerExposure; nMinExposure = msGeneralSettings.vsCameras[nCameraIndex].nMarkerExposureMin; nMaxExposure = msGeneralSettings.vsCameras[nCameraIndex].nMarkerExposureMax; nCurrentThreshold = msGeneralSettings.vsCameras[nCameraIndex].nMarkerThreshold; nMinThreshold = msGeneralSettings.vsCameras[nCameraIndex].nMarkerThresholdMin; nMaxThreshold = msGeneralSettings.vsCameras[nCameraIndex].nMarkerThresholdMax; return true; } return false; } bool CRTProtocol::GetCameraVideoSettings( unsigned int nCameraIndex, EVideoResolution &eVideoResolution, EVideoAspectRatio &eVideoAspectRatio, unsigned int &nVideoFrequency, unsigned int &nCurrentExposure, unsigned int &nMinExposure, unsigned int &nMaxExposure, unsigned int &nCurrentFlashTime, unsigned int &nMinFlashTime, unsigned int &nMaxFlashTime) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { eVideoResolution = msGeneralSettings.vsCameras[nCameraIndex].eVideoResolution; eVideoAspectRatio = msGeneralSettings.vsCameras[nCameraIndex].eVideoAspectRatio; nVideoFrequency = msGeneralSettings.vsCameras[nCameraIndex].nVideoFrequency; nCurrentExposure = msGeneralSettings.vsCameras[nCameraIndex].nVideoExposure; nMinExposure = msGeneralSettings.vsCameras[nCameraIndex].nVideoExposureMin; nMaxExposure = msGeneralSettings.vsCameras[nCameraIndex].nVideoExposureMax; nCurrentFlashTime = msGeneralSettings.vsCameras[nCameraIndex].nVideoFlashTime; nMinFlashTime = msGeneralSettings.vsCameras[nCameraIndex].nVideoFlashTimeMin; nMaxFlashTime = msGeneralSettings.vsCameras[nCameraIndex].nVideoFlashTimeMax; return true; } return false; } bool CRTProtocol::GetCameraSyncOutSettings( unsigned int nCameraIndex, unsigned int portNumber, ESyncOutFreqMode &eSyncOutMode, unsigned int &nSyncOutValue, float &fSyncOutDutyCycle, bool &bSyncOutNegativePolarity) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { if (portNumber == 1 || portNumber == 2) { eSyncOutMode = msGeneralSettings.vsCameras[nCameraIndex].eSyncOutMode[portNumber - 1]; nSyncOutValue = msGeneralSettings.vsCameras[nCameraIndex].nSyncOutValue[portNumber - 1]; fSyncOutDutyCycle = msGeneralSettings.vsCameras[nCameraIndex].fSyncOutDutyCycle[portNumber - 1]; } if (portNumber > 0 && portNumber < 4) { bSyncOutNegativePolarity = msGeneralSettings.vsCameras[nCameraIndex].bSyncOutNegativePolarity[portNumber - 1]; } else { return false; } return true; } return false; } bool CRTProtocol::GetCameraPosition( unsigned int nCameraIndex, SPoint &sPoint, float fvRotationMatrix[3][3]) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { sPoint.fX = msGeneralSettings.vsCameras[nCameraIndex].fPositionX; sPoint.fY = msGeneralSettings.vsCameras[nCameraIndex].fPositionY; sPoint.fZ = msGeneralSettings.vsCameras[nCameraIndex].fPositionZ; memcpy_s(fvRotationMatrix, 9 * sizeof(float), msGeneralSettings.vsCameras[nCameraIndex].fPositionRotMatrix, 9 * sizeof(float)); return true; } return false; } bool CRTProtocol::GetCameraOrientation( unsigned int nCameraIndex, int &nOrientation) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { nOrientation = msGeneralSettings.vsCameras[nCameraIndex].nOrientation; return true; } return false; } bool CRTProtocol::GetCameraResolution( unsigned int nCameraIndex, unsigned int &nMarkerWidth, unsigned int &nMarkerHeight, unsigned int &nVideoWidth, unsigned int &nVideoHeight) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { nMarkerWidth = msGeneralSettings.vsCameras[nCameraIndex].nMarkerResolutionWidth; nMarkerHeight = msGeneralSettings.vsCameras[nCameraIndex].nMarkerResolutionHeight; nVideoWidth = msGeneralSettings.vsCameras[nCameraIndex].nVideoResolutionWidth; nVideoHeight = msGeneralSettings.vsCameras[nCameraIndex].nVideoResolutionHeight; return true; } return false; } bool CRTProtocol::GetCameraFOV( unsigned int nCameraIndex, unsigned int &nMarkerLeft, unsigned int &nMarkerTop, unsigned int &nMarkerRight, unsigned int &nMarkerBottom, unsigned int &nVideoLeft, unsigned int &nVideoTop, unsigned int &nVideoRight, unsigned int &nVideoBottom) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { nMarkerLeft = msGeneralSettings.vsCameras[nCameraIndex].nMarkerFOVLeft; nMarkerTop = msGeneralSettings.vsCameras[nCameraIndex].nMarkerFOVTop; nMarkerRight = msGeneralSettings.vsCameras[nCameraIndex].nMarkerFOVRight; nMarkerBottom = msGeneralSettings.vsCameras[nCameraIndex].nMarkerFOVBottom; nVideoLeft = msGeneralSettings.vsCameras[nCameraIndex].nVideoFOVLeft; nVideoTop = msGeneralSettings.vsCameras[nCameraIndex].nVideoFOVTop; nVideoRight = msGeneralSettings.vsCameras[nCameraIndex].nVideoFOVRight; nVideoBottom = msGeneralSettings.vsCameras[nCameraIndex].nVideoFOVBottom; return true; } return false; } bool CRTProtocol::GetCameraLensControlSettings(const unsigned int nCameraIndex, float* focus, float* aperture) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { *focus = msGeneralSettings.vsCameras[nCameraIndex].fFocus; if (std::isnan(*focus)) return false; *aperture = msGeneralSettings.vsCameras[nCameraIndex].fAperture; return true; } return false; } bool CRTProtocol::GetCameraAutoExposureSettings(const unsigned int nCameraIndex, bool* autoExposureEnabled, float* autoExposureCompensation) const { if (nCameraIndex < msGeneralSettings.vsCameras.size()) { *autoExposureCompensation = msGeneralSettings.vsCameras[nCameraIndex].autoExposureCompensation; if (std::isnan(*autoExposureCompensation)) return false; *autoExposureEnabled = msGeneralSettings.vsCameras[nCameraIndex].autoExposureEnabled; return true; } return false; } bool CRTProtocol::GetCameraAutoWhiteBalance(const unsigned int nCameraIndex, bool* autoWhiteBalanceEnabled) const { if (nCameraIndex < msGeneralSettings.vsCameras.size() && msGeneralSettings.vsCameras[nCameraIndex].autoWhiteBalance >= 0) { *autoWhiteBalanceEnabled = msGeneralSettings.vsCameras[nCameraIndex].autoWhiteBalance == 1; return true; } return false; } CRTProtocol::EAxis CRTProtocol::Get3DUpwardAxis() const { return ms3DSettings.eAxisUpwards; } const char* CRTProtocol::Get3DCalibrated() const { return ms3DSettings.pCalibrationTime; } unsigned int CRTProtocol::Get3DLabeledMarkerCount() const { return (unsigned int)ms3DSettings.s3DLabels.size(); } const char* CRTProtocol::Get3DLabelName(unsigned int nMarkerIndex) const { if (nMarkerIndex < ms3DSettings.s3DLabels.size()) { return ms3DSettings.s3DLabels[nMarkerIndex].oName.c_str(); } return NULL; } unsigned int CRTProtocol::Get3DLabelColor(unsigned int nMarkerIndex) const { if (nMarkerIndex < ms3DSettings.s3DLabels.size()) { return ms3DSettings.s3DLabels[nMarkerIndex].nRGBColor; } return 0; } unsigned int CRTProtocol::Get3DBoneCount() const { return (unsigned int)ms3DSettings.sBones.size(); } const char* CRTProtocol::Get3DBoneFromName(unsigned int boneIndex) const { if (boneIndex < ms3DSettings.sBones.size()) { return ms3DSettings.sBones[boneIndex].fromName.c_str(); } return NULL; } const char* CRTProtocol::Get3DBoneToName(unsigned int boneIndex) const { if (boneIndex < ms3DSettings.sBones.size()) { return ms3DSettings.sBones[boneIndex].toName.c_str(); } return NULL; } void CRTProtocol::Get6DOFEulerNames(std::string &first, std::string &second, std::string &third) const { first = mvs6DOFSettings.eulerFirst; second = mvs6DOFSettings.eulerSecond; third = mvs6DOFSettings.eulerThird; } unsigned int CRTProtocol::Get6DOFBodyCount() const { return (unsigned int)mvs6DOFSettings.bodySettings.size(); } const char* CRTProtocol::Get6DOFBodyName(unsigned int nBodyIndex) const { if (nBodyIndex < mvs6DOFSettings.bodySettings.size()) { return mvs6DOFSettings.bodySettings[nBodyIndex].oName.c_str(); } return NULL; } unsigned int CRTProtocol::Get6DOFBodyColor(unsigned int nBodyIndex) const { if (nBodyIndex < mvs6DOFSettings.bodySettings.size()) { return mvs6DOFSettings.bodySettings[nBodyIndex].nRGBColor; } return 0; } unsigned int CRTProtocol::Get6DOFBodyPointCount(unsigned int nBodyIndex) const { if (nBodyIndex < mvs6DOFSettings.bodySettings.size()) { return (unsigned int)mvs6DOFSettings.bodySettings.at(nBodyIndex).vsPoints.size(); } return false; } bool CRTProtocol::Get6DOFBodyPoint(unsigned int nBodyIndex, unsigned int nMarkerIndex, SPoint &sPoint) const { if (nBodyIndex < mvs6DOFSettings.bodySettings.size()) { if (nMarkerIndex < mvs6DOFSettings.bodySettings.at(nBodyIndex).vsPoints.size()) { sPoint.fX = mvs6DOFSettings.bodySettings.at(nBodyIndex).vsPoints[nMarkerIndex].fX; sPoint.fY = mvs6DOFSettings.bodySettings.at(nBodyIndex).vsPoints[nMarkerIndex].fY; sPoint.fZ = mvs6DOFSettings.bodySettings.at(nBodyIndex).vsPoints[nMarkerIndex].fZ; return true; } } return false; } unsigned int CRTProtocol::GetGazeVectorCount() const { return (unsigned int)mvsGazeVectorSettings.size(); } const char* CRTProtocol::GetGazeVectorName(unsigned int nGazeVectorIndex) const { if (nGazeVectorIndex < mvsGazeVectorSettings.size()) { return mvsGazeVectorSettings[nGazeVectorIndex].name.c_str(); } return NULL; } float CRTProtocol::GetGazeVectorFrequency(unsigned int nGazeVectorIndex) const { if (nGazeVectorIndex < mvsGazeVectorSettings.size()) { return mvsGazeVectorSettings[nGazeVectorIndex].frequency; } return 0; } unsigned int CRTProtocol::GetAnalogDeviceCount() const { return (unsigned int)mvsAnalogDeviceSettings.size(); } bool CRTProtocol::GetAnalogDevice(unsigned int nDeviceIndex, unsigned int &nDeviceID, unsigned int &nChannels, char* &pName, unsigned int &nFrequency, char* &pUnit, float &fMinRange, float &fMaxRange) const { if (nDeviceIndex < mvsAnalogDeviceSettings.size()) { nDeviceID = mvsAnalogDeviceSettings.at(nDeviceIndex).nDeviceID; pName = (char*)mvsAnalogDeviceSettings.at(nDeviceIndex).oName.c_str(); nChannels = mvsAnalogDeviceSettings.at(nDeviceIndex).nChannels; nFrequency = mvsAnalogDeviceSettings.at(nDeviceIndex).nFrequency; pUnit = (char*)mvsAnalogDeviceSettings.at(nDeviceIndex).oUnit.c_str(); fMinRange = mvsAnalogDeviceSettings.at(nDeviceIndex).fMinRange; fMaxRange = mvsAnalogDeviceSettings.at(nDeviceIndex).fMaxRange; return true; } return false; } const char* CRTProtocol::GetAnalogLabel(unsigned int nDeviceIndex, unsigned int nChannelIndex) const { if (nDeviceIndex < mvsAnalogDeviceSettings.size()) { if (nChannelIndex < mvsAnalogDeviceSettings.at(nDeviceIndex).voLabels.size()) { return mvsAnalogDeviceSettings.at(nDeviceIndex).voLabels.at(nChannelIndex).c_str(); } } return NULL; } const char* CRTProtocol::GetAnalogUnit(unsigned int nDeviceIndex, unsigned int nChannelIndex) const { if (nDeviceIndex < mvsAnalogDeviceSettings.size()) { if (nChannelIndex < mvsAnalogDeviceSettings.at(nDeviceIndex).voUnits.size()) { return mvsAnalogDeviceSettings.at(nDeviceIndex).voUnits.at(nChannelIndex).c_str(); } } return NULL; } void CRTProtocol::GetForceUnits(char* &pLength, char* &pForce) const { pLength = (char*)msForceSettings.oUnitLength.c_str(); pForce = (char*)msForceSettings.oUnitForce.c_str(); } unsigned int CRTProtocol::GetForcePlateCount() const { return (unsigned int)msForceSettings.vsForcePlates.size(); } bool CRTProtocol::GetForcePlate(unsigned int nPlateIndex, unsigned int &nID, unsigned int &nAnalogDeviceID, unsigned int &nFrequency, char* &pType, char* &pName, float &fLength, float &fWidth) const { if (nPlateIndex < msForceSettings.vsForcePlates.size()) { nID = msForceSettings.vsForcePlates[nPlateIndex].nID; nAnalogDeviceID = msForceSettings.vsForcePlates[nPlateIndex].nAnalogDeviceID; nFrequency = msForceSettings.vsForcePlates[nPlateIndex].nFrequency; pType = (char*)msForceSettings.vsForcePlates[nPlateIndex].oType.c_str(); pName = (char*)msForceSettings.vsForcePlates[nPlateIndex].oName.c_str(); fLength = msForceSettings.vsForcePlates[nPlateIndex].fLength; fWidth = msForceSettings.vsForcePlates[nPlateIndex].fWidth; return true; } return false; } bool CRTProtocol::GetForcePlateLocation(unsigned int nPlateIndex, SPoint sCorner[4]) const { if (nPlateIndex < msForceSettings.vsForcePlates.size()) { memcpy_s(sCorner, 3 * 4 *sizeof(float), msForceSettings.vsForcePlates[nPlateIndex].asCorner, 3 * 4 * sizeof(float)); return true; } return false; } bool CRTProtocol::GetForcePlateOrigin(unsigned int nPlateIndex, SPoint &sOrigin) const { if (nPlateIndex < msForceSettings.vsForcePlates.size()) { sOrigin = msForceSettings.vsForcePlates[nPlateIndex].sOrigin; return true; } return false; } unsigned int CRTProtocol::GetForcePlateChannelCount(unsigned int nPlateIndex) const { if (nPlateIndex < msForceSettings.vsForcePlates.size()) { return (unsigned int)msForceSettings.vsForcePlates[nPlateIndex].vChannels.size(); } return 0; } bool CRTProtocol::GetForcePlateChannel(unsigned int nPlateIndex, unsigned int nChannelIndex, unsigned int &nChannelNumber, float &fConversionFactor) const { if (nPlateIndex < msForceSettings.vsForcePlates.size()) { if (nChannelIndex < msForceSettings.vsForcePlates[nPlateIndex].vChannels.size()) { nChannelNumber = msForceSettings.vsForcePlates[nPlateIndex].vChannels[nChannelIndex].nChannelNumber; fConversionFactor = msForceSettings.vsForcePlates[nPlateIndex].vChannels[nChannelIndex].fConversionFactor; return true; } } return false; } bool CRTProtocol::GetForcePlateCalibrationMatrix(unsigned int nPlateIndex, float fvCalMatrix[12][12], unsigned int* rows, unsigned int* columns) const { if (nPlateIndex < msForceSettings.vsForcePlates.size()) { if (msForceSettings.vsForcePlates[nPlateIndex].bValidCalibrationMatrix) { *rows = msForceSettings.vsForcePlates[nPlateIndex].nCalibrationMatrixRows; *columns = msForceSettings.vsForcePlates[nPlateIndex].nCalibrationMatrixColumns; memcpy_s( fvCalMatrix, msForceSettings.vsForcePlates[nPlateIndex].nCalibrationMatrixRows * msForceSettings.vsForcePlates[nPlateIndex].nCalibrationMatrixColumns * sizeof(float), msForceSettings.vsForcePlates[nPlateIndex].afCalibrationMatrix, msForceSettings.vsForcePlates[nPlateIndex].nCalibrationMatrixRows * msForceSettings.vsForcePlates[nPlateIndex].nCalibrationMatrixColumns * sizeof(float)); return true; } } return false; } unsigned int CRTProtocol::GetImageCameraCount() const { return (unsigned int)mvsImageSettings.size(); } bool CRTProtocol::GetImageCamera(unsigned int nCameraIndex, unsigned int &nCameraID, bool &bEnabled, CRTPacket::EImageFormat &eFormat, unsigned int &nWidth, unsigned int &nHeight, float &fCropLeft, float &fCropTop, float &fCropRight, float &fCropBottom) const { if (nCameraIndex < mvsImageSettings.size()) { nCameraID = mvsImageSettings[nCameraIndex].nID; bEnabled = mvsImageSettings[nCameraIndex].bEnabled; eFormat = mvsImageSettings[nCameraIndex].eFormat; nWidth = mvsImageSettings[nCameraIndex].nWidth; nHeight = mvsImageSettings[nCameraIndex].nHeight; fCropLeft = mvsImageSettings[nCameraIndex].fCropLeft; fCropTop = mvsImageSettings[nCameraIndex].fCropTop; fCropRight = mvsImageSettings[nCameraIndex].fCropRight; fCropBottom = mvsImageSettings[nCameraIndex].fCropBottom; return true; } return false; } unsigned int CRTProtocol::GetSkeletonCount() const { return (unsigned int)mSkeletonSettings.size(); } const char* CRTProtocol::GetSkeletonName(unsigned int skeletonIndex) { if (skeletonIndex < mSkeletonSettings.size()) { return (char*)mSkeletonSettings[skeletonIndex].name.c_str(); } return nullptr; } unsigned int CRTProtocol::GetSkeletonSegmentCount(unsigned int skeletonIndex) { if (skeletonIndex < mSkeletonSettings.size()) { return static_cast<long unsigned>(mSkeletonSettings[skeletonIndex].segments.size()); } return 0; } bool CRTProtocol::GetSkeleton(unsigned int skeletonIndex, SSettingsSkeleton* skeleton) { if (skeleton == nullptr) return false; if (skeletonIndex < mSkeletonSettings.size()) { *skeleton = mSkeletonSettings[skeletonIndex]; return true; } return false; } bool CRTProtocol::GetSkeletonSegment(unsigned int skeletonIndex, unsigned int segmentIndex, SSettingsSkeletonSegment* segment) { if (segment == nullptr) return false; if (skeletonIndex < mSkeletonSettings.size()) { if (segmentIndex < mSkeletonSettings[skeletonIndex].segments.size()) { *segment = mSkeletonSettings[skeletonIndex].segments[segmentIndex]; return true; } } return false; } CRTProtocol::ECameraSystemType CRTProtocol::GetCameraSystemType() const { return msGeneralSettings.sCameraSystem.eType; } bool CRTProtocol::SetSystemSettings( const unsigned int* pnCaptureFrequency, const float* pfCaptureTime, const bool* pbStartOnExtTrig, const bool* startOnTrigNO, const bool* startOnTrigNC, const bool* startOnTrigSoftware, const EProcessingActions* peProcessingActions, const EProcessingActions* peRtProcessingActions, const EProcessingActions* peReprocessingActions) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); if (pnCaptureFrequency) { AddXMLElementUnsignedInt(&oXML, "Frequency", pnCaptureFrequency); } if (pfCaptureTime) { AddXMLElementFloat(&oXML, "Capture_Time", pfCaptureTime, 3); } if (pbStartOnExtTrig) { AddXMLElementBool(&oXML, "Start_On_External_Trigger", pbStartOnExtTrig); if (mnMajorVersion > 1 || mnMinorVersion > 14) { AddXMLElementBool(&oXML, "Start_On_Trigger_NO", startOnTrigNO); AddXMLElementBool(&oXML, "Start_On_Trigger_NC", startOnTrigNC); AddXMLElementBool(&oXML, "Start_On_Trigger_Software", startOnTrigSoftware); } } _TCHAR* processings[3] = { "Processing_Actions", "RealTime_Processing_Actions", "Reprocessing_Actions" }; const EProcessingActions* processingActions[3] = { peProcessingActions, peRtProcessingActions, peReprocessingActions }; auto actionsCount = (mnMajorVersion > 1 || mnMinorVersion > 13) ? 3 : 1; for (auto i = 0; i < actionsCount; i++) { if (processingActions[i]) { oXML.AddElem(processings[i]); oXML.IntoElem(); if (mnMajorVersion > 1 || mnMinorVersion > 13) { AddXMLElementBool(&oXML, "PreProcessing2D", (*processingActions[i] & ProcessingPreProcess2D) != 0); } if (*processingActions[i] & ProcessingTracking2D && i != 1) // i != 1 => Not RtProcessingSettings { oXML.AddElem("Tracking", "2D"); } else if (*processingActions[i] & ProcessingTracking3D) { oXML.AddElem("Tracking", "3D"); } else { oXML.AddElem("Tracking", "False"); } if (i != 1) //Not RtProcessingSettings { AddXMLElementBool(&oXML, "TwinSystemMerge", (*processingActions[i] & ProcessingTwinSystemMerge) != 0); AddXMLElementBool(&oXML, "SplineFill", (*processingActions[i] & ProcessingSplineFill) != 0); } AddXMLElementBool(&oXML, "AIM", (*processingActions[i] & ProcessingAIM) != 0); AddXMLElementBool(&oXML, "Track6DOF", (*processingActions[i] & Processing6DOFTracking) != 0); AddXMLElementBool(&oXML, "ForceData", (*processingActions[i] & ProcessingForceData) != 0); AddXMLElementBool(&oXML, "GazeVector", (*processingActions[i] & ProcessingGazeVector) != 0); if (i != 1) //Not RtProcessingSettings { AddXMLElementBool(&oXML, "ExportTSV", (*processingActions[i] & ProcessingExportTSV) != 0); AddXMLElementBool(&oXML, "ExportC3D", (*processingActions[i] & ProcessingExportC3D) != 0); AddXMLElementBool(&oXML, "ExportMatlabFile", (*processingActions[i] & ProcessingExportMatlabFile) != 0); AddXMLElementBool(&oXML, "ExportAviFile", (*processingActions[i] & ProcessingExportAviFile) != 0); } oXML.OutOfElem(); // Processing_Actions } } oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // SetGeneral bool CRTProtocol::SetExtTimeBaseSettings( const bool* pbEnabled, const ESignalSource* peSignalSource, const bool* pbSignalModePeriodic, const unsigned int* pnFreqMultiplier, const unsigned int* pnFreqDivisor, const unsigned int* pnFreqTolerance, const float* pfNominalFrequency, const bool* pbNegativeEdge, const unsigned int* pnSignalShutterDelay, const float* pfNonPeriodicTimeout) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); oXML.AddElem("External_Time_Base"); oXML.IntoElem(); AddXMLElementBool(&oXML, "Enabled", pbEnabled); if (peSignalSource) { switch (*peSignalSource) { case SourceControlPort : oXML.AddElem("Signal_Source", "Control port"); break; case SourceIRReceiver : oXML.AddElem("Signal_Source", "IR receiver"); break; case SourceSMPTE : oXML.AddElem("Signal_Source", "SMPTE"); break; case SourceVideoSync : oXML.AddElem("Signal_Source", "Video sync"); break; case SourceIRIG: oXML.AddElem("Signal_Source", "IRIG"); break; } } AddXMLElementBool(&oXML, "Signal_Mode", pbSignalModePeriodic, "Periodic", "Non-periodic"); AddXMLElementUnsignedInt(&oXML, "Frequency_Multiplier", pnFreqMultiplier); AddXMLElementUnsignedInt(&oXML, "Frequency_Divisor", pnFreqDivisor); AddXMLElementUnsignedInt(&oXML, "Frequency_Tolerance", pnFreqTolerance); if (pfNominalFrequency) { if (*pfNominalFrequency < 0) { oXML.AddElem("Nominal_Frequency", "None"); } else { AddXMLElementFloat(&oXML, "Nominal_Frequency", pfNominalFrequency, 3); } } AddXMLElementBool(&oXML, "Signal_Edge", pbNegativeEdge, "Negative", "Positive"); AddXMLElementUnsignedInt(&oXML, "Signal_Shutter_Delay", pnSignalShutterDelay); AddXMLElementFloat(&oXML, "Non_Periodic_Timeout", pfNonPeriodicTimeout, 3); oXML.OutOfElem(); // External_Time_Base oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // SetGeneralExtTimeBase // nCameraID starts on 1. If nCameraID < 0 then settings are applied to all cameras. bool CRTProtocol::SetCameraSettings( const unsigned int nCameraID, const ECameraMode* peMode, const float* pfMarkerExposure, const float* pfMarkerThreshold, const int* pnOrientation) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); oXML.AddElem("Camera"); oXML.IntoElem(); AddXMLElementUnsignedInt(&oXML, "ID", &nCameraID); if (peMode) { switch (*peMode) { case ModeMarker : oXML.AddElem("Mode", "Marker"); break; case ModeMarkerIntensity : oXML.AddElem("Mode", "Marker Intensity"); break; case ModeVideo : oXML.AddElem("Mode", "Video"); break; } } AddXMLElementFloat(&oXML, "Marker_Exposure", pfMarkerExposure); AddXMLElementFloat(&oXML, "Marker_Threshold", pfMarkerThreshold); AddXMLElementInt(&oXML, "Orientation", pnOrientation); oXML.OutOfElem(); // Camera oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // SetGeneralCamera // nCameraID starts on 1. If nCameraID < 0 then settings are applied to all cameras. bool CRTProtocol::SetCameraVideoSettings( const unsigned int nCameraID, const EVideoResolution* eVideoResolution, const EVideoAspectRatio* eVideoAspectRatio, const unsigned int* pnVideoFrequency, const float* pfVideoExposure, const float* pfVideoFlashTime) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); oXML.AddElem("Camera"); oXML.IntoElem(); AddXMLElementUnsignedInt(&oXML, "ID", &nCameraID); if (eVideoResolution) { switch (*eVideoResolution) { case VideoResolution1080p: oXML.AddElem("Video_Resolution", "1080p"); break; case VideoResolution720p: oXML.AddElem("Video_Resolution", "720p"); break; case VideoResolution540p: oXML.AddElem("Video_Resolution", "540p"); break; case VideoResolution480p: oXML.AddElem("Video_Resolution", "480p"); break; } } if (eVideoAspectRatio) { switch (*eVideoAspectRatio) { case VideoAspectRatio16x9: oXML.AddElem("Video_Aspect_Ratio", "16x9"); break; case VideoAspectRatio4x3: oXML.AddElem("Video_Aspect_Ratio", "4x3"); break; case VideoAspectRatio1x1: oXML.AddElem("Video_Aspect_Ratio", "1x1"); break; } } AddXMLElementUnsignedInt(&oXML, "Video_Frequency", pnVideoFrequency); AddXMLElementFloat(&oXML, "Video_Exposure", pfVideoExposure); AddXMLElementFloat(&oXML, "Video_Flash_Time", pfVideoFlashTime); oXML.OutOfElem(); // Camera oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // SetGeneralCameraVideo // nCameraID starts on 1. If nCameraID < 0 then settings are applied to all cameras. bool CRTProtocol::SetCameraSyncOutSettings( const unsigned int nCameraID, const unsigned int portNumber, const ESyncOutFreqMode* peSyncOutMode, const unsigned int* pnSyncOutValue, const float* pfSyncOutDutyCycle, const bool* pbSyncOutNegativePolarity) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); oXML.AddElem("Camera"); oXML.IntoElem(); AddXMLElementUnsignedInt(&oXML, "ID", &nCameraID); int port = portNumber - 1; if (((port == 0 || port == 1) && peSyncOutMode) || (port == 2)) { oXML.AddElem(port == 0 ? "Sync_Out" : (port == 1 ? "Sync_Out2" : "Sync_Out_MT")); oXML.IntoElem(); if (port == 0 || port == 1) { switch (*peSyncOutMode) { case ModeShutterOut: oXML.AddElem("Mode", "Shutter out"); break; case ModeMultiplier: oXML.AddElem("Mode", "Multiplier"); break; case ModeDivisor: oXML.AddElem("Mode", "Divisor"); break; case ModeActualFreq: oXML.AddElem("Mode", "Camera independent"); break; case ModeMeasurementTime: oXML.AddElem("Mode", "Measurement time"); break; case ModeFixed100Hz: oXML.AddElem("Mode", "Continuous 100Hz"); break; default: return false; // Should never happen } if (*peSyncOutMode == ModeMultiplier || *peSyncOutMode == ModeDivisor || *peSyncOutMode == ModeActualFreq) { if (pnSyncOutValue) { AddXMLElementUnsignedInt(&oXML, "Value", pnSyncOutValue); } if (pfSyncOutDutyCycle) { AddXMLElementFloat(&oXML, "Duty_Cycle", pfSyncOutDutyCycle, 3); } } } if (pbSyncOutNegativePolarity && (port == 2 || (peSyncOutMode && *peSyncOutMode != ModeFixed100Hz))) { AddXMLElementBool(&oXML, "Signal_Polarity", pbSyncOutNegativePolarity, "Negative", "Positive"); } oXML.OutOfElem(); // Sync_Out } oXML.OutOfElem(); // Camera oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // SetGeneralCameraSyncOut // nCameraID starts on 1. If nCameraID < 0 then settings are applied to all cameras. bool CRTProtocol::SetCameraLensControlSettings(const unsigned int nCameraID, const float focus, const float aperture) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); oXML.AddElem("Camera"); oXML.IntoElem(); AddXMLElementUnsignedInt(&oXML, "ID", &nCameraID); oXML.AddElem("LensControl"); oXML.IntoElem(); oXML.AddElem("Focus"); oXML.AddAttrib("Value", Format("%f", focus).c_str()); oXML.AddElem("Aperture"); oXML.AddAttrib("Value", Format("%f", aperture).c_str()); oXML.OutOfElem(); // LensControl oXML.OutOfElem(); // Camera oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // nCameraID starts on 1. If nCameraID < 0 then settings are applied to all cameras. bool CRTProtocol::SetCameraAutoExposureSettings(const unsigned int nCameraID, const bool autoExposure, const float compensation) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); oXML.AddElem("Camera"); oXML.IntoElem(); AddXMLElementUnsignedInt(&oXML, "ID", &nCameraID); oXML.AddElem("LensControl"); oXML.IntoElem(); oXML.AddElem("AutoExposure"); oXML.AddAttrib("Enabled", autoExposure ? "true" : "false"); oXML.AddAttrib("Compensation", Format("%f", compensation).c_str()); oXML.OutOfElem(); // AutoExposure oXML.OutOfElem(); // Camera oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // nCameraID starts on 1. If nCameraID < 0 then settings are applied to all cameras. bool CRTProtocol::SetCameraAutoWhiteBalance(const unsigned int nCameraID, const bool enable) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("General"); oXML.IntoElem(); oXML.AddElem("Camera"); oXML.IntoElem(); AddXMLElementUnsignedInt(&oXML, "ID", &nCameraID); oXML.AddElem("AutoWhiteBalance", enable ? "true" : "false"); oXML.OutOfElem(); // Camera oXML.OutOfElem(); // General oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } bool CRTProtocol::SetImageSettings( const unsigned int nCameraID, const bool* pbEnable, const CRTPacket::EImageFormat* peFormat, const unsigned int* pnWidth, const unsigned int* pnHeight, const float* pfLeftCrop, const float* pfTopCrop, const float* pfRightCrop, const float* pfBottomCrop) { CMarkup oXML; oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("Image"); oXML.IntoElem(); oXML.AddElem("Camera"); oXML.IntoElem(); AddXMLElementUnsignedInt(&oXML, "ID", &nCameraID); AddXMLElementBool(&oXML, "Enabled", pbEnable); if (peFormat) { switch (*peFormat) { case CRTPacket::FormatRawGrayscale : oXML.AddElem("Format", "RAWGrayscale"); break; case CRTPacket::FormatRawBGR : oXML.AddElem("Format", "RAWBGR"); break; case CRTPacket::FormatJPG : oXML.AddElem("Format", "JPG"); break; case CRTPacket::FormatPNG : oXML.AddElem("Format", "PNG"); break; } } AddXMLElementUnsignedInt(&oXML, "Width", pnWidth); AddXMLElementUnsignedInt(&oXML, "Height", pnHeight); AddXMLElementFloat(&oXML, "Left_Crop", pfLeftCrop); AddXMLElementFloat(&oXML, "Top_Crop", pfTopCrop); AddXMLElementFloat(&oXML, "Right_Crop", pfRightCrop); AddXMLElementFloat(&oXML, "Bottom_Crop", pfBottomCrop); oXML.OutOfElem(); // Camera oXML.OutOfElem(); // Image oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } return false; } // SetImageSettings bool CRTProtocol::SetForceSettings( const unsigned int nPlateID, const SPoint* psCorner1, const SPoint* psCorner2, const SPoint* psCorner3, const SPoint* psCorner4) { CMarkup oXML; if (nPlateID > 0) { oXML.AddElem("QTM_Settings"); oXML.IntoElem(); oXML.AddElem("Force"); oXML.IntoElem(); oXML.AddElem("Plate"); oXML.IntoElem(); if (mnMajorVersion > 1 || mnMinorVersion > 7) { AddXMLElementUnsignedInt(&oXML, "Plate_ID", &nPlateID); } else { AddXMLElementUnsignedInt(&oXML, "Force_Plate_Index", &nPlateID); } if (psCorner1) { oXML.AddElem("Corner1"); oXML.IntoElem(); AddXMLElementFloat(&oXML, "X", &(psCorner1->fX)); AddXMLElementFloat(&oXML, "Y", &(psCorner1->fY)); AddXMLElementFloat(&oXML, "Z", &(psCorner1->fZ)); oXML.OutOfElem(); // Corner1 } if (psCorner2) { oXML.AddElem("Corner2"); oXML.IntoElem(); AddXMLElementFloat(&oXML, "X", &(psCorner2->fX)); AddXMLElementFloat(&oXML, "Y", &(psCorner2->fY)); AddXMLElementFloat(&oXML, "Z", &(psCorner2->fZ)); oXML.OutOfElem(); // Corner2 } if (psCorner3) { oXML.AddElem("Corner3"); oXML.IntoElem(); AddXMLElementFloat(&oXML, "X", &(psCorner3->fX)); AddXMLElementFloat(&oXML, "Y", &(psCorner3->fY)); AddXMLElementFloat(&oXML, "Z", &(psCorner3->fZ)); oXML.OutOfElem(); // Corner3 } if (psCorner4) { oXML.AddElem("Corner4"); oXML.IntoElem(); AddXMLElementFloat(&oXML, "X", &(psCorner4->fX)); AddXMLElementFloat(&oXML, "Y", &(psCorner4->fY)); AddXMLElementFloat(&oXML, "Z", &(psCorner4->fZ)); oXML.OutOfElem(); // Corner4 } oXML.OutOfElem(); // Plate oXML.OutOfElem(); // Force oXML.OutOfElem(); // QTM_Settings if (SendXML(oXML.GetDoc().c_str())) { return true; } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Illegal force plate id: %d.", nPlateID); } return false; } // SetForceSettings char* CRTProtocol::GetErrorString() { return maErrorStr; } bool CRTProtocol::SendString(const char* pCmdStr, int nType) { int nSize; int nCmdStrLen = (int)strlen(pCmdStr); static char aSendBuffer[5000]; if (nCmdStrLen > sizeof(aSendBuffer)) { sprintf_s (maErrorStr, sizeof(maErrorStr), "String is larger than send buffer."); return false; } // // Header size + length of the string + terminating null char // nSize = 8 + nCmdStrLen + 1; memcpy(aSendBuffer + 8, pCmdStr, nCmdStrLen + 1); if ((mnMajorVersion == 1 && mnMinorVersion == 0) || mbBigEndian) { *((unsigned int*)aSendBuffer) = htonl(nSize); *((unsigned int*)(aSendBuffer + 4)) = htonl(nType); } else { *((unsigned int*)aSendBuffer) = nSize; *((unsigned int*)(aSendBuffer + 4)) = nType; } if (mpoNetwork->Send(aSendBuffer, nSize) == false) { sprintf_s (maErrorStr, sizeof(maErrorStr), mpoNetwork->GetErrorString()); return false; } return true; } // SendString bool CRTProtocol::SendCommand(const char* pCmdStr) { return SendString(pCmdStr, CRTPacket::PacketCommand); } // SendCommand bool CRTProtocol::SendCommand(const char* pCmdStr, char* pCommandResponseStr, unsigned int nCommandResponseLen, unsigned int timeout) { CRTPacket::EPacketType eType; if (SendString(pCmdStr, CRTPacket::PacketCommand)) { while (ReceiveRTPacket(eType, true, timeout) > 0) { if (eType == CRTPacket::PacketCommand) { strcpy_s(pCommandResponseStr, nCommandResponseLen, mpoRTPacket->GetCommandString()); return true; } if (eType == CRTPacket::PacketError) { strcpy_s(pCommandResponseStr, nCommandResponseLen, mpoRTPacket->GetErrorString()); return false; } } } else { char pTmpStr[256]; strcpy_s(pTmpStr, sizeof(pTmpStr), maErrorStr); sprintf_s(maErrorStr, sizeof(maErrorStr), "\'%s\' command failed. %s", pCmdStr, pTmpStr); } pCommandResponseStr[0] = 0; return false; } // SendCommand bool CRTProtocol::SendXML(const char* pCmdStr) { CRTPacket::EPacketType eType; if (SendString(pCmdStr, CRTPacket::PacketXML)) { if (ReceiveRTPacket(eType, true) > 0) { if (eType == CRTPacket::PacketCommand) { if (strcmp(mpoRTPacket->GetCommandString(), "Setting parameters succeeded") == 0) { return true; } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Expected command response \"Setting parameters succeeded\". Got \"%s\".", mpoRTPacket->GetCommandString()); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Expected command response packet. Got packet type %d.", (int)eType); } } else { sprintf_s(maErrorStr, sizeof(maErrorStr), "Missing command response packet."); } } else { char pTmpStr[256]; strcpy_s(pTmpStr, sizeof(pTmpStr), maErrorStr); sprintf_s(maErrorStr, sizeof(maErrorStr), "Failed to send XML string. %s", pTmpStr); } return false; } // SendXML void CRTProtocol::AddXMLElementBool(CMarkup* oXML, _TCHAR* tTag, const bool* pbValue, _TCHAR* tTrue, _TCHAR* tFalse) { if (pbValue) { oXML->AddElem(tTag, *pbValue ? tTrue : tFalse); } } void CRTProtocol::AddXMLElementBool(CMarkup* oXML, _TCHAR* tTag, const bool pbValue, _TCHAR* tTrue, _TCHAR* tFalse) { oXML->AddElem(tTag, pbValue ? tTrue : tFalse); } void CRTProtocol::AddXMLElementInt(CMarkup* oXML, _TCHAR* tTag, const int* pnValue) { if (pnValue) { std::string tVal; tVal = Format("%d", *pnValue); oXML->AddElem(tTag, tVal.c_str()); } } void CRTProtocol::AddXMLElementUnsignedInt(CMarkup* oXML, _TCHAR* tTag, const unsigned int* pnValue) { if (pnValue) { std::string tVal; tVal = Format("%u", *pnValue); oXML->AddElem(tTag, tVal.c_str()); } } void CRTProtocol::AddXMLElementFloat(CMarkup* oXML, _TCHAR* tTag, const float* pfValue, unsigned int pnDecimals) { if (pfValue) { std::string tVal; char fFormat[10]; sprintf_s(fFormat, sizeof(fFormat), "%%.%df", pnDecimals); tVal = Format(fFormat, *pfValue); oXML->AddElem(tTag, tVal.c_str()); } } std::string CRTProtocol::Format(const char *fmt, ...) const { using std::string; using std::vector; string retStr(""); if (NULL != fmt) { va_list marker = NULL; // initialize variable arguments va_start(marker, fmt); // Get formatted string length adding one for NULL size_t len = _vscprintf(fmt, marker) + 1; // Create a char vector to hold the formatted string. vector<char> buffer(len, '\0'); int nWritten = _vsnprintf_s(&buffer[0], buffer.size(), len, fmt, marker); if (nWritten > 0) { retStr = &buffer[0]; } // Reset variable arguments va_end(marker); } return retStr; } bool CRTProtocol::CompareNoCase(std::string tStr1, const _TCHAR* tStr2) const { std::transform(tStr1.begin(), tStr1.end(), tStr1.begin(), ::tolower); return tStr1.compare(tStr2) == 0; }
[ "lars.nilsson@qualisys.se" ]
lars.nilsson@qualisys.se
5eb88065fb04ce18ce49f57564112d9c363a508f
70418d8faa76b41715c707c54a8b0cddfb393fb3
/13052.cpp
7f25a050a1e90526dd3c9bca0cba3f9d8856494c
[]
no_license
evandrix/UVa
ca79c25c8bf28e9e05cae8414f52236dc5ac1c68
17a902ece2457c8cb0ee70c320bf0583c0f9a4ce
refs/heads/master
2021-06-05T01:44:17.908960
2017-10-22T18:59:42
2017-10-22T18:59:42
107,893,680
3
1
null
null
null
null
UTF-8
C++
false
false
357
cpp
#include <bits/stdc++.h> using namespace std; int main() { int testcase, cases = 0; scanf("%d", &testcase); while (testcase--) { int A, B; double p, q; scanf("%d %d", &A, &B); if (A == 0 && B == 0) p = q = 0; else if (B % 2 == 0) p = 1, q = 0; else p = 0, q = 1; printf("Case %d: %.3lf %.3lf\n", ++cases, p, q); } return 0; }
[ "yleewei@dso.org.sg" ]
yleewei@dso.org.sg
5406bc43f39f0e160202ee742922f9aa67ecebec
f819d6e972a5cf26ad0d13b2be482a353d3cfeb9
/Doc/Sinkhold_DocPJ/Sinkhold_Doc/AWP_Weapons.cpp
dcf04c13320c277326c5c5e7a60e0046ac4e9de6
[]
no_license
Sandwich33/Sinkhole4_9
b317dc2ca75879597197c4db1c2983ac7c677e48
72d0cb90ea6b8ba39966fd23e9b31b1ef8d65be1
refs/heads/master
2021-01-21T15:26:23.278122
2016-08-11T09:17:25
2016-08-11T09:17:25
53,466,519
0
0
null
null
null
null
UTF-8
C++
false
false
44
cpp
#include "stdafx.h" #include "AWP_Weapons.h"
[ "edragon33@gmail.com" ]
edragon33@gmail.com
dc0277a9a72b259fd3577b39cb817780476ade7b
e5010e873ef995693036e3a99cc78bfdfba7eff6
/build/build-DeviceToolBox-unknown-Debug/ui_ConfigDialog.h
0f7ff988cefd8f6b4c1a701859f46c306f6c4c14
[]
no_license
halukasama/DLTools
85f03ca966fb866d1462d51902381ed199f1ec57
43c76ee8680044561529f7f415e65cc0a9af8071
refs/heads/master
2021-07-09T20:18:35.914240
2017-10-10T18:32:13
2017-10-10T18:32:13
106,455,953
0
0
null
null
null
null
UTF-8
C++
false
false
3,842
h
/******************************************************************************** ** Form generated from reading UI file 'ConfigDialog.ui' ** ** Created by: Qt User Interface Compiler version 5.6.2 ** ** WARNING! All changes made in this file will be lost when recompiling UI file! ********************************************************************************/ #ifndef UI_CONFIGDIALOG_H #define UI_CONFIGDIALOG_H #include <QtCore/QVariant> #include <QtWidgets/QAction> #include <QtWidgets/QApplication> #include <QtWidgets/QButtonGroup> #include <QtWidgets/QDialog> #include <QtWidgets/QDialogButtonBox> #include <QtWidgets/QGridLayout> #include <QtWidgets/QHeaderView> #include <QtWidgets/QLabel> #include <QtWidgets/QLineEdit> QT_BEGIN_NAMESPACE class Ui_ConfigDialog { public: QGridLayout *gridLayout; QLabel *label; QLineEdit *ipLineEdit; QLabel *label_2; QLineEdit *gatewayLineEdit; QLineEdit *subnetLineEdit; QLabel *label_3; QDialogButtonBox *buttonBox; void setupUi(QDialog *ConfigDialog) { if (ConfigDialog->objectName().isEmpty()) ConfigDialog->setObjectName(QStringLiteral("ConfigDialog")); ConfigDialog->resize(370, 200); ConfigDialog->setMinimumSize(QSize(370, 200)); ConfigDialog->setMaximumSize(QSize(370, 200)); gridLayout = new QGridLayout(ConfigDialog); gridLayout->setObjectName(QStringLiteral("gridLayout")); label = new QLabel(ConfigDialog); label->setObjectName(QStringLiteral("label")); gridLayout->addWidget(label, 0, 0, 1, 1); ipLineEdit = new QLineEdit(ConfigDialog); ipLineEdit->setObjectName(QStringLiteral("ipLineEdit")); ipLineEdit->setEnabled(false); gridLayout->addWidget(ipLineEdit, 0, 1, 1, 1); label_2 = new QLabel(ConfigDialog); label_2->setObjectName(QStringLiteral("label_2")); gridLayout->addWidget(label_2, 1, 0, 1, 1); gatewayLineEdit = new QLineEdit(ConfigDialog); gatewayLineEdit->setObjectName(QStringLiteral("gatewayLineEdit")); gatewayLineEdit->setEnabled(false); gridLayout->addWidget(gatewayLineEdit, 2, 1, 1, 1); subnetLineEdit = new QLineEdit(ConfigDialog); subnetLineEdit->setObjectName(QStringLiteral("subnetLineEdit")); subnetLineEdit->setEnabled(false); gridLayout->addWidget(subnetLineEdit, 1, 1, 1, 1); label_3 = new QLabel(ConfigDialog); label_3->setObjectName(QStringLiteral("label_3")); gridLayout->addWidget(label_3, 2, 0, 1, 1); buttonBox = new QDialogButtonBox(ConfigDialog); buttonBox->setObjectName(QStringLiteral("buttonBox")); buttonBox->setOrientation(Qt::Horizontal); buttonBox->setStandardButtons(QDialogButtonBox::Cancel|QDialogButtonBox::Ok); gridLayout->addWidget(buttonBox, 3, 0, 1, 2); retranslateUi(ConfigDialog); QObject::connect(buttonBox, SIGNAL(accepted()), ConfigDialog, SLOT(accept())); QObject::connect(buttonBox, SIGNAL(rejected()), ConfigDialog, SLOT(reject())); QMetaObject::connectSlotsByName(ConfigDialog); } // setupUi void retranslateUi(QDialog *ConfigDialog) { ConfigDialog->setWindowTitle(QApplication::translate("ConfigDialog", "\350\256\276\345\244\207\344\277\241\346\201\257", 0)); label->setText(QApplication::translate("ConfigDialog", "IP\345\234\260\345\235\200:", 0)); label_2->setText(QApplication::translate("ConfigDialog", "\345\255\220\347\275\221\346\216\251\347\240\201:", 0)); label_3->setText(QApplication::translate("ConfigDialog", "\347\275\221\345\205\263:", 0)); } // retranslateUi }; namespace Ui { class ConfigDialog: public Ui_ConfigDialog {}; } // namespace Ui QT_END_NAMESPACE #endif // UI_CONFIGDIALOG_H
[ "jlwangtat@gmail.com" ]
jlwangtat@gmail.com
90c14a59c54ad7a3e1710777f296178933dc5828
2cf5e1f2c1d7acaf0f2f9f1f939994d06b494b11
/src/hash/sha256.cpp
58e5cd89bc549f7d10f290361691a90644932a7d
[ "MIT" ]
permissive
solosTec/crypto
b3ba5436788719a219b15d212e8db5c744c195d6
32d6d68fed185f7c437d4f1764c72b50721ca466
refs/heads/master
2023-08-31T02:07:40.666856
2021-02-12T10:08:34
2021-02-12T10:08:34
213,223,655
0
1
MIT
2022-08-22T05:30:41
2019-10-06T18:42:48
C++
UTF-8
C++
false
false
945
cpp
/* * The MIT License (MIT) * * Copyright (c) 2017 Sylko Olzscher * */ #include <crypto/hash/sha256.h> #include <openssl/crypto.h> // OPENSSL_cleanse namespace cyng { namespace crypto { sha256::sha256() : ctx_() { SHA256_Init(&ctx_); } bool sha256::update(std::string const& str) { return update(str.c_str(), str.length()); } bool sha256::update(const void* ptr, std::size_t length) { return SHA256_Update(&ctx_, ptr, length) != 0; } digest_sha256::value_type sha256::finalize() { digest_sha256::value_type d; SHA256_Final(d.data(), &ctx_); OPENSSL_cleanse(&ctx_, sizeof(ctx_)); return d; } } crypto::digest_sha256::value_type sha256_hash(std::string const& str) { crypto::sha256 h; h.update(str); return h.finalize(); } crypto::digest_sha256::value_type sha256_hash(buffer_t const& b) { crypto::sha256 h; h.update(b.data(), b.size()); return h.finalize(); } }
[ "CmdPirx@gmail.com" ]
CmdPirx@gmail.com
4d54f6f3dd2f1431c6b83a166a67ae1d686b4dc2
92e7a96c196e563b70f78db321680d830af80a53
/InstitutionalTrading/Client/CltPresentation/ReportDataProviderFactory.h
f341bbee23fb289e83ecf414ad65788a52ba699a
[]
no_license
alexfordc/zq
513723341132dd2b01f5ca3debb567b2fd31c033
a0b05b7416fe68784e072da477e8c869097584e2
refs/heads/master
2021-05-25T14:19:37.317957
2018-02-24T05:57:23
2018-02-24T05:57:23
null
0
0
null
null
null
null
GB18030
C++
false
false
1,252
h
#pragma once #include "AbstractReportDataProvider.h" #include "AccountHodeReportDP.h" #include "AccountInterestReportDP.h" #include "AccountTradesReportDP.h" #include "Singleton.h" namespace ReportDataProvider { public interface class IReportDataProviderFactory { public: virtual IReportDataProvider^ CreateDataProvider() = 0; }; //用户持仓统计工厂 public ref class CAccountHodeReportDataProviderFactory :public IReportDataProviderFactory, Singleton<CAccountHodeReportDataProviderFactory> { public: virtual IReportDataProvider^ CreateDataProvider() { return gcnew CAccountHodeReportDataProvider(); } }; //用户权益统计工厂 public ref class CAccountInterestsDataProviderFactory :public IReportDataProviderFactory, Singleton<CAccountInterestsDataProviderFactory> { public: virtual IReportDataProvider^ CreateDataProvider() { return gcnew CAccountInterestReportDataProvider(); } }; //用户交易统计工厂 public ref class CAccountTradesReportDataProviderFactory :public IReportDataProviderFactory, Singleton<CAccountTradesReportDataProviderFactory> { public: virtual IReportDataProvider^ CreateDataProvider() { return gcnew CAccountTradesReportDataProvider(); } }; }
[ "w.z.y2006@163.com" ]
w.z.y2006@163.com
83c4bcb17f190660c0dab4d01aac8f729765cb3f
ebe1eaf68b4ebe941e564ecaf536a06d625e1eda
/Engine/include/XSEIImage.h
44cd916cb404ac7c1836fdafa6174c523aa81c14
[]
no_license
przemyslaw-szymanski/x-source-engine
54a23e9ad740f7ab1b4a439f87733c366233eb58
1afa8c0dea628b6a252ee40aef39c31ec99d3c97
refs/heads/master
2020-12-24T15:41:01.851654
2015-08-07T14:37:12
2015-08-07T14:37:12
13,867,990
0
0
null
null
null
null
UTF-8
C++
false
false
2,251
h
#ifndef XSE_IIMAGE_H #define XSE_IIMAGE_H #include "XSEIResource.h" #include "XSERenderSystemCommon.h" namespace XSE { namespace Resources { class XST_API IImage : public IResource { friend class CImageManager; public: enum class CHANNEL : u32 { RED, GREEN, BLUE, ALPHA, _MAX }; typedef XST::TCObjectSmartPointer< IImage > ImagePtr; typedef XST::TCWeakPointer< IImage > ImageWeakPtr; public: IImage(XSE_IRESOURCE_DECL_PARAMS) : XSE_IRESOURCE_CTOR {} virtual ~IImage() {} virtual ImagePtr Clone() const = 0; virtual XST::CColor GetColor(cu32& uiX, cu32& uiY) const = 0; virtual XST::CColor GetColor(cu32& uiPosition) const = 0; virtual void GetColor(cu32& uiPosition, XST::CColor* pColorOut) const = 0; virtual void GetColor(cu32& uiX, cu32& uiY, XST::CColor* pColorOut) const = 0; virtual u8 GetChannelColor(cu32& uiPosition, const IImage::CHANNEL& eChannel) const = 0; virtual u8 GetChannelColor(cu32& uiX, cu32& uiY, const IImage::CHANNEL& eChannel) const = 0; virtual u32 GetPixelCount() const = 0; virtual void SetColor(cu32& uiX, cu32& uiY, const XST::CColor& Color) = 0; virtual void SetColor(cu32& uiPosition, const XST::CColor& Color) = 0; virtual void SetSize(cu32& uiWidth, cu32& uiHeight) = 0; virtual u32 GetWidth() const = 0; virtual u32 GetHeight() const = 0; virtual u32 GetBitsPerPixel() const = 0; virtual void SetBitsPerPixel(IMAGE_BPP_TYPE eType) = 0; virtual cu8* GetData() const = 0; virtual ul32 GetDataSize() const = 0; virtual IMAGE_FORMAT GetFormat() const = 0; virtual RS_FORMAT GetRenderSystemFormat() const = 0; virtual void SetFormat(IMAGE_FORMAT eFormat) = 0; virtual bool IsManual() const = 0; virtual void SetDataType(IMAGE_DATA_TYPE eType) = 0; virtual void Scale(cu32& uiWidth, cu32& uiHeight) = 0; virtual i32 Save(xst_castring& strFileName) = 0; }; }//resources typedef Resources::IImage::ImagePtr ImagePtr; typedef Resources::IImage::ImageWeakPtr ImageWeakPtr; typedef Resources::IImage::CHANNEL COLOR_CHANNEL; }//xse #endif
[ "przemek.p.szymanski@gmail.com" ]
przemek.p.szymanski@gmail.com
5518b3dff98d36f34f5c381c28a0bde3b6aed9b4
a1ed68a597f95370af7003d81f553f6790fa01a2
/uml/cpp.source/Pattern.cpp
80864cb7eb3e7e6672c20582e93cb1722c5d4ba1
[]
no_license
Sighter/remeta2
46ee956ec86379a05c11f9b94ec9e91b7017edcf
927f2bc1f0ad5362a95ed200c447ed1e68e693a5
refs/heads/master
2016-09-06T04:10:05.302854
2015-02-07T14:59:11
2015-02-07T14:59:11
2,132,918
0
0
null
null
null
null
UTF-8
C++
false
false
22
cpp
#include "Pattern.h"
[ "sighter@resource-dnb.de" ]
sighter@resource-dnb.de
2f348e6341911475b6c609f12706907ef3d602ba
92e4b8185fc2a86d6b5920e84941a14dc31a5a57
/starwars/Camera.cpp
3787ad36aeb01208298e647a46649c0692c85792
[]
no_license
iph/Graphics
31761cd346e7480e3fae7f68cb2eb6ca3f99da54
b6ac1445fb27ac1acec9cd88844e841e57bb0c3a
refs/heads/master
2020-06-05T05:30:14.753092
2012-10-16T21:28:13
2012-10-16T21:28:13
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,975
cpp
#include "Camera.h" Camera::Camera(GLfloat * pos, GLfloat * at, GLfloat * up_i): camLocation(pos[0], pos[1], pos[2]), lookAt(at[0],at[1],at[2]), up(up_i[0], up_i[1], up_i[2]){} void Camera::translate(float xpos, float ypos, float zpos){ camLocation.x += xpos; camLocation.y += ypos; camLocation.z += zpos; //cout << "Z:"<<camLocation.z << "Lookat:"<<lookAt.z<< endl; //cout << camLocation.z + lookAt.z << endl; } void Camera::rotate(float deg, int x, int y, int z){ Vertex temp(camLocation.x, camLocation.y, camLocation.z); translate((float)-camLocation.x, (float)-camLocation.y, (float)-camLocation.z); deg = 3.141592654f*2/180 * deg; if(x == 1){ GLfloat ypos = camLocation.y; GLfloat zpos = camLocation.z; camLocation.y = ypos*(float)cos(deg) - zpos*(float)sin(deg); camLocation.z = ypos*(float)sin(deg) + zpos*(float)cos(deg); ypos = lookAt.y; zpos = lookAt.z; lookAt.y = ypos*(float)cos(deg) - zpos*(float)sin(deg); lookAt.z = ypos*(float)sin(deg) + zpos*(float)cos(deg); } if(y == 1){ GLfloat xpos = camLocation.x; GLfloat zpos = camLocation.z; camLocation.x = xpos*(float)cos(deg) - zpos*(float)sin(deg); camLocation.z = xpos*(float)sin(deg) + zpos*(float)cos(deg); xpos = lookAt.x; zpos = lookAt.z; lookAt.x = xpos*(float)cos(deg) - zpos*(float)sin(deg); lookAt.z = xpos*(float)sin(deg) + zpos*(float)cos(deg); } if(z == 1){ GLfloat xpos = camLocation.x; GLfloat ypos = camLocation.y; camLocation.x = xpos*(float)cos(deg) - ypos*(float)sin(deg); camLocation.y = xpos*(float)sin(deg) + ypos*(float)cos(deg); xpos = lookAt.x; ypos = lookAt.y; lookAt.x = xpos*(float)cos(deg) - ypos*(float)sin(deg); lookAt.y = xpos*(float)sin(deg) + ypos*(float)cos(deg); xpos = up.x; ypos = up.y; up.x = xpos*(float)cos(deg) - ypos*(float)sin(deg); up.y = xpos*(float)sin(deg) + ypos*(float)cos(deg); } translate((float)temp.x, (float)temp.y, (float)temp.z); } void Camera::updateLookAt(){ }
[ "seanmyers0608@gmail.com" ]
seanmyers0608@gmail.com
b1dcf48a396840f12abd4db2e97322439745a88f
1576d13faa16eca786afac8a62111fa4d92fc499
/cpp/2014/bomberman/GDL-library/doxygen/.svn/text-base/Model.cpp.svn-base
f5652525dad3ca529a976ff78cc6884a8f252d25
[]
no_license
LeBAD420/EpiHistory
7b47796df513227faa332839a521977befc2d110
6fb2354ce74af4242f1ef93689cddb85b8a5f4b7
refs/heads/master
2020-06-14T10:09:56.390302
2013-08-01T15:44:57
2013-08-01T15:44:57
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,038
/* ** ** */ #include <vector> #include <iostream> #include <GL/gl.h> #include <GL/glu.h> #include "Assert.hpp" #include "ModelImpl.hpp" #include "Model.hpp" namespace gdl { Model::Model() : Resource<ModelImpl>(NULL) { } Model::Model(ModelImpl* impl) : Resource<ModelImpl>(impl) { } Model::~Model() { } Model Model::load(const std::string& filename) { return ModelImpl::load(filename); } void Model::update(const IClock& gameTime) { data_->update(gameTime); } void Model::draw() { data_->draw(); } void Model::draw_pose(int pose_id) { data_->draw_pose(pose_id); } std::vector<std::string> const& Model::get_animation_names() const { return data_->get_animation_names(); } std::vector<std::string> const& Model::get_stackanimation_names() const { return data_->get_stackanimation_names(); } void Model::stop_animation(const std::string& name) { data_->stop_animation(name); } const Color& Model::get_default_model_color() const { return this->data_->get_default_color(); } void Model::set_default_model_color(const Color& color) { this->data_->set_default_color(color); } bool Model::cut_animation(Model& _model, const std::string& stackAnim, int id_start, int id_end, const std::string& _newName) { return ModelImpl::cut_animation(*_model.data_, stackAnim, id_start, id_end, _newName); } bool Model::animation_hasStarted(const std::string& name) const { return !this->anim_is_ended(name); } bool Model::anim_is_ended(const std::string& name) const { return data_->anim_is_ended(name); } // -1 si l animation n existe pas ou n est pas jouer double Model::get_anim_speed(const std::string& name) const { return data_->get_anim_speed(name); } // -1 si l animation n existe pas ou n est pas jouer double Model::get_anim_blendfactor(const std::string& name) const { return data_->get_anim_blendfactor(name); } char Model::get_anim_state(const std::string& name) const { return data_->get_anim_state(name); } void Model::set_anim_bendfactor(const std::string& name, double blendFactor) { data_->set_anim_bendfactor(name, blendFactor); } void Model::set_anim_speed(const std::string& name, double speed) { data_->set_anim_speed(name, speed); } // Anim::AnimStates void Model::set_anim_state(const std::string& name, char state) { data_->set_anim_state(name, state); } void Model::add_anim_state(const std::string& name, Anim::AnimStates state) { data_->add_anim_state(name, state); } void Model::remove_anim_state(const std::string& name, Anim::AnimStates state) { data_->remove_anim_state(name, state); } bool Model::play(const std::string& name, char state) { return data_->play(name, state); } void Model::infos() { } void Model::Begin() { ModelImpl::Begin(); } void Model::End() { ModelImpl::End(); } }
[ "quentin.pidoux@epitech.eu" ]
quentin.pidoux@epitech.eu
08e50157ca1c2b74b6f9794ce40b6c378183567b
ebe1e922d0237f8bf79d018cab7ff9878fcd2101
/Vidu/dem_so_dong_cua_tep.cpp
c5012b4343658087d3287bebf3e54b8c92b5e87a
[]
no_license
BinhMinhs10/dev-C-
b79d1ea314c314e1dea8c4fef4c8e7d489285deb
7100683517bdde4840545fa4c7f8ececd5eff618
refs/heads/master
2021-04-15T18:33:05.080965
2018-03-23T16:17:09
2018-03-23T16:17:09
126,510,397
0
0
null
null
null
null
UTF-8
C++
false
false
126
cpp
#define EOF-1 #define EOL 0x0A int ch,dem; ch=getchar(); while ((ch=getchar()) != EOF) while ((ch=getchar()) != EOL) dem++;
[ "nguyenbinhminh07101997@gmail.com" ]
nguyenbinhminh07101997@gmail.com
f687435ad8566b16b12c7b9cd2490a6c7b234422
596e587664f0ea8f9e8ca8b04b238f4dcd84fc55
/dfmux/src/HardwareMap.cxx
ebcf80cc8a475b911aac2b848ba964c5cf4f6e60
[ "BSD-2-Clause" ]
permissive
JohnChood2/spt3g_software
44c049aba80967a17582e6f916eede682bdb498a
9e9491df790a15f2ed61e366db639386e7cf6bba
refs/heads/master
2020-03-23T10:47:35.573109
2018-06-27T22:52:47
2018-06-27T22:52:47
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,838
cxx
#include <arpa/inet.h> #include <sstream> #include <pybindings.h> #include <dfmux/HardwareMap.h> #include <container_pybindings.h> std::string DfMuxChannelMapping::Description() const { std::ostringstream s; s << "IP: " << ((ntohl(board_ip) >> 24) & 0xff) << "." << ((ntohl(board_ip) >> 16) & 0xff) << "." << ((ntohl(board_ip) >> 8) & 0xff) << "." << (ntohl(board_ip) & 0xff) << ", " << "Board: " << board_serial << " (slot " << board_slot << " crate "<< crate_serial<< "), " << "Module (1-indexed): " << (module + 1) << ", Channel (1-indexed): " << (channel + 1); return s.str(); } std::string DfMuxChannelMapping::Summary() const { std::ostringstream s; if (crate_serial != -1) s << crate_serial << "_" << board_slot << "/" << (module + 1) << "/" << (channel + 1); else s << board_serial << "/" << (module + 1) << "/" << (channel + 1); return s.str(); } template <class A> void DfMuxChannelMapping::serialize(A &ar, unsigned v) { using namespace cereal; ar & make_nvp("G3FrameObject", base_class<G3FrameObject>(this)); ar & make_nvp("board_ip", board_ip); ar & make_nvp("board_serial", board_serial); ar & make_nvp("board_slot", board_slot); if (v > 1) ar & make_nvp("crate_serial", crate_serial); else crate_serial = 0; ar & make_nvp("module", module); ar & make_nvp("channel", channel); } G3_SERIALIZABLE_CODE(DfMuxChannelMapping); G3_SERIALIZABLE_CODE(DfMuxWiringMap); PYBINDINGS("dfmux") { EXPORT_FRAMEOBJECT(DfMuxChannelMapping, init<>(), "Bolometer wiring information. Module and channel IDs are stored " "zero-indexed, but be aware that they often printed one-indexed " "for compatibility with pydfmux.") .def_readwrite("board_ip", &DfMuxChannelMapping::board_ip, "IP Address of the board, encoded as an int using struct") .def_readwrite("board_serial", &DfMuxChannelMapping::board_serial, "Serial number of the readout board to which this channel is " "attached.") .def_readwrite("board_slot", &DfMuxChannelMapping::board_slot, "Crate slot of the board to which this channel is attached or -1 " "if the board is not in a crate.") .def_readwrite("crate_serial", &DfMuxChannelMapping::crate_serial, "Serial number of the crate in which the readout board is housed " "or -1 if the board is not in a crate.") .def_readwrite("module", &DfMuxChannelMapping::module, "0-indexed module/SQUID ID of the channel") .def_readwrite("channel", &DfMuxChannelMapping::channel, "0-indexed channel number on the parent module/SQUID") ; register_g3map<DfMuxWiringMap>("DfMuxWiringMap", "Mapping from " "logical detector ID string (same as used in timestreams) to wiring " "information (the board, module, and channel to which a given " "detector is connected)"); }
[ "nwhitehorn@berkeley.edu" ]
nwhitehorn@berkeley.edu
13e38310fcb3d1070918aff62d94ff728af5f711
b70ce6c518e9d890c22d17cd2e7af992a12cc0e0
/External/json-3.5.0/Inc/json/json.hpp
3a2bbf21e00e4af80a76630dc632e7c7d1639cb4
[ "MIT", "Zlib", "BSL-1.0", "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
nicolasgustafsson/WonderMake
6266e18ffe83e8aec6d8641f3ceda9c2c5519fd5
27a08637d01dcf0d14ee2fac90db46a267112013
refs/heads/master
2023-08-16T22:24:38.558935
2022-01-03T09:58:02
2022-01-03T09:58:02
159,575,762
5
0
MIT
2023-09-06T12:29:38
2018-11-28T22:50:28
C++
UTF-8
C++
false
false
714,449
hpp
/* __ _____ _____ _____ __| | __| | | | JSON for Modern C++ | | |__ | | | | | | version 3.5.0 |_____|_____|_____|_|___| https://github.com/nlohmann/json Licensed under the MIT License <http://opensource.org/licenses/MIT>. SPDX-License-Identifier: MIT Copyright (c) 2013-2018 Niels Lohmann <http://nlohmann.me>. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #ifndef NLOHMANN_JSON_HPP #define NLOHMANN_JSON_HPP #define NLOHMANN_JSON_VERSION_MAJOR 3 #define NLOHMANN_JSON_VERSION_MINOR 5 #define NLOHMANN_JSON_VERSION_PATCH 0 #include <algorithm> // all_of, find, for_each #include <cassert> // assert #include <ciso646> // and, not, or #include <cstddef> // nullptr_t, ptrdiff_t, size_t #include <functional> // hash, less #include <initializer_list> // initializer_list #include <iosfwd> // istream, ostream #include <iterator> // random_access_iterator_tag #include <numeric> // accumulate #include <string> // string, stoi, to_string #include <utility> // declval, forward, move, pair, swap #define and && #define and_eq &= #define bitand & #define bitor | #define compl ~ #define not ! #define not_eq != #define or || #define or_eq |= #define xor ^ #define xor_eq ^= // #include <nlohmann/json_fwd.hpp> #ifndef NLOHMANN_JSON_FWD_HPP #define NLOHMANN_JSON_FWD_HPP #include <cstdint> // int64_t, uint64_t #include <map> // map #include <memory> // allocator #include <string> // string #include <vector> // vector /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief default JSONSerializer template argument This serializer ignores the template arguments and uses ADL ([argument-dependent lookup](https://en.cppreference.com/w/cpp/language/adl)) for serialization. */ template<typename T = void, typename SFINAE = void> struct adl_serializer; template<template<typename U, typename V, typename... Args> class ObjectType = std::map, template<typename U, typename... Args> class ArrayType = std::vector, class StringType = std::string, class BooleanType = bool, class NumberIntegerType = std::int64_t, class NumberUnsignedType = std::uint64_t, class NumberFloatType = double, template<typename U> class AllocatorType = std::allocator, template<typename T, typename SFINAE = void> class JSONSerializer = adl_serializer> class basic_json; /*! @brief JSON Pointer A JSON pointer defines a string syntax for identifying a specific value within a JSON document. It can be used with functions `at` and `operator[]`. Furthermore, JSON pointers are the base for JSON patches. @sa [RFC 6901](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ template<typename BasicJsonType> class json_pointer; /*! @brief default JSON class This type is the default specialization of the @ref basic_json class which uses the standard template types. @since version 1.0.0 */ using json = basic_json<>; } // namespace nlohmann #endif // #include <nlohmann/detail/macro_scope.hpp> // This file contains all internal macro definitions // You MUST include macro_unscope.hpp at the end of json.hpp to undef all of them // exclude unsupported compilers #if !defined(JSON_SKIP_UNSUPPORTED_COMPILER_CHECK) #if defined(__clang__) #if (__clang_major__ * 10000 + __clang_minor__ * 100 + __clang_patchlevel__) < 30400 // #error "unsupported Clang version - see https://github.com/nlohmann/json#supported-compilers" #endif #elif defined(__GNUC__) && !(defined(__ICC) || defined(__INTEL_COMPILER)) #if (__GNUC__ * 10000 + __GNUC_MINOR__ * 100 + __GNUC_PATCHLEVEL__) < 40800 #error "unsupported GCC version - see https://github.com/nlohmann/json#supported-compilers" #endif #endif #endif // disable float-equal warnings on GCC/clang #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wfloat-equal" #endif // disable documentation warnings on clang #if defined(__clang__) #pragma GCC diagnostic push #pragma GCC diagnostic ignored "-Wdocumentation" #endif // allow for portable deprecation warnings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_DEPRECATED __attribute__((deprecated)) #elif defined(_MSC_VER) #define JSON_DEPRECATED __declspec(deprecated) #else #define JSON_DEPRECATED #endif // allow to disable exceptions #if (defined(__cpp_exceptions) || defined(__EXCEPTIONS) || defined(_CPPUNWIND)) && !defined(JSON_NOEXCEPTION) #define JSON_THROW(exception) throw exception #define JSON_TRY try #define JSON_CATCH(exception) catch(exception) #define JSON_INTERNAL_CATCH(exception) catch(exception) #else #define JSON_THROW(exception) std::abort() #define JSON_TRY if(true) #define JSON_CATCH(exception) if(false) #define JSON_INTERNAL_CATCH(exception) if(false) #endif // override exception macros #if defined(JSON_THROW_USER) #undef JSON_THROW #define JSON_THROW JSON_THROW_USER #endif #if defined(JSON_TRY_USER) #undef JSON_TRY #define JSON_TRY JSON_TRY_USER #endif #if defined(JSON_CATCH_USER) #undef JSON_CATCH #define JSON_CATCH JSON_CATCH_USER #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_CATCH_USER #endif #if defined(JSON_INTERNAL_CATCH_USER) #undef JSON_INTERNAL_CATCH #define JSON_INTERNAL_CATCH JSON_INTERNAL_CATCH_USER #endif // manual branch prediction #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #define JSON_LIKELY(x) __builtin_expect(!!(x), 1) #define JSON_UNLIKELY(x) __builtin_expect(!!(x), 0) #else #define JSON_LIKELY(x) x #define JSON_UNLIKELY(x) x #endif // C++ language standard detection #if (defined(__cplusplus) && __cplusplus >= 201703L) || (defined(_HAS_CXX17) && _HAS_CXX17 == 1) // fix for issue #464 #define JSON_HAS_CPP_17 #define JSON_HAS_CPP_14 #elif (defined(__cplusplus) && __cplusplus >= 201402L) || (defined(_HAS_CXX14) && _HAS_CXX14 == 1) #define JSON_HAS_CPP_14 #endif /*! @brief macro to briefly define a mapping between an enum and JSON @def NLOHMANN_JSON_SERIALIZE_ENUM @since version 3.4.0 */ #define NLOHMANN_JSON_SERIALIZE_ENUM(ENUM_TYPE, ...) \ template<typename BasicJsonType> \ inline void to_json(BasicJsonType& j, const ENUM_TYPE& e) \ { \ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [e](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ { \ return ej_pair.first == e; \ }); \ j = ((it != std::end(m)) ? it : std::begin(m))->second; \ } \ template<typename BasicJsonType> \ inline void from_json(const BasicJsonType& j, ENUM_TYPE& e) \ { \ static_assert(std::is_enum<ENUM_TYPE>::value, #ENUM_TYPE " must be an enum!"); \ static const std::pair<ENUM_TYPE, BasicJsonType> m[] = __VA_ARGS__; \ auto it = std::find_if(std::begin(m), std::end(m), \ [j](const std::pair<ENUM_TYPE, BasicJsonType>& ej_pair) -> bool \ { \ return ej_pair.second == j; \ }); \ e = ((it != std::end(m)) ? it : std::begin(m))->first; \ } // Ugly macros to avoid uglier copy-paste when specializing basic_json. They // may be removed in the future once the class is split. #define NLOHMANN_BASIC_JSON_TPL_DECLARATION \ template<template<typename, typename, typename...> class ObjectType, \ template<typename, typename...> class ArrayType, \ class StringType, class BooleanType, class NumberIntegerType, \ class NumberUnsignedType, class NumberFloatType, \ template<typename> class AllocatorType, \ template<typename, typename = void> class JSONSerializer> #define NLOHMANN_BASIC_JSON_TPL \ basic_json<ObjectType, ArrayType, StringType, BooleanType, \ NumberIntegerType, NumberUnsignedType, NumberFloatType, \ AllocatorType, JSONSerializer> // #include <nlohmann/detail/meta/cpp_future.hpp> #include <ciso646> // not #include <cstddef> // size_t #include <type_traits> // conditional, enable_if, false_type, integral_constant, is_constructible, is_integral, is_same, remove_cv, remove_reference, true_type namespace nlohmann { namespace detail { // alias templates to reduce boilerplate template<bool B, typename T = void> using enable_if_t = typename std::enable_if<B, T>::type; template<typename T> using uncvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type; // implementation of C++14 index_sequence and affiliates // source: https://stackoverflow.com/a/32223343 template<std::size_t... Ints> struct index_sequence { using type = index_sequence; using value_type = std::size_t; static constexpr std::size_t size() noexcept { return sizeof...(Ints); } }; template<class Sequence1, class Sequence2> struct merge_and_renumber; template<std::size_t... I1, std::size_t... I2> struct merge_and_renumber<index_sequence<I1...>, index_sequence<I2...>> : index_sequence < I1..., (sizeof...(I1) + I2)... > {}; template<std::size_t N> struct make_index_sequence : merge_and_renumber < typename make_index_sequence < N / 2 >::type, typename make_index_sequence < N - N / 2 >::type > {}; template<> struct make_index_sequence<0> : index_sequence<> {}; template<> struct make_index_sequence<1> : index_sequence<0> {}; template<typename... Ts> using index_sequence_for = make_index_sequence<sizeof...(Ts)>; // dispatch utility (taken from ranges-v3) template<unsigned N> struct priority_tag : priority_tag < N - 1 > {}; template<> struct priority_tag<0> {}; // taken from ranges-v3 template<typename T> struct static_const { static constexpr T value{}; }; template<typename T> constexpr T static_const<T>::value; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/meta/type_traits.hpp> #include <ciso646> // not #include <limits> // numeric_limits #include <type_traits> // false_type, is_constructible, is_integral, is_same, true_type #include <utility> // declval // #include <nlohmann/json_fwd.hpp> // #include <nlohmann/detail/iterators/iterator_traits.hpp> #include <iterator> // random_access_iterator_tag // #include <nlohmann/detail/meta/void_t.hpp> namespace nlohmann { namespace detail { template <typename ...Ts> struct make_void { using type = void; }; template <typename ...Ts> using void_t = typename make_void<Ts...>::type; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/meta/cpp_future.hpp> namespace nlohmann { namespace detail { template <typename It, typename = void> struct iterator_types {}; template <typename It> struct iterator_types < It, void_t<typename It::difference_type, typename It::value_type, typename It::pointer, typename It::reference, typename It::iterator_category >> { using difference_type = typename It::difference_type; using value_type = typename It::value_type; using pointer = typename It::pointer; using reference = typename It::reference; using iterator_category = typename It::iterator_category; }; // This is required as some compilers implement std::iterator_traits in a way that // doesn't work with SFINAE. See https://github.com/nlohmann/json/issues/1341. template <typename T, typename = void> struct iterator_traits { }; template <typename T> struct iterator_traits < T, enable_if_t < !std::is_pointer<T>::value >> : iterator_types<T> { }; template <typename T> struct iterator_traits<T*, enable_if_t<std::is_object<T>::value>> { using iterator_category = std::random_access_iterator_tag; using value_type = T; using difference_type = ptrdiff_t; using pointer = T*; using reference = T&; }; } } // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/detected.hpp> #include <type_traits> // #include <nlohmann/detail/meta/void_t.hpp> // http://en.cppreference.com/w/cpp/experimental/is_detected namespace nlohmann { namespace detail { struct nonesuch { nonesuch() = delete; ~nonesuch() = delete; nonesuch(nonesuch const&) = delete; void operator=(nonesuch const&) = delete; }; template <class Default, class AlwaysVoid, template <class...> class Op, class... Args> struct detector { using value_t = std::false_type; using type = Default; }; template <class Default, template <class...> class Op, class... Args> struct detector<Default, void_t<Op<Args...>>, Op, Args...> { using value_t = std::true_type; using type = Op<Args...>; }; template <template <class...> class Op, class... Args> using is_detected = typename detector<nonesuch, void, Op, Args...>::value_t; template <template <class...> class Op, class... Args> using detected_t = typename detector<nonesuch, void, Op, Args...>::type; template <class Default, template <class...> class Op, class... Args> using detected_or = detector<Default, void, Op, Args...>; template <class Default, template <class...> class Op, class... Args> using detected_or_t = typename detected_or<Default, Op, Args...>::type; template <class Expected, template <class...> class Op, class... Args> using is_detected_exact = std::is_same<Expected, detected_t<Op, Args...>>; template <class To, template <class...> class Op, class... Args> using is_detected_convertible = std::is_convertible<detected_t<Op, Args...>, To>; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { /*! @brief detail namespace with internal helper functions This namespace collects functions that should not be exposed, implementations of some @ref basic_json methods, and meta-programming helpers. @since version 2.1.0 */ namespace detail { ///////////// // helpers // ///////////// // Note to maintainers: // // Every trait in this file expects a non CV-qualified type. // The only exceptions are in the 'aliases for detected' section // (i.e. those of the form: decltype(T::member_function(std::declval<T>()))) // // In this case, T has to be properly CV-qualified to constraint the function arguments // (e.g. to_json(BasicJsonType&, const T&)) template<typename> struct is_basic_json : std::false_type {}; NLOHMANN_BASIC_JSON_TPL_DECLARATION struct is_basic_json<NLOHMANN_BASIC_JSON_TPL> : std::true_type {}; ////////////////////////// // aliases for detected // ////////////////////////// template <typename T> using mapped_type_t = typename T::mapped_type; template <typename T> using key_type_t = typename T::key_type; template <typename T> using value_type_t = typename T::value_type; template <typename T> using difference_type_t = typename T::difference_type; template <typename T> using pointer_t = typename T::pointer; template <typename T> using reference_t = typename T::reference; template <typename T> using iterator_category_t = typename T::iterator_category; template <typename T> using iterator_t = typename T::iterator; template <typename T, typename... Args> using to_json_function = decltype(T::to_json(std::declval<Args>()...)); template <typename T, typename... Args> using from_json_function = decltype(T::from_json(std::declval<Args>()...)); template <typename T, typename U> using get_template_function = decltype(std::declval<T>().template get<U>()); // trait checking if JSONSerializer<T>::from_json(json const&, udt&) exists template <typename BasicJsonType, typename T, typename = void> struct has_from_json : std::false_type {}; template <typename BasicJsonType, typename T> struct has_from_json<BasicJsonType, T, enable_if_t<!is_basic_json<T>::value>> { using serializer = typename BasicJsonType::template json_serializer<T, void>; static constexpr bool value = is_detected_exact<void, from_json_function, serializer, const BasicJsonType&, T&>::value; }; // This trait checks if JSONSerializer<T>::from_json(json const&) exists // this overload is used for non-default-constructible user-defined-types template <typename BasicJsonType, typename T, typename = void> struct has_non_default_from_json : std::false_type {}; template<typename BasicJsonType, typename T> struct has_non_default_from_json<BasicJsonType, T, enable_if_t<!is_basic_json<T>::value>> { using serializer = typename BasicJsonType::template json_serializer<T, void>; static constexpr bool value = is_detected_exact<T, from_json_function, serializer, const BasicJsonType&>::value; }; // This trait checks if BasicJsonType::json_serializer<T>::to_json exists // Do not evaluate the trait when T is a basic_json type, to avoid template instantiation infinite recursion. template <typename BasicJsonType, typename T, typename = void> struct has_to_json : std::false_type {}; template <typename BasicJsonType, typename T> struct has_to_json<BasicJsonType, T, enable_if_t<!is_basic_json<T>::value>> { using serializer = typename BasicJsonType::template json_serializer<T, void>; static constexpr bool value = is_detected_exact<void, to_json_function, serializer, BasicJsonType&, T>::value; }; /////////////////// // is_ functions // /////////////////// template <typename T, typename = void> struct is_iterator_traits : std::false_type {}; template <typename T> struct is_iterator_traits<iterator_traits<T>> { private: using traits = iterator_traits<T>; public: static constexpr auto value = is_detected<value_type_t, traits>::value && is_detected<difference_type_t, traits>::value && is_detected<pointer_t, traits>::value && is_detected<iterator_category_t, traits>::value && is_detected<reference_t, traits>::value; }; // source: https://stackoverflow.com/a/37193089/4116453 template <typename T, typename = void> struct is_complete_type : std::false_type {}; template <typename T> struct is_complete_type<T, decltype(void(sizeof(T)))> : std::true_type {}; template <typename BasicJsonType, typename CompatibleObjectType, typename = void> struct is_compatible_object_type_impl : std::false_type {}; template <typename BasicJsonType, typename CompatibleObjectType> struct is_compatible_object_type_impl < BasicJsonType, CompatibleObjectType, enable_if_t<is_detected<mapped_type_t, CompatibleObjectType>::value && is_detected<key_type_t, CompatibleObjectType>::value >> { using object_t = typename BasicJsonType::object_t; // macOS's is_constructible does not play well with nonesuch... static constexpr bool value = std::is_constructible<typename object_t::key_type, typename CompatibleObjectType::key_type>::value and std::is_constructible<typename object_t::mapped_type, typename CompatibleObjectType::mapped_type>::value; }; template <typename BasicJsonType, typename CompatibleObjectType> struct is_compatible_object_type : is_compatible_object_type_impl<BasicJsonType, CompatibleObjectType> {}; template <typename BasicJsonType, typename ConstructibleObjectType, typename = void> struct is_constructible_object_type_impl : std::false_type {}; template <typename BasicJsonType, typename ConstructibleObjectType> struct is_constructible_object_type_impl < BasicJsonType, ConstructibleObjectType, enable_if_t<is_detected<mapped_type_t, ConstructibleObjectType>::value && is_detected<key_type_t, ConstructibleObjectType>::value >> { using object_t = typename BasicJsonType::object_t; static constexpr bool value = (std::is_constructible<typename ConstructibleObjectType::key_type, typename object_t::key_type>::value and std::is_same<typename object_t::mapped_type, typename ConstructibleObjectType::mapped_type>::value) or (has_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type>::value or has_non_default_from_json<BasicJsonType, typename ConstructibleObjectType::mapped_type >::value); }; template <typename BasicJsonType, typename ConstructibleObjectType> struct is_constructible_object_type : is_constructible_object_type_impl<BasicJsonType, ConstructibleObjectType> {}; template <typename BasicJsonType, typename CompatibleStringType, typename = void> struct is_compatible_string_type_impl : std::false_type {}; template <typename BasicJsonType, typename CompatibleStringType> struct is_compatible_string_type_impl < BasicJsonType, CompatibleStringType, enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, CompatibleStringType>::value >> { static constexpr auto value = std::is_constructible<typename BasicJsonType::string_t, CompatibleStringType>::value; }; template <typename BasicJsonType, typename ConstructibleStringType> struct is_compatible_string_type : is_compatible_string_type_impl<BasicJsonType, ConstructibleStringType> {}; template <typename BasicJsonType, typename ConstructibleStringType, typename = void> struct is_constructible_string_type_impl : std::false_type {}; template <typename BasicJsonType, typename ConstructibleStringType> struct is_constructible_string_type_impl < BasicJsonType, ConstructibleStringType, enable_if_t<is_detected_exact<typename BasicJsonType::string_t::value_type, value_type_t, ConstructibleStringType>::value >> { static constexpr auto value = std::is_constructible<ConstructibleStringType, typename BasicJsonType::string_t>::value; }; template <typename BasicJsonType, typename ConstructibleStringType> struct is_constructible_string_type : is_constructible_string_type_impl<BasicJsonType, ConstructibleStringType> {}; template <typename BasicJsonType, typename CompatibleArrayType, typename = void> struct is_compatible_array_type_impl : std::false_type {}; template <typename BasicJsonType, typename CompatibleArrayType> struct is_compatible_array_type_impl < BasicJsonType, CompatibleArrayType, enable_if_t<is_detected<value_type_t, CompatibleArrayType>::value && is_detected<iterator_t, CompatibleArrayType>::value && // This is needed because json_reverse_iterator has a ::iterator type... // Therefore it is detected as a CompatibleArrayType. // The real fix would be to have an Iterable concept. !is_iterator_traits< iterator_traits<CompatibleArrayType>>::value >> { static constexpr bool value = std::is_constructible<BasicJsonType, typename CompatibleArrayType::value_type>::value; }; template <typename BasicJsonType, typename CompatibleArrayType> struct is_compatible_array_type : is_compatible_array_type_impl<BasicJsonType, CompatibleArrayType> {}; template <typename BasicJsonType, typename ConstructibleArrayType, typename = void> struct is_constructible_array_type_impl : std::false_type {}; template <typename BasicJsonType, typename ConstructibleArrayType> struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t<std::is_same<ConstructibleArrayType, typename BasicJsonType::value_type>::value >> : std::true_type {}; template <typename BasicJsonType, typename ConstructibleArrayType> struct is_constructible_array_type_impl < BasicJsonType, ConstructibleArrayType, enable_if_t<!std::is_same<ConstructibleArrayType, typename BasicJsonType::value_type>::value && is_detected<value_type_t, ConstructibleArrayType>::value && is_detected<iterator_t, ConstructibleArrayType>::value && is_complete_type< detected_t<value_type_t, ConstructibleArrayType>>::value >> { static constexpr bool value = // This is needed because json_reverse_iterator has a ::iterator type, // furthermore, std::back_insert_iterator (and other iterators) have a base class `iterator`... // Therefore it is detected as a ConstructibleArrayType. // The real fix would be to have an Iterable concept. ! is_iterator_traits < iterator_traits<ConstructibleArrayType >>::value && (std::is_same<typename ConstructibleArrayType::value_type, typename BasicJsonType::array_t::value_type>::value || has_from_json<BasicJsonType, typename ConstructibleArrayType::value_type>::value || has_non_default_from_json < BasicJsonType, typename ConstructibleArrayType::value_type >::value); }; template <typename BasicJsonType, typename ConstructibleArrayType> struct is_constructible_array_type : is_constructible_array_type_impl<BasicJsonType, ConstructibleArrayType> {}; template <typename RealIntegerType, typename CompatibleNumberIntegerType, typename = void> struct is_compatible_integer_type_impl : std::false_type {}; template <typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type_impl < RealIntegerType, CompatibleNumberIntegerType, enable_if_t<std::is_integral<RealIntegerType>::value and std::is_integral<CompatibleNumberIntegerType>::value and not std::is_same<bool, CompatibleNumberIntegerType>::value >> { // is there an assert somewhere on overflows? using RealLimits = std::numeric_limits<RealIntegerType>; using CompatibleLimits = std::numeric_limits<CompatibleNumberIntegerType>; static constexpr auto value = std::is_constructible<RealIntegerType, CompatibleNumberIntegerType>::value and CompatibleLimits::is_integer and RealLimits::is_signed == CompatibleLimits::is_signed; }; template <typename RealIntegerType, typename CompatibleNumberIntegerType> struct is_compatible_integer_type : is_compatible_integer_type_impl<RealIntegerType, CompatibleNumberIntegerType> {}; template <typename BasicJsonType, typename CompatibleType, typename = void> struct is_compatible_type_impl: std::false_type {}; template <typename BasicJsonType, typename CompatibleType> struct is_compatible_type_impl < BasicJsonType, CompatibleType, enable_if_t<is_complete_type<CompatibleType>::value >> { static constexpr bool value = has_to_json<BasicJsonType, CompatibleType>::value; }; template <typename BasicJsonType, typename CompatibleType> struct is_compatible_type : is_compatible_type_impl<BasicJsonType, CompatibleType> {}; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/exceptions.hpp> #include <exception> // exception #include <stdexcept> // runtime_error #include <string> // to_string // #include <nlohmann/detail/input/position_t.hpp> #include <cstddef> // size_t namespace nlohmann { namespace detail { /// struct to capture the start position of the current token struct position_t { /// the total number of characters read std::size_t chars_read_total = 0; /// the number of characters read in the current line std::size_t chars_read_current_line = 0; /// the number of lines read std::size_t lines_read = 0; /// conversion to size_t to preserve SAX interface constexpr operator size_t() const { return chars_read_total; } }; } } namespace nlohmann { namespace detail { //////////////// // exceptions // //////////////// /*! @brief general exception of the @ref basic_json class This class is an extension of `std::exception` objects with a member @a id for exception ids. It is used as the base class for all exceptions thrown by the @ref basic_json class. This class can hence be used as "wildcard" to catch exceptions. Subclasses: - @ref parse_error for exceptions indicating a parse error - @ref invalid_iterator for exceptions indicating errors with iterators - @ref type_error for exceptions indicating executing a member function with a wrong type - @ref out_of_range for exceptions indicating access out of the defined range - @ref other_error for exceptions indicating other library errors @internal @note To have nothrow-copy-constructible exceptions, we internally use `std::runtime_error` which can cope with arbitrary-length error messages. Intermediate strings are built with static functions and then passed to the actual constructor. @endinternal @liveexample{The following code shows how arbitrary library exceptions can be caught.,exception} @since version 3.0.0 */ class exception : public std::exception { public: /// returns the explanatory string const char* what() const noexcept override { return m.what(); } /// the id of the exception const int id; protected: exception(int id_, const char* what_arg) : id(id_), m(what_arg) {} static std::string name(const std::string& ename, int id_) { return "[json.exception." + ename + "." + std::to_string(id_) + "] "; } private: /// an exception object as storage for error messages std::runtime_error m; }; /*! @brief exception indicating a parse error This exception is thrown by the library when a parse error occurs. Parse errors can occur during the deserialization of JSON text, CBOR, MessagePack, as well as when using JSON Patch. Member @a byte holds the byte index of the last read character in the input file. Exceptions have ids 1xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.parse_error.101 | parse error at 2: unexpected end of input; expected string literal | This error indicates a syntax error while deserializing a JSON text. The error message describes that an unexpected token (character) was encountered, and the member @a byte indicates the error position. json.exception.parse_error.102 | parse error at 14: missing or wrong low surrogate | JSON uses the `\uxxxx` format to describe Unicode characters. Code points above above 0xFFFF are split into two `\uxxxx` entries ("surrogate pairs"). This error indicates that the surrogate pair is incomplete or contains an invalid code point. json.exception.parse_error.103 | parse error: code points above 0x10FFFF are invalid | Unicode supports code points up to 0x10FFFF. Code points above 0x10FFFF are invalid. json.exception.parse_error.104 | parse error: JSON patch must be an array of objects | [RFC 6902](https://tools.ietf.org/html/rfc6902) requires a JSON Patch document to be a JSON document that represents an array of objects. json.exception.parse_error.105 | parse error: operation must have string member 'op' | An operation of a JSON Patch document must contain exactly one "op" member, whose value indicates the operation to perform. Its value must be one of "add", "remove", "replace", "move", "copy", or "test"; other values are errors. json.exception.parse_error.106 | parse error: array index '01' must not begin with '0' | An array index in a JSON Pointer ([RFC 6901](https://tools.ietf.org/html/rfc6901)) may be `0` or any number without a leading `0`. json.exception.parse_error.107 | parse error: JSON pointer must be empty or begin with '/' - was: 'foo' | A JSON Pointer must be a Unicode string containing a sequence of zero or more reference tokens, each prefixed by a `/` character. json.exception.parse_error.108 | parse error: escape character '~' must be followed with '0' or '1' | In a JSON Pointer, only `~0` and `~1` are valid escape sequences. json.exception.parse_error.109 | parse error: array index 'one' is not a number | A JSON Pointer array index must be a number. json.exception.parse_error.110 | parse error at 1: cannot read 2 bytes from vector | When parsing CBOR or MessagePack, the byte vector ends before the complete value has been read. json.exception.parse_error.112 | parse error at 1: error reading CBOR; last byte: 0xF8 | Not all types of CBOR or MessagePack are supported. This exception occurs if an unsupported byte was read. json.exception.parse_error.113 | parse error at 2: expected a CBOR string; last byte: 0x98 | While parsing a map key, a value that is not a string has been read. json.exception.parse_error.114 | parse error: Unsupported BSON record type 0x0F | The parsing of the corresponding BSON record type is not implemented (yet). @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). @liveexample{The following code shows how a `parse_error` exception can be caught.,parse_error} @sa @ref exception for the base class of the library exceptions @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class parse_error : public exception { public: /*! @brief create a parse error exception @param[in] id_ the id of the exception @param[in] position the position where the error occurred (or with chars_read_total=0 if the position cannot be determined) @param[in] what_arg the explanatory string @return parse_error object */ static parse_error create(int id_, const position_t& pos, const std::string& what_arg) { std::string w = exception::name("parse_error", id_) + "parse error" + position_string(pos) + ": " + what_arg; return parse_error(id_, pos.chars_read_total, w.c_str()); } static parse_error create(int id_, std::size_t byte_, const std::string& what_arg) { std::string w = exception::name("parse_error", id_) + "parse error" + (byte_ != 0 ? (" at byte " + std::to_string(byte_)) : "") + ": " + what_arg; return parse_error(id_, byte_, w.c_str()); } /*! @brief byte index of the parse error The byte index of the last read character in the input file. @note For an input with n bytes, 1 is the index of the first character and n+1 is the index of the terminating null byte or the end of file. This also holds true when reading a byte vector (CBOR or MessagePack). */ const std::size_t byte; private: parse_error(int id_, std::size_t byte_, const char* what_arg) : exception(id_, what_arg), byte(byte_) {} static std::string position_string(const position_t& pos) { return " at line " + std::to_string(pos.lines_read + 1) + ", column " + std::to_string(pos.chars_read_current_line); } }; /*! @brief exception indicating errors with iterators This exception is thrown if iterators passed to a library function do not match the expected semantics. Exceptions have ids 2xx. name / id | example message | description ----------------------------------- | --------------- | ------------------------- json.exception.invalid_iterator.201 | iterators are not compatible | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.202 | iterator does not fit current value | In an erase or insert function, the passed iterator @a pos does not belong to the JSON value for which the function was called. It hence does not define a valid position for the deletion/insertion. json.exception.invalid_iterator.203 | iterators do not fit current value | Either iterator passed to function @ref erase(IteratorType first, IteratorType last) does not belong to the JSON value from which values shall be erased. It hence does not define a valid range to delete values from. json.exception.invalid_iterator.204 | iterators out of range | When an iterator range for a primitive type (number, boolean, or string) is passed to a constructor or an erase function, this range has to be exactly (@ref begin(), @ref end()), because this is the only way the single stored value is expressed. All other ranges are invalid. json.exception.invalid_iterator.205 | iterator out of range | When an iterator for a primitive type (number, boolean, or string) is passed to an erase function, the iterator has to be the @ref begin() iterator, because it is the only way to address the stored value. All other iterators are invalid. json.exception.invalid_iterator.206 | cannot construct with iterators from null | The iterators passed to constructor @ref basic_json(InputIT first, InputIT last) belong to a JSON null value and hence to not define a valid range. json.exception.invalid_iterator.207 | cannot use key() for non-object iterators | The key() member function can only be used on iterators belonging to a JSON object, because other types do not have a concept of a key. json.exception.invalid_iterator.208 | cannot use operator[] for object iterators | The operator[] to specify a concrete offset cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.209 | cannot use offsets with object iterators | The offset operators (+, -, +=, -=) cannot be used on iterators belonging to a JSON object, because JSON objects are unordered. json.exception.invalid_iterator.210 | iterators do not fit | The iterator range passed to the insert function are not compatible, meaning they do not belong to the same container. Therefore, the range (@a first, @a last) is invalid. json.exception.invalid_iterator.211 | passed iterators may not belong to container | The iterator range passed to the insert function must not be a subrange of the container to insert to. json.exception.invalid_iterator.212 | cannot compare iterators of different containers | When two iterators are compared, they must belong to the same container. json.exception.invalid_iterator.213 | cannot compare order of object iterators | The order of object iterators cannot be compared, because JSON objects are unordered. json.exception.invalid_iterator.214 | cannot get value | Cannot get value for iterator: Either the iterator belongs to a null value or it is an iterator to a primitive type (number, boolean, or string), but the iterator is different to @ref begin(). @liveexample{The following code shows how an `invalid_iterator` exception can be caught.,invalid_iterator} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class invalid_iterator : public exception { public: static invalid_iterator create(int id_, const std::string& what_arg) { std::string w = exception::name("invalid_iterator", id_) + what_arg; return invalid_iterator(id_, w.c_str()); } private: invalid_iterator(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating executing a member function with a wrong type This exception is thrown in case of a type error; that is, a library function is executed on a JSON value whose type does not match the expected semantics. Exceptions have ids 3xx. name / id | example message | description ----------------------------- | --------------- | ------------------------- json.exception.type_error.301 | cannot create object from initializer list | To create an object from an initializer list, the initializer list must consist only of a list of pairs whose first element is a string. When this constraint is violated, an array is created instead. json.exception.type_error.302 | type must be object, but is array | During implicit or explicit value conversion, the JSON type must be compatible to the target type. For instance, a JSON string can only be converted into string types, but not into numbers or boolean types. json.exception.type_error.303 | incompatible ReferenceType for get_ref, actual type is object | To retrieve a reference to a value stored in a @ref basic_json object with @ref get_ref, the type of the reference must match the value type. For instance, for a JSON array, the @a ReferenceType must be @ref array_t&. json.exception.type_error.304 | cannot use at() with string | The @ref at() member functions can only be executed for certain JSON types. json.exception.type_error.305 | cannot use operator[] with string | The @ref operator[] member functions can only be executed for certain JSON types. json.exception.type_error.306 | cannot use value() with string | The @ref value() member functions can only be executed for certain JSON types. json.exception.type_error.307 | cannot use erase() with string | The @ref erase() member functions can only be executed for certain JSON types. json.exception.type_error.308 | cannot use push_back() with string | The @ref push_back() and @ref operator+= member functions can only be executed for certain JSON types. json.exception.type_error.309 | cannot use insert() with | The @ref insert() member functions can only be executed for certain JSON types. json.exception.type_error.310 | cannot use swap() with number | The @ref swap() member functions can only be executed for certain JSON types. json.exception.type_error.311 | cannot use emplace_back() with string | The @ref emplace_back() member function can only be executed for certain JSON types. json.exception.type_error.312 | cannot use update() with string | The @ref update() member functions can only be executed for certain JSON types. json.exception.type_error.313 | invalid value to unflatten | The @ref unflatten function converts an object whose keys are JSON Pointers back into an arbitrary nested JSON value. The JSON Pointers must not overlap, because then the resulting value would not be well defined. json.exception.type_error.314 | only objects can be unflattened | The @ref unflatten function only works for an object whose keys are JSON Pointers. json.exception.type_error.315 | values in object must be primitive | The @ref unflatten function only works for an object whose keys are JSON Pointers and whose values are primitive. json.exception.type_error.316 | invalid UTF-8 byte at index 10: 0x7E | The @ref dump function only works with UTF-8 encoded strings; that is, if you assign a `std::string` to a JSON value, make sure it is UTF-8 encoded. | json.exception.type_error.317 | JSON value cannot be serialized to requested format | The dynamic type of the object cannot be represented in the requested serialization format (e.g. a raw `true` or `null` JSON object cannot be serialized to BSON) | @liveexample{The following code shows how a `type_error` exception can be caught.,type_error} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref out_of_range for exceptions indicating access out of the defined range @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class type_error : public exception { public: static type_error create(int id_, const std::string& what_arg) { std::string w = exception::name("type_error", id_) + what_arg; return type_error(id_, w.c_str()); } private: type_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating access out of the defined range This exception is thrown in case a library function is called on an input parameter that exceeds the expected range, for instance in case of array indices or nonexisting object keys. Exceptions have ids 4xx. name / id | example message | description ------------------------------- | --------------- | ------------------------- json.exception.out_of_range.401 | array index 3 is out of range | The provided array index @a i is larger than @a size-1. json.exception.out_of_range.402 | array index '-' (3) is out of range | The special array index `-` in a JSON Pointer never describes a valid element of the array, but the index past the end. That is, it can only be used to add elements at this position, but not to read it. json.exception.out_of_range.403 | key 'foo' not found | The provided key was not found in the JSON object. json.exception.out_of_range.404 | unresolved reference token 'foo' | A reference token in a JSON Pointer could not be resolved. json.exception.out_of_range.405 | JSON pointer has no parent | The JSON Patch operations 'remove' and 'add' can not be applied to the root element of the JSON value. json.exception.out_of_range.406 | number overflow parsing '10E1000' | A parsed number could not be stored as without changing it to NaN or INF. json.exception.out_of_range.407 | number overflow serializing '9223372036854775808' | UBJSON and BSON only support integer numbers up to 9223372036854775807. | json.exception.out_of_range.408 | excessive array size: 8658170730974374167 | The size (following `#`) of an UBJSON array or object exceeds the maximal capacity. | json.exception.out_of_range.409 | BSON key cannot contain code point U+0000 (at byte 2) | Key identifiers to be serialized to BSON cannot contain code point U+0000, since the key is stored as zero-terminated c-string | @liveexample{The following code shows how an `out_of_range` exception can be caught.,out_of_range} @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref other_error for exceptions indicating other library errors @since version 3.0.0 */ class out_of_range : public exception { public: static out_of_range create(int id_, const std::string& what_arg) { std::string w = exception::name("out_of_range", id_) + what_arg; return out_of_range(id_, w.c_str()); } private: out_of_range(int id_, const char* what_arg) : exception(id_, what_arg) {} }; /*! @brief exception indicating other library errors This exception is thrown in case of errors that cannot be classified with the other exception types. Exceptions have ids 5xx. name / id | example message | description ------------------------------ | --------------- | ------------------------- json.exception.other_error.501 | unsuccessful: {"op":"test","path":"/baz", "value":"bar"} | A JSON Patch operation 'test' failed. The unsuccessful operation is also printed. @sa @ref exception for the base class of the library exceptions @sa @ref parse_error for exceptions indicating a parse error @sa @ref invalid_iterator for exceptions indicating errors with iterators @sa @ref type_error for exceptions indicating executing a member function with a wrong type @sa @ref out_of_range for exceptions indicating access out of the defined range @liveexample{The following code shows how an `other_error` exception can be caught.,other_error} @since version 3.0.0 */ class other_error : public exception { public: static other_error create(int id_, const std::string& what_arg) { std::string w = exception::name("other_error", id_) + what_arg; return other_error(id_, w.c_str()); } private: other_error(int id_, const char* what_arg) : exception(id_, what_arg) {} }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/value_t.hpp> #include <array> // array #include <ciso646> // and #include <cstddef> // size_t #include <cstdint> // uint8_t namespace nlohmann { namespace detail { /////////////////////////// // JSON type enumeration // /////////////////////////// /*! @brief the JSON type enumeration This enumeration collects the different JSON types. It is internally used to distinguish the stored values, and the functions @ref basic_json::is_null(), @ref basic_json::is_object(), @ref basic_json::is_array(), @ref basic_json::is_string(), @ref basic_json::is_boolean(), @ref basic_json::is_number() (with @ref basic_json::is_number_integer(), @ref basic_json::is_number_unsigned(), and @ref basic_json::is_number_float()), @ref basic_json::is_discarded(), @ref basic_json::is_primitive(), and @ref basic_json::is_structured() rely on it. @note There are three enumeration entries (number_integer, number_unsigned, and number_float), because the library distinguishes these three types for numbers: @ref basic_json::number_unsigned_t is used for unsigned integers, @ref basic_json::number_integer_t is used for signed integers, and @ref basic_json::number_float_t is used for floating-point numbers or to approximate integers which do not fit in the limits of their respective type. @sa @ref basic_json::basic_json(const value_t value_type) -- create a JSON value with the default value for a given type @since version 1.0.0 */ enum class value_t : std::uint8_t { null, ///< null value object, ///< object (unordered set of name/value pairs) array, ///< array (ordered collection of values) string, ///< string value boolean, ///< boolean value number_integer, ///< number value (signed integer) number_unsigned, ///< number value (unsigned integer) number_float, ///< number value (floating-point) discarded ///< discarded by the the parser callback function }; /*! @brief comparison operator for JSON types Returns an ordering that is similar to Python: - order: null < boolean < number < object < array < string - furthermore, each type is not smaller than itself - discarded values are not comparable @since version 1.0.0 */ inline bool operator<(const value_t lhs, const value_t rhs) noexcept { static constexpr std::array<std::uint8_t, 8> order = {{ 0 /* null */, 3 /* object */, 4 /* array */, 5 /* string */, 1 /* boolean */, 2 /* integer */, 2 /* unsigned */, 2 /* float */ } }; const auto l_index = static_cast<std::size_t>(lhs); const auto r_index = static_cast<std::size_t>(rhs); return l_index < order.size() and r_index < order.size() and order[l_index] < order[r_index]; } } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/conversions/from_json.hpp> #include <algorithm> // transform #include <array> // array #include <ciso646> // and, not #include <forward_list> // forward_list #include <iterator> // inserter, front_inserter, end #include <map> // map #include <string> // string #include <tuple> // tuple, make_tuple #include <type_traits> // is_arithmetic, is_same, is_enum, underlying_type, is_convertible #include <unordered_map> // unordered_map #include <utility> // pair, declval #include <valarray> // valarray // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename std::nullptr_t& n) { if (JSON_UNLIKELY(not j.is_null())) { JSON_THROW(type_error::create(302, "type must be null, but is " + std::string(j.type_name()))); } n = nullptr; } // overloads for basic_json template parameters template<typename BasicJsonType, typename ArithmeticType, enable_if_t<std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void get_arithmetic_value(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::boolean_t& b) { if (JSON_UNLIKELY(not j.is_boolean())) { JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(j.type_name()))); } b = *j.template get_ptr<const typename BasicJsonType::boolean_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::string_t& s) { if (JSON_UNLIKELY(not j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); } s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); } template < typename BasicJsonType, typename ConstructibleStringType, enable_if_t < is_constructible_string_type<BasicJsonType, ConstructibleStringType>::value and not std::is_same<typename BasicJsonType::string_t, ConstructibleStringType>::value, int > = 0 > void from_json(const BasicJsonType& j, ConstructibleStringType& s) { if (JSON_UNLIKELY(not j.is_string())) { JSON_THROW(type_error::create(302, "type must be string, but is " + std::string(j.type_name()))); } s = *j.template get_ptr<const typename BasicJsonType::string_t*>(); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_float_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_unsigned_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType> void from_json(const BasicJsonType& j, typename BasicJsonType::number_integer_t& val) { get_arithmetic_value(j, val); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void from_json(const BasicJsonType& j, EnumType& e) { typename std::underlying_type<EnumType>::type val; get_arithmetic_value(j, val); e = static_cast<EnumType>(val); } // forward_list doesn't have an insert method template<typename BasicJsonType, typename T, typename Allocator, enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::forward_list<T, Allocator>& l) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } std::transform(j.rbegin(), j.rend(), std::front_inserter(l), [](const BasicJsonType & i) { return i.template get<T>(); }); } // valarray doesn't have an insert method template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<BasicJsonType, T>::value, int> = 0> void from_json(const BasicJsonType& j, std::valarray<T>& l) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } l.resize(j.size()); std::copy(j.m_value.array->begin(), j.m_value.array->end(), std::begin(l)); } template<typename BasicJsonType> void from_json_array_impl(const BasicJsonType& j, typename BasicJsonType::array_t& arr, priority_tag<3> /*unused*/) { arr = *j.template get_ptr<const typename BasicJsonType::array_t*>(); } template <typename BasicJsonType, typename T, std::size_t N> auto from_json_array_impl(const BasicJsonType& j, std::array<T, N>& arr, priority_tag<2> /*unused*/) -> decltype(j.template get<T>(), void()) { for (std::size_t i = 0; i < N; ++i) { arr[i] = j.at(i).template get<T>(); } } template<typename BasicJsonType, typename ConstructibleArrayType> auto from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<1> /*unused*/) -> decltype( arr.reserve(std::declval<typename ConstructibleArrayType::size_type>()), j.template get<typename ConstructibleArrayType::value_type>(), void()) { using std::end; arr.reserve(j.size()); std::transform(j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename ConstructibleArrayType::value_type>(); }); } template <typename BasicJsonType, typename ConstructibleArrayType> void from_json_array_impl(const BasicJsonType& j, ConstructibleArrayType& arr, priority_tag<0> /*unused*/) { using std::end; std::transform( j.begin(), j.end(), std::inserter(arr, end(arr)), [](const BasicJsonType & i) { // get<BasicJsonType>() returns *this, this won't call a from_json // method when value_type is BasicJsonType return i.template get<typename ConstructibleArrayType::value_type>(); }); } template <typename BasicJsonType, typename ConstructibleArrayType, enable_if_t < is_constructible_array_type<BasicJsonType, ConstructibleArrayType>::value and not is_constructible_object_type<BasicJsonType, ConstructibleArrayType>::value and not is_constructible_string_type<BasicJsonType, ConstructibleArrayType>::value and not is_basic_json<ConstructibleArrayType>::value, int > = 0 > auto from_json(const BasicJsonType& j, ConstructibleArrayType& arr) -> decltype(from_json_array_impl(j, arr, priority_tag<3> {}), j.template get<typename ConstructibleArrayType::value_type>(), void()) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } from_json_array_impl(j, arr, priority_tag<3> {}); } template<typename BasicJsonType, typename ConstructibleObjectType, enable_if_t<is_constructible_object_type<BasicJsonType, ConstructibleObjectType>::value, int> = 0> void from_json(const BasicJsonType& j, ConstructibleObjectType& obj) { if (JSON_UNLIKELY(not j.is_object())) { JSON_THROW(type_error::create(302, "type must be object, but is " + std::string(j.type_name()))); } auto inner_object = j.template get_ptr<const typename BasicJsonType::object_t*>(); using value_type = typename ConstructibleObjectType::value_type; std::transform( inner_object->begin(), inner_object->end(), std::inserter(obj, obj.begin()), [](typename BasicJsonType::object_t::value_type const & p) { return value_type(p.first, p.second.template get<typename ConstructibleObjectType::mapped_type>()); }); } // overload for arithmetic types, not chosen for basic_json template arguments // (BooleanType, etc..); note: Is it really necessary to provide explicit // overloads for boolean_t etc. in case of a custom BooleanType which is not // an arithmetic type? template<typename BasicJsonType, typename ArithmeticType, enable_if_t < std::is_arithmetic<ArithmeticType>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_unsigned_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_integer_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::number_float_t>::value and not std::is_same<ArithmeticType, typename BasicJsonType::boolean_t>::value, int> = 0> void from_json(const BasicJsonType& j, ArithmeticType& val) { switch (static_cast<value_t>(j)) { case value_t::number_unsigned: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_unsigned_t*>()); break; } case value_t::number_integer: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_integer_t*>()); break; } case value_t::number_float: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::number_float_t*>()); break; } case value_t::boolean: { val = static_cast<ArithmeticType>(*j.template get_ptr<const typename BasicJsonType::boolean_t*>()); break; } default: JSON_THROW(type_error::create(302, "type must be number, but is " + std::string(j.type_name()))); } } template<typename BasicJsonType, typename A1, typename A2> void from_json(const BasicJsonType& j, std::pair<A1, A2>& p) { p = {j.at(0).template get<A1>(), j.at(1).template get<A2>()}; } template<typename BasicJsonType, typename Tuple, std::size_t... Idx> void from_json_tuple_impl(const BasicJsonType& j, Tuple& t, index_sequence<Idx...> /*unused*/) { t = std::make_tuple(j.at(Idx).template get<typename std::tuple_element<Idx, Tuple>::type>()...); } template<typename BasicJsonType, typename... Args> void from_json(const BasicJsonType& j, std::tuple<Args...>& t) { from_json_tuple_impl(j, t, index_sequence_for<Args...> {}); } template <typename BasicJsonType, typename Key, typename Value, typename Compare, typename Allocator, typename = enable_if_t<not std::is_constructible< typename BasicJsonType::string_t, Key>::value>> void from_json(const BasicJsonType& j, std::map<Key, Value, Compare, Allocator>& m) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } for (const auto& p : j) { if (JSON_UNLIKELY(not p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); } m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>()); } } template <typename BasicJsonType, typename Key, typename Value, typename Hash, typename KeyEqual, typename Allocator, typename = enable_if_t<not std::is_constructible< typename BasicJsonType::string_t, Key>::value>> void from_json(const BasicJsonType& j, std::unordered_map<Key, Value, Hash, KeyEqual, Allocator>& m) { if (JSON_UNLIKELY(not j.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(j.type_name()))); } for (const auto& p : j) { if (JSON_UNLIKELY(not p.is_array())) { JSON_THROW(type_error::create(302, "type must be array, but is " + std::string(p.type_name()))); } m.emplace(p.at(0).template get<Key>(), p.at(1).template get<Value>()); } } struct from_json_fn { template<typename BasicJsonType, typename T> auto operator()(const BasicJsonType& j, T& val) const noexcept(noexcept(from_json(j, val))) -> decltype(from_json(j, val), void()) { return from_json(j, val); } }; } // namespace detail /// namespace to hold default `from_json` function /// to see why this is required: /// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2015/n4381.html namespace { constexpr const auto& from_json = detail::static_const<detail::from_json_fn>::value; } // namespace } // namespace nlohmann // #include <nlohmann/detail/conversions/to_json.hpp> #include <ciso646> // or, and, not #include <iterator> // begin, end #include <tuple> // tuple, get #include <type_traits> // is_same, is_constructible, is_floating_point, is_enum, underlying_type #include <utility> // move, forward, declval, pair #include <valarray> // valarray #include <vector> // vector // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> // #include <nlohmann/detail/value_t.hpp> // #include <nlohmann/detail/iterators/iteration_proxy.hpp> #include <cstddef> // size_t #include <string> // string, to_string #include <iterator> // input_iterator_tag #include <tuple> // tuple_size, get, tuple_element // #include <nlohmann/detail/value_t.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> namespace nlohmann { namespace detail { template <typename IteratorType> class iteration_proxy_value { public: using difference_type = std::ptrdiff_t; using value_type = iteration_proxy_value; using pointer = value_type * ; using reference = value_type & ; using iterator_category = std::input_iterator_tag; private: /// the iterator IteratorType anchor; /// an index for arrays (used to create key names) std::size_t array_index = 0; /// last stringified array index mutable std::size_t array_index_last = 0; /// a string representation of the array index mutable std::string array_index_str = "0"; /// an empty string (to return a reference for primitive values) const std::string empty_str = ""; public: explicit iteration_proxy_value(IteratorType it) noexcept : anchor(it) {} /// dereference operator (needed for range-based for) iteration_proxy_value& operator*() { return *this; } /// increment operator (needed for range-based for) iteration_proxy_value& operator++() { ++anchor; ++array_index; return *this; } /// equality operator (needed for InputIterator) bool operator==(const iteration_proxy_value& o) const { return anchor == o.anchor; } /// inequality operator (needed for range-based for) bool operator!=(const iteration_proxy_value& o) const { return anchor != o.anchor; } /// return key of the iterator const std::string& key() const { assert(anchor.m_object != nullptr); switch (anchor.m_object->type()) { // use integer array index as key case value_t::array: { if (array_index != array_index_last) { array_index_str = std::to_string(array_index); array_index_last = array_index; } return array_index_str; } // use key from the object case value_t::object: return anchor.key(); // use an empty key for all primitive types default: return empty_str; } } /// return value of the iterator typename IteratorType::reference value() const { return anchor.value(); } }; /// proxy class for the items() function template<typename IteratorType> class iteration_proxy { private: /// the container to iterate typename IteratorType::reference container; public: /// construct iteration proxy from a container explicit iteration_proxy(typename IteratorType::reference cont) noexcept : container(cont) {} /// return iterator begin (needed for range-based for) iteration_proxy_value<IteratorType> begin() noexcept { return iteration_proxy_value<IteratorType>(container.begin()); } /// return iterator end (needed for range-based for) iteration_proxy_value<IteratorType> end() noexcept { return iteration_proxy_value<IteratorType>(container.end()); } }; // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template <std::size_t N, typename IteratorType, enable_if_t<N == 0, int> = 0> auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.key()) { return i.key(); } // Structured Bindings Support // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 template <std::size_t N, typename IteratorType, enable_if_t<N == 1, int> = 0> auto get(const nlohmann::detail::iteration_proxy_value<IteratorType>& i) -> decltype(i.value()) { return i.value(); } } // namespace detail } // namespace nlohmann // The Addition to the STD Namespace is required to add // Structured Bindings Support to the iteration_proxy_value class // For further reference see https://blog.tartanllama.xyz/structured-bindings/ // And see https://github.com/nlohmann/json/pull/1391 namespace std { template <typename IteratorType> class tuple_size<::nlohmann::detail::iteration_proxy_value<IteratorType>> : public std::integral_constant<std::size_t, 2> {}; template <std::size_t N, typename IteratorType> class tuple_element<N, ::nlohmann::detail::iteration_proxy_value<IteratorType >> { public: using type = decltype( get<N>(std::declval < ::nlohmann::detail::iteration_proxy_value<IteratorType >> ())); }; } namespace nlohmann { namespace detail { ////////////////// // constructors // ////////////////// template<value_t> struct external_constructor; template<> struct external_constructor<value_t::boolean> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::boolean_t b) noexcept { j.m_type = value_t::boolean; j.m_value = b; j.assert_invariant(); } }; template<> struct external_constructor<value_t::string> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::string_t& s) { j.m_type = value_t::string; j.m_value = s; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::string_t&& s) { j.m_type = value_t::string; j.m_value = std::move(s); j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleStringType, enable_if_t<not std::is_same<CompatibleStringType, typename BasicJsonType::string_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleStringType& str) { j.m_type = value_t::string; j.m_value.string = j.template create<typename BasicJsonType::string_t>(str); j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_float> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_float_t val) noexcept { j.m_type = value_t::number_float; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_unsigned> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_unsigned_t val) noexcept { j.m_type = value_t::number_unsigned; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::number_integer> { template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::number_integer_t val) noexcept { j.m_type = value_t::number_integer; j.m_value = val; j.assert_invariant(); } }; template<> struct external_constructor<value_t::array> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::array_t& arr) { j.m_type = value_t::array; j.m_value = arr; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { j.m_type = value_t::array; j.m_value = std::move(arr); j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleArrayType, enable_if_t<not std::is_same<CompatibleArrayType, typename BasicJsonType::array_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleArrayType& arr) { using std::begin; using std::end; j.m_type = value_t::array; j.m_value.array = j.template create<typename BasicJsonType::array_t>(begin(arr), end(arr)); j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, const std::vector<bool>& arr) { j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->reserve(arr.size()); for (const bool x : arr) { j.m_value.array->push_back(x); } j.assert_invariant(); } template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> static void construct(BasicJsonType& j, const std::valarray<T>& arr) { j.m_type = value_t::array; j.m_value = value_t::array; j.m_value.array->resize(arr.size()); std::copy(std::begin(arr), std::end(arr), j.m_value.array->begin()); j.assert_invariant(); } }; template<> struct external_constructor<value_t::object> { template<typename BasicJsonType> static void construct(BasicJsonType& j, const typename BasicJsonType::object_t& obj) { j.m_type = value_t::object; j.m_value = obj; j.assert_invariant(); } template<typename BasicJsonType> static void construct(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { j.m_type = value_t::object; j.m_value = std::move(obj); j.assert_invariant(); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<not std::is_same<CompatibleObjectType, typename BasicJsonType::object_t>::value, int> = 0> static void construct(BasicJsonType& j, const CompatibleObjectType& obj) { using std::begin; using std::end; j.m_type = value_t::object; j.m_value.object = j.template create<typename BasicJsonType::object_t>(begin(obj), end(obj)); j.assert_invariant(); } }; ///////////// // to_json // ///////////// template<typename BasicJsonType, typename T, enable_if_t<std::is_same<T, typename BasicJsonType::boolean_t>::value, int> = 0> void to_json(BasicJsonType& j, T b) noexcept { external_constructor<value_t::boolean>::construct(j, b); } template<typename BasicJsonType, typename CompatibleString, enable_if_t<std::is_constructible<typename BasicJsonType::string_t, CompatibleString>::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleString& s) { external_constructor<value_t::string>::construct(j, s); } template<typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::string_t&& s) { external_constructor<value_t::string>::construct(j, std::move(s)); } template<typename BasicJsonType, typename FloatType, enable_if_t<std::is_floating_point<FloatType>::value, int> = 0> void to_json(BasicJsonType& j, FloatType val) noexcept { external_constructor<value_t::number_float>::construct(j, static_cast<typename BasicJsonType::number_float_t>(val)); } template<typename BasicJsonType, typename CompatibleNumberUnsignedType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_unsigned_t, CompatibleNumberUnsignedType>::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberUnsignedType val) noexcept { external_constructor<value_t::number_unsigned>::construct(j, static_cast<typename BasicJsonType::number_unsigned_t>(val)); } template<typename BasicJsonType, typename CompatibleNumberIntegerType, enable_if_t<is_compatible_integer_type<typename BasicJsonType::number_integer_t, CompatibleNumberIntegerType>::value, int> = 0> void to_json(BasicJsonType& j, CompatibleNumberIntegerType val) noexcept { external_constructor<value_t::number_integer>::construct(j, static_cast<typename BasicJsonType::number_integer_t>(val)); } template<typename BasicJsonType, typename EnumType, enable_if_t<std::is_enum<EnumType>::value, int> = 0> void to_json(BasicJsonType& j, EnumType e) noexcept { using underlying_type = typename std::underlying_type<EnumType>::type; external_constructor<value_t::number_integer>::construct(j, static_cast<underlying_type>(e)); } template<typename BasicJsonType> void to_json(BasicJsonType& j, const std::vector<bool>& e) { external_constructor<value_t::array>::construct(j, e); } template <typename BasicJsonType, typename CompatibleArrayType, enable_if_t<is_compatible_array_type<BasicJsonType, CompatibleArrayType>::value and not is_compatible_object_type< BasicJsonType, CompatibleArrayType>::value and not is_compatible_string_type<BasicJsonType, CompatibleArrayType>::value and not is_basic_json<CompatibleArrayType>::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleArrayType& arr) { external_constructor<value_t::array>::construct(j, arr); } template<typename BasicJsonType, typename T, enable_if_t<std::is_convertible<T, BasicJsonType>::value, int> = 0> void to_json(BasicJsonType& j, const std::valarray<T>& arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template<typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::array_t&& arr) { external_constructor<value_t::array>::construct(j, std::move(arr)); } template<typename BasicJsonType, typename CompatibleObjectType, enable_if_t<is_compatible_object_type<BasicJsonType, CompatibleObjectType>::value and not is_basic_json<CompatibleObjectType>::value, int> = 0> void to_json(BasicJsonType& j, const CompatibleObjectType& obj) { external_constructor<value_t::object>::construct(j, obj); } template<typename BasicJsonType> void to_json(BasicJsonType& j, typename BasicJsonType::object_t&& obj) { external_constructor<value_t::object>::construct(j, std::move(obj)); } template < typename BasicJsonType, typename T, std::size_t N, enable_if_t<not std::is_constructible<typename BasicJsonType::string_t, const T(&)[N]>::value, int> = 0 > void to_json(BasicJsonType& j, const T(&arr)[N]) { external_constructor<value_t::array>::construct(j, arr); } template<typename BasicJsonType, typename... Args> void to_json(BasicJsonType& j, const std::pair<Args...>& p) { j = { p.first, p.second }; } // for https://github.com/nlohmann/json/pull/1134 template < typename BasicJsonType, typename T, enable_if_t<std::is_same<T, iteration_proxy_value<typename BasicJsonType::iterator>>::value, int> = 0> void to_json(BasicJsonType& j, const T& b) { j = { {b.key(), b.value()} }; } template<typename BasicJsonType, typename Tuple, std::size_t... Idx> void to_json_tuple_impl(BasicJsonType& j, const Tuple& t, index_sequence<Idx...> /*unused*/) { j = { std::get<Idx>(t)... }; } template<typename BasicJsonType, typename... Args> void to_json(BasicJsonType& j, const std::tuple<Args...>& t) { to_json_tuple_impl(j, t, index_sequence_for<Args...> {}); } struct to_json_fn { template<typename BasicJsonType, typename T> auto operator()(BasicJsonType& j, T&& val) const noexcept(noexcept(to_json(j, std::forward<T>(val)))) -> decltype(to_json(j, std::forward<T>(val)), void()) { return to_json(j, std::forward<T>(val)); } }; } // namespace detail /// namespace to hold default `to_json` function namespace { constexpr const auto& to_json = detail::static_const<detail::to_json_fn>::value; } // namespace } // namespace nlohmann // #include <nlohmann/detail/input/input_adapters.hpp> #include <cassert> // assert #include <cstddef> // size_t #include <cstring> // strlen #include <istream> // istream #include <iterator> // begin, end, iterator_traits, random_access_iterator_tag, distance, next #include <memory> // shared_ptr, make_shared, addressof #include <numeric> // accumulate #include <string> // string, char_traits #include <type_traits> // enable_if, is_base_of, is_pointer, is_integral, remove_pointer #include <utility> // pair, declval #include <cstdio> //FILE * // #include <nlohmann/detail/iterators/iterator_traits.hpp> // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { namespace detail { /// the supported input formats enum class input_format_t { json, cbor, msgpack, ubjson, bson }; //////////////////// // input adapters // //////////////////// /*! @brief abstract input adapter interface Produces a stream of std::char_traits<char>::int_type characters from a std::istream, a buffer, or some other input type. Accepts the return of exactly one non-EOF character for future input. The int_type characters returned consist of all valid char values as positive values (typically unsigned char), plus an EOF value outside that range, specified by the value of the function std::char_traits<char>::eof(). This value is typically -1, but could be any arbitrary value which is not a valid char value. */ struct input_adapter_protocol { /// get a character [0,255] or std::char_traits<char>::eof(). virtual std::char_traits<char>::int_type get_character() = 0; virtual ~input_adapter_protocol() = default; }; /// a type to simplify interfaces using input_adapter_t = std::shared_ptr<input_adapter_protocol>; /*! Input adapter for stdio file access. This adapter read only 1 byte and do not use any buffer. This adapter is a very low level adapter. */ class file_input_adapter : public input_adapter_protocol { public: explicit file_input_adapter(std::FILE* f) noexcept : m_file(f) {} std::char_traits<char>::int_type get_character() noexcept override { return std::fgetc(m_file); } private: /// the file pointer to read from std::FILE* m_file; }; /*! Input adapter for a (caching) istream. Ignores a UFT Byte Order Mark at beginning of input. Does not support changing the underlying std::streambuf in mid-input. Maintains underlying std::istream and std::streambuf to support subsequent use of standard std::istream operations to process any input characters following those used in parsing the JSON input. Clears the std::istream flags; any input errors (e.g., EOF) will be detected by the first subsequent call for input from the std::istream. */ class input_stream_adapter : public input_adapter_protocol { public: ~input_stream_adapter() override { // clear stream flags; we use underlying streambuf I/O, do not // maintain ifstream flags, except eof is.clear(is.rdstate() & std::ios::eofbit); } explicit input_stream_adapter(std::istream& i) : is(i), sb(*i.rdbuf()) {} // delete because of pointer members input_stream_adapter(const input_stream_adapter&) = delete; input_stream_adapter& operator=(input_stream_adapter&) = delete; input_stream_adapter(input_stream_adapter&&) = delete; input_stream_adapter& operator=(input_stream_adapter&&) = delete; // std::istream/std::streambuf use std::char_traits<char>::to_int_type, to // ensure that std::char_traits<char>::eof() and the character 0xFF do not // end up as the same value, eg. 0xFFFFFFFF. std::char_traits<char>::int_type get_character() override { auto res = sb.sbumpc(); // set eof manually, as we don't use the istream interface. if (res == EOF) { is.clear(is.rdstate() | std::ios::eofbit); } return res; } private: /// the associated input stream std::istream& is; std::streambuf& sb; }; /// input adapter for buffer input class input_buffer_adapter : public input_adapter_protocol { public: input_buffer_adapter(const char* b, const std::size_t l) noexcept : cursor(b), limit(b + l) {} // delete because of pointer members input_buffer_adapter(const input_buffer_adapter&) = delete; input_buffer_adapter& operator=(input_buffer_adapter&) = delete; input_buffer_adapter(input_buffer_adapter&&) = delete; input_buffer_adapter& operator=(input_buffer_adapter&&) = delete; ~input_buffer_adapter() override = default; std::char_traits<char>::int_type get_character() noexcept override { if (JSON_LIKELY(cursor < limit)) { return std::char_traits<char>::to_int_type(*(cursor++)); } return std::char_traits<char>::eof(); } private: /// pointer to the current character const char* cursor; /// pointer past the last character const char* const limit; }; template<typename WideStringType, size_t T> struct wide_string_input_helper { // UTF-32 static void fill_buffer(const WideStringType& str, size_t& current_wchar, std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (current_wchar == str.size()) { utf8_bytes[0] = std::char_traits<char>::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = static_cast<int>(str[current_wchar++]); // UTF-32 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = wc; utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = 0xC0 | ((wc >> 6) & 0x1F); utf8_bytes[1] = 0x80 | (wc & 0x3F); utf8_bytes_filled = 2; } else if (wc <= 0xFFFF) { utf8_bytes[0] = 0xE0 | ((wc >> 12) & 0x0F); utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F); utf8_bytes[2] = 0x80 | (wc & 0x3F); utf8_bytes_filled = 3; } else if (wc <= 0x10FFFF) { utf8_bytes[0] = 0xF0 | ((wc >> 18) & 0x07); utf8_bytes[1] = 0x80 | ((wc >> 12) & 0x3F); utf8_bytes[2] = 0x80 | ((wc >> 6) & 0x3F); utf8_bytes[3] = 0x80 | (wc & 0x3F); utf8_bytes_filled = 4; } else { // unknown character utf8_bytes[0] = wc; utf8_bytes_filled = 1; } } } }; template<typename WideStringType> struct wide_string_input_helper<WideStringType, 2> { // UTF-16 static void fill_buffer(const WideStringType& str, size_t& current_wchar, std::array<std::char_traits<char>::int_type, 4>& utf8_bytes, size_t& utf8_bytes_index, size_t& utf8_bytes_filled) { utf8_bytes_index = 0; if (current_wchar == str.size()) { utf8_bytes[0] = std::char_traits<char>::eof(); utf8_bytes_filled = 1; } else { // get the current character const auto wc = static_cast<int>(str[current_wchar++]); // UTF-16 to UTF-8 encoding if (wc < 0x80) { utf8_bytes[0] = wc; utf8_bytes_filled = 1; } else if (wc <= 0x7FF) { utf8_bytes[0] = 0xC0 | ((wc >> 6)); utf8_bytes[1] = 0x80 | (wc & 0x3F); utf8_bytes_filled = 2; } else if (0xD800 > wc || wc >= 0xE000) { utf8_bytes[0] = 0xE0 | ((wc >> 12)); utf8_bytes[1] = 0x80 | ((wc >> 6) & 0x3F); utf8_bytes[2] = 0x80 | (wc & 0x3F); utf8_bytes_filled = 3; } else { if (current_wchar < str.size()) { const auto wc2 = static_cast<int>(str[current_wchar++]); const int charcode = 0x10000 + (((wc & 0x3FF) << 10) | (wc2 & 0x3FF)); utf8_bytes[0] = 0xf0 | (charcode >> 18); utf8_bytes[1] = 0x80 | ((charcode >> 12) & 0x3F); utf8_bytes[2] = 0x80 | ((charcode >> 6) & 0x3F); utf8_bytes[3] = 0x80 | (charcode & 0x3F); utf8_bytes_filled = 4; } else { // unknown character ++current_wchar; utf8_bytes[0] = wc; utf8_bytes_filled = 1; } } } } }; template<typename WideStringType> class wide_string_input_adapter : public input_adapter_protocol { public: explicit wide_string_input_adapter(const WideStringType& w) noexcept : str(w) {} std::char_traits<char>::int_type get_character() noexcept override { // check if buffer needs to be filled if (utf8_bytes_index == utf8_bytes_filled) { fill_buffer<sizeof(typename WideStringType::value_type)>(); assert(utf8_bytes_filled > 0); assert(utf8_bytes_index == 0); } // use buffer assert(utf8_bytes_filled > 0); assert(utf8_bytes_index < utf8_bytes_filled); return utf8_bytes[utf8_bytes_index++]; } private: template<size_t T> void fill_buffer() { wide_string_input_helper<WideStringType, T>::fill_buffer(str, current_wchar, utf8_bytes, utf8_bytes_index, utf8_bytes_filled); } /// the wstring to process const WideStringType& str; /// index of the current wchar in str std::size_t current_wchar = 0; /// a buffer for UTF-8 bytes std::array<std::char_traits<char>::int_type, 4> utf8_bytes = {{0, 0, 0, 0}}; /// index to the utf8_codes array for the next valid byte std::size_t utf8_bytes_index = 0; /// number of valid bytes in the utf8_codes array std::size_t utf8_bytes_filled = 0; }; class input_adapter { public: // native support input_adapter(std::FILE* file) : ia(std::make_shared<file_input_adapter>(file)) {} /// input adapter for input stream input_adapter(std::istream& i) : ia(std::make_shared<input_stream_adapter>(i)) {} /// input adapter for input stream input_adapter(std::istream&& i) : ia(std::make_shared<input_stream_adapter>(i)) {} input_adapter(const std::wstring& ws) : ia(std::make_shared<wide_string_input_adapter<std::wstring>>(ws)) {} input_adapter(const std::u16string& ws) : ia(std::make_shared<wide_string_input_adapter<std::u16string>>(ws)) {} input_adapter(const std::u32string& ws) : ia(std::make_shared<wide_string_input_adapter<std::u32string>>(ws)) {} /// input adapter for buffer template<typename CharT, typename std::enable_if< std::is_pointer<CharT>::value and std::is_integral<typename std::remove_pointer<CharT>::type>::value and sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> input_adapter(CharT b, std::size_t l) : ia(std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(b), l)) {} // derived support /// input adapter for string literal template<typename CharT, typename std::enable_if< std::is_pointer<CharT>::value and std::is_integral<typename std::remove_pointer<CharT>::type>::value and sizeof(typename std::remove_pointer<CharT>::type) == 1, int>::type = 0> input_adapter(CharT b) : input_adapter(reinterpret_cast<const char*>(b), std::strlen(reinterpret_cast<const char*>(b))) {} /// input adapter for iterator range with contiguous storage template<class IteratorType, typename std::enable_if< std::is_same<typename iterator_traits<IteratorType>::iterator_category, std::random_access_iterator_tag>::value, int>::type = 0> input_adapter(IteratorType first, IteratorType last) { #ifndef NDEBUG // assertion to check that the iterator range is indeed contiguous, // see http://stackoverflow.com/a/35008842/266378 for more discussion const auto is_contiguous = std::accumulate( first, last, std::pair<bool, int>(true, 0), [&first](std::pair<bool, int> res, decltype(*first) val) { res.first &= (val == *(std::next(std::addressof(*first), res.second++))); return res; }).first; assert(is_contiguous); #endif // assertion to check that each element is 1 byte long static_assert( sizeof(typename iterator_traits<IteratorType>::value_type) == 1, "each element in the iterator range must have the size of 1 byte"); const auto len = static_cast<size_t>(std::distance(first, last)); if (JSON_LIKELY(len > 0)) { // there is at least one element: use the address of first ia = std::make_shared<input_buffer_adapter>(reinterpret_cast<const char*>(&(*first)), len); } else { // the address of first cannot be used: use nullptr ia = std::make_shared<input_buffer_adapter>(nullptr, len); } } /// input adapter for array template<class T, std::size_t N> input_adapter(T (&array)[N]) : input_adapter(std::begin(array), std::end(array)) {} /// input adapter for contiguous container template<class ContiguousContainer, typename std::enable_if<not std::is_pointer<ContiguousContainer>::value and std::is_base_of<std::random_access_iterator_tag, typename iterator_traits<decltype(std::begin(std::declval<ContiguousContainer const>()))>::iterator_category>::value, int>::type = 0> input_adapter(const ContiguousContainer& c) : input_adapter(std::begin(c), std::end(c)) {} operator input_adapter_t() { return ia; } private: /// the actual adapter input_adapter_t ia = nullptr; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/lexer.hpp> #include <clocale> // localeconv #include <cstddef> // size_t #include <cstdlib> // strtof, strtod, strtold, strtoll, strtoull #include <cstdio> // snprintf #include <initializer_list> // initializer_list #include <string> // char_traits, string #include <vector> // vector // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/input/input_adapters.hpp> // #include <nlohmann/detail/input/position_t.hpp> namespace nlohmann { namespace detail { /////////// // lexer // /////////// /*! @brief lexical analysis This class organizes the lexical analysis during JSON deserialization. */ template<typename BasicJsonType> class lexer { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; public: /// token types for the parser enum class token_type { uninitialized, ///< indicating the scanner is uninitialized literal_true, ///< the `true` literal literal_false, ///< the `false` literal literal_null, ///< the `null` literal value_string, ///< a string -- use get_string() for actual value value_unsigned, ///< an unsigned integer -- use get_number_unsigned() for actual value value_integer, ///< a signed integer -- use get_number_integer() for actual value value_float, ///< an floating point number -- use get_number_float() for actual value begin_array, ///< the character for array begin `[` begin_object, ///< the character for object begin `{` end_array, ///< the character for array end `]` end_object, ///< the character for object end `}` name_separator, ///< the name separator `:` value_separator, ///< the value separator `,` parse_error, ///< indicating a parse error end_of_input, ///< indicating the end of the input buffer literal_or_value ///< a literal or the begin of a value (only for diagnostics) }; /// return name of values of type token_type (only used for errors) static const char* token_type_name(const token_type t) noexcept { switch (t) { case token_type::uninitialized: return "<uninitialized>"; case token_type::literal_true: return "true literal"; case token_type::literal_false: return "false literal"; case token_type::literal_null: return "null literal"; case token_type::value_string: return "string literal"; case lexer::token_type::value_unsigned: case lexer::token_type::value_integer: case lexer::token_type::value_float: return "number literal"; case token_type::begin_array: return "'['"; case token_type::begin_object: return "'{'"; case token_type::end_array: return "']'"; case token_type::end_object: return "'}'"; case token_type::name_separator: return "':'"; case token_type::value_separator: return "','"; case token_type::parse_error: return "<parse error>"; case token_type::end_of_input: return "end of input"; case token_type::literal_or_value: return "'[', '{', or a literal"; // LCOV_EXCL_START default: // catch non-enum values return "unknown token"; // LCOV_EXCL_STOP } } explicit lexer(detail::input_adapter_t&& adapter) : ia(std::move(adapter)), decimal_point_char(get_decimal_point()) {} // delete because of pointer members lexer(const lexer&) = delete; lexer(lexer&&) = delete; lexer& operator=(lexer&) = delete; lexer& operator=(lexer&&) = delete; ~lexer() = default; private: ///////////////////// // locales ///////////////////// /// return the locale-dependent decimal point static char get_decimal_point() noexcept { const auto loc = localeconv(); assert(loc != nullptr); return (loc->decimal_point == nullptr) ? '.' : *(loc->decimal_point); } ///////////////////// // scan functions ///////////////////// /*! @brief get codepoint from 4 hex characters following `\u` For input "\u c1 c2 c3 c4" the codepoint is: (c1 * 0x1000) + (c2 * 0x0100) + (c3 * 0x0010) + c4 = (c1 << 12) + (c2 << 8) + (c3 << 4) + (c4 << 0) Furthermore, the possible characters '0'..'9', 'A'..'F', and 'a'..'f' must be converted to the integers 0x0..0x9, 0xA..0xF, 0xA..0xF, resp. The conversion is done by subtracting the offset (0x30, 0x37, and 0x57) between the ASCII value of the character and the desired integer value. @return codepoint (0x0000..0xFFFF) or -1 in case of an error (e.g. EOF or non-hex character) */ int get_codepoint() { // this function only makes sense after reading `\u` assert(current == 'u'); int codepoint = 0; const auto factors = { 12, 8, 4, 0 }; for (const auto factor : factors) { get(); if (current >= '0' and current <= '9') { codepoint += ((current - 0x30) << factor); } else if (current >= 'A' and current <= 'F') { codepoint += ((current - 0x37) << factor); } else if (current >= 'a' and current <= 'f') { codepoint += ((current - 0x57) << factor); } else { return -1; } } assert(0x0000 <= codepoint and codepoint <= 0xFFFF); return codepoint; } /*! @brief check if the next byte(s) are inside a given range Adds the current byte and, for each passed range, reads a new byte and checks if it is inside the range. If a violation was detected, set up an error message and return false. Otherwise, return true. @param[in] ranges list of integers; interpreted as list of pairs of inclusive lower and upper bound, respectively @pre The passed list @a ranges must have 2, 4, or 6 elements; that is, 1, 2, or 3 pairs. This precondition is enforced by an assertion. @return true if and only if no range violation was detected */ bool next_byte_in_range(std::initializer_list<int> ranges) { assert(ranges.size() == 2 || ranges.size() == 4 or ranges.size() == 6); add(current); for (auto range = ranges.begin(); range != ranges.end(); ++range) { get(); if (JSON_LIKELY(*range <= current and current <= *(++range))) { add(current); } else { error_message = "invalid string: ill-formed UTF-8 byte"; return false; } } return true; } /*! @brief scan a string literal This function scans a string according to Sect. 7 of RFC 7159. While scanning, bytes are escaped and copied into buffer token_buffer. Then the function returns successfully, token_buffer is *not* null-terminated (as it may contain \0 bytes), and token_buffer.size() is the number of bytes in the string. @return token_type::value_string if string could be successfully scanned, token_type::parse_error otherwise @note In case of errors, variable error_message contains a textual description. */ token_type scan_string() { // reset token_buffer (ignore opening quote) reset(); // we entered the function by reading an open quote assert(current == '\"'); while (true) { // get next character switch (get()) { // end of file while parsing string case std::char_traits<char>::eof(): { error_message = "invalid string: missing closing quote"; return token_type::parse_error; } // closing quote case '\"': { return token_type::value_string; } // escapes case '\\': { switch (get()) { // quotation mark case '\"': add('\"'); break; // reverse solidus case '\\': add('\\'); break; // solidus case '/': add('/'); break; // backspace case 'b': add('\b'); break; // form feed case 'f': add('\f'); break; // line feed case 'n': add('\n'); break; // carriage return case 'r': add('\r'); break; // tab case 't': add('\t'); break; // unicode escapes case 'u': { const int codepoint1 = get_codepoint(); int codepoint = codepoint1; // start with codepoint1 if (JSON_UNLIKELY(codepoint1 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if code point is a high surrogate if (0xD800 <= codepoint1 and codepoint1 <= 0xDBFF) { // expect next \uxxxx entry if (JSON_LIKELY(get() == '\\' and get() == 'u')) { const int codepoint2 = get_codepoint(); if (JSON_UNLIKELY(codepoint2 == -1)) { error_message = "invalid string: '\\u' must be followed by 4 hex digits"; return token_type::parse_error; } // check if codepoint2 is a low surrogate if (JSON_LIKELY(0xDC00 <= codepoint2 and codepoint2 <= 0xDFFF)) { // overwrite codepoint codepoint = // high surrogate occupies the most significant 22 bits (codepoint1 << 10) // low surrogate occupies the least significant 15 bits + codepoint2 // there is still the 0xD800, 0xDC00 and 0x10000 noise // in the result so we have to subtract with: // (0xD800 << 10) + DC00 - 0x10000 = 0x35FDC00 - 0x35FDC00; } else { error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { error_message = "invalid string: surrogate U+DC00..U+DFFF must be followed by U+DC00..U+DFFF"; return token_type::parse_error; } } else { if (JSON_UNLIKELY(0xDC00 <= codepoint1 and codepoint1 <= 0xDFFF)) { error_message = "invalid string: surrogate U+DC00..U+DFFF must follow U+D800..U+DBFF"; return token_type::parse_error; } } // result of the above calculation yields a proper codepoint assert(0x00 <= codepoint and codepoint <= 0x10FFFF); // translate codepoint into bytes if (codepoint < 0x80) { // 1-byte characters: 0xxxxxxx (ASCII) add(codepoint); } else if (codepoint <= 0x7FF) { // 2-byte characters: 110xxxxx 10xxxxxx add(0xC0 | (codepoint >> 6)); add(0x80 | (codepoint & 0x3F)); } else if (codepoint <= 0xFFFF) { // 3-byte characters: 1110xxxx 10xxxxxx 10xxxxxx add(0xE0 | (codepoint >> 12)); add(0x80 | ((codepoint >> 6) & 0x3F)); add(0x80 | (codepoint & 0x3F)); } else { // 4-byte characters: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx add(0xF0 | (codepoint >> 18)); add(0x80 | ((codepoint >> 12) & 0x3F)); add(0x80 | ((codepoint >> 6) & 0x3F)); add(0x80 | (codepoint & 0x3F)); } break; } // other characters after escape default: error_message = "invalid string: forbidden character after backslash"; return token_type::parse_error; } break; } // invalid control characters case 0x00: { error_message = "invalid string: control character U+0000 (NUL) must be escaped to \\u0000"; return token_type::parse_error; } case 0x01: { error_message = "invalid string: control character U+0001 (SOH) must be escaped to \\u0001"; return token_type::parse_error; } case 0x02: { error_message = "invalid string: control character U+0002 (STX) must be escaped to \\u0002"; return token_type::parse_error; } case 0x03: { error_message = "invalid string: control character U+0003 (ETX) must be escaped to \\u0003"; return token_type::parse_error; } case 0x04: { error_message = "invalid string: control character U+0004 (EOT) must be escaped to \\u0004"; return token_type::parse_error; } case 0x05: { error_message = "invalid string: control character U+0005 (ENQ) must be escaped to \\u0005"; return token_type::parse_error; } case 0x06: { error_message = "invalid string: control character U+0006 (ACK) must be escaped to \\u0006"; return token_type::parse_error; } case 0x07: { error_message = "invalid string: control character U+0007 (BEL) must be escaped to \\u0007"; return token_type::parse_error; } case 0x08: { error_message = "invalid string: control character U+0008 (BS) must be escaped to \\u0008 or \\b"; return token_type::parse_error; } case 0x09: { error_message = "invalid string: control character U+0009 (HT) must be escaped to \\u0009 or \\t"; return token_type::parse_error; } case 0x0A: { error_message = "invalid string: control character U+000A (LF) must be escaped to \\u000A or \\n"; return token_type::parse_error; } case 0x0B: { error_message = "invalid string: control character U+000B (VT) must be escaped to \\u000B"; return token_type::parse_error; } case 0x0C: { error_message = "invalid string: control character U+000C (FF) must be escaped to \\u000C or \\f"; return token_type::parse_error; } case 0x0D: { error_message = "invalid string: control character U+000D (CR) must be escaped to \\u000D or \\r"; return token_type::parse_error; } case 0x0E: { error_message = "invalid string: control character U+000E (SO) must be escaped to \\u000E"; return token_type::parse_error; } case 0x0F: { error_message = "invalid string: control character U+000F (SI) must be escaped to \\u000F"; return token_type::parse_error; } case 0x10: { error_message = "invalid string: control character U+0010 (DLE) must be escaped to \\u0010"; return token_type::parse_error; } case 0x11: { error_message = "invalid string: control character U+0011 (DC1) must be escaped to \\u0011"; return token_type::parse_error; } case 0x12: { error_message = "invalid string: control character U+0012 (DC2) must be escaped to \\u0012"; return token_type::parse_error; } case 0x13: { error_message = "invalid string: control character U+0013 (DC3) must be escaped to \\u0013"; return token_type::parse_error; } case 0x14: { error_message = "invalid string: control character U+0014 (DC4) must be escaped to \\u0014"; return token_type::parse_error; } case 0x15: { error_message = "invalid string: control character U+0015 (NAK) must be escaped to \\u0015"; return token_type::parse_error; } case 0x16: { error_message = "invalid string: control character U+0016 (SYN) must be escaped to \\u0016"; return token_type::parse_error; } case 0x17: { error_message = "invalid string: control character U+0017 (ETB) must be escaped to \\u0017"; return token_type::parse_error; } case 0x18: { error_message = "invalid string: control character U+0018 (CAN) must be escaped to \\u0018"; return token_type::parse_error; } case 0x19: { error_message = "invalid string: control character U+0019 (EM) must be escaped to \\u0019"; return token_type::parse_error; } case 0x1A: { error_message = "invalid string: control character U+001A (SUB) must be escaped to \\u001A"; return token_type::parse_error; } case 0x1B: { error_message = "invalid string: control character U+001B (ESC) must be escaped to \\u001B"; return token_type::parse_error; } case 0x1C: { error_message = "invalid string: control character U+001C (FS) must be escaped to \\u001C"; return token_type::parse_error; } case 0x1D: { error_message = "invalid string: control character U+001D (GS) must be escaped to \\u001D"; return token_type::parse_error; } case 0x1E: { error_message = "invalid string: control character U+001E (RS) must be escaped to \\u001E"; return token_type::parse_error; } case 0x1F: { error_message = "invalid string: control character U+001F (US) must be escaped to \\u001F"; return token_type::parse_error; } // U+0020..U+007F (except U+0022 (quote) and U+005C (backspace)) case 0x20: case 0x21: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: { add(current); break; } // U+0080..U+07FF: bytes C2..DF 80..BF case 0xC2: case 0xC3: case 0xC4: case 0xC5: case 0xC6: case 0xC7: case 0xC8: case 0xC9: case 0xCA: case 0xCB: case 0xCC: case 0xCD: case 0xCE: case 0xCF: case 0xD0: case 0xD1: case 0xD2: case 0xD3: case 0xD4: case 0xD5: case 0xD6: case 0xD7: case 0xD8: case 0xD9: case 0xDA: case 0xDB: case 0xDC: case 0xDD: case 0xDE: case 0xDF: { if (JSON_UNLIKELY(not next_byte_in_range({0x80, 0xBF}))) { return token_type::parse_error; } break; } // U+0800..U+0FFF: bytes E0 A0..BF 80..BF case 0xE0: { if (JSON_UNLIKELY(not (next_byte_in_range({0xA0, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+1000..U+CFFF: bytes E1..EC 80..BF 80..BF // U+E000..U+FFFF: bytes EE..EF 80..BF 80..BF case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xEE: case 0xEF: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+D000..U+D7FF: bytes ED 80..9F 80..BF case 0xED: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x9F, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+10000..U+3FFFF F0 90..BF 80..BF 80..BF case 0xF0: { if (JSON_UNLIKELY(not (next_byte_in_range({0x90, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+40000..U+FFFFF F1..F3 80..BF 80..BF 80..BF case 0xF1: case 0xF2: case 0xF3: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0xBF, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // U+100000..U+10FFFF F4 80..8F 80..BF 80..BF case 0xF4: { if (JSON_UNLIKELY(not (next_byte_in_range({0x80, 0x8F, 0x80, 0xBF, 0x80, 0xBF})))) { return token_type::parse_error; } break; } // remaining bytes (80..C1 and F5..FF) are ill-formed default: { error_message = "invalid string: ill-formed UTF-8 byte"; return token_type::parse_error; } } } } static void strtof(float& f, const char* str, char** endptr) noexcept { f = std::strtof(str, endptr); } static void strtof(double& f, const char* str, char** endptr) noexcept { f = std::strtod(str, endptr); } static void strtof(long double& f, const char* str, char** endptr) noexcept { f = std::strtold(str, endptr); } /*! @brief scan a number literal This function scans a string according to Sect. 6 of RFC 7159. The function is realized with a deterministic finite state machine derived from the grammar described in RFC 7159. Starting in state "init", the input is read and used to determined the next state. Only state "done" accepts the number. State "error" is a trap state to model errors. In the table below, "anything" means any character but the ones listed before. state | 0 | 1-9 | e E | + | - | . | anything ---------|----------|----------|----------|---------|---------|----------|----------- init | zero | any1 | [error] | [error] | minus | [error] | [error] minus | zero | any1 | [error] | [error] | [error] | [error] | [error] zero | done | done | exponent | done | done | decimal1 | done any1 | any1 | any1 | exponent | done | done | decimal1 | done decimal1 | decimal2 | [error] | [error] | [error] | [error] | [error] | [error] decimal2 | decimal2 | decimal2 | exponent | done | done | done | done exponent | any2 | any2 | [error] | sign | sign | [error] | [error] sign | any2 | any2 | [error] | [error] | [error] | [error] | [error] any2 | any2 | any2 | done | done | done | done | done The state machine is realized with one label per state (prefixed with "scan_number_") and `goto` statements between them. The state machine contains cycles, but any cycle can be left when EOF is read. Therefore, the function is guaranteed to terminate. During scanning, the read bytes are stored in token_buffer. This string is then converted to a signed integer, an unsigned integer, or a floating-point number. @return token_type::value_unsigned, token_type::value_integer, or token_type::value_float if number could be successfully scanned, token_type::parse_error otherwise @note The scanner is independent of the current locale. Internally, the locale's decimal point is used instead of `.` to work with the locale-dependent converters. */ token_type scan_number() // lgtm [cpp/use-of-goto] { // reset token_buffer to store the number's bytes reset(); // the type of the parsed number; initially set to unsigned; will be // changed if minus sign, decimal point or exponent is read token_type number_type = token_type::value_unsigned; // state (init): we just found out we need to scan a number switch (current) { case '-': { add(current); goto scan_number_minus; } case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } // LCOV_EXCL_START default: { // all other characters are rejected outside scan_number() assert(false); } // LCOV_EXCL_STOP } scan_number_minus: // state: we just parsed a leading minus sign number_type = token_type::value_integer; switch (get()) { case '0': { add(current); goto scan_number_zero; } case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } default: { error_message = "invalid number; expected digit after '-'"; return token_type::parse_error; } } scan_number_zero: // state: we just parse a zero (maybe with a leading minus sign) switch (get()) { case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_any1: // state: we just parsed a number 0-9 (maybe with a leading minus sign) switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any1; } case '.': { add(decimal_point_char); goto scan_number_decimal1; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_decimal1: // state: we just parsed a decimal point number_type = token_type::value_float; switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } default: { error_message = "invalid number; expected digit after '.'"; return token_type::parse_error; } } scan_number_decimal2: // we just parsed at least one number after a decimal point switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_decimal2; } case 'e': case 'E': { add(current); goto scan_number_exponent; } default: goto scan_number_done; } scan_number_exponent: // we just parsed an exponent number_type = token_type::value_float; switch (get()) { case '+': case '-': { add(current); goto scan_number_sign; } case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected '+', '-', or digit after exponent"; return token_type::parse_error; } } scan_number_sign: // we just parsed an exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: { error_message = "invalid number; expected digit after exponent sign"; return token_type::parse_error; } } scan_number_any2: // we just parsed a number after the exponent or exponent sign switch (get()) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': { add(current); goto scan_number_any2; } default: goto scan_number_done; } scan_number_done: // unget the character after the number (we only read it to know that // we are done scanning a number) unget(); char* endptr = nullptr; errno = 0; // try to parse integers first and fall back to floats if (number_type == token_type::value_unsigned) { const auto x = std::strtoull(token_buffer.data(), &endptr, 10); // we checked the number format before assert(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_unsigned = static_cast<number_unsigned_t>(x); if (value_unsigned == x) { return token_type::value_unsigned; } } } else if (number_type == token_type::value_integer) { const auto x = std::strtoll(token_buffer.data(), &endptr, 10); // we checked the number format before assert(endptr == token_buffer.data() + token_buffer.size()); if (errno == 0) { value_integer = static_cast<number_integer_t>(x); if (value_integer == x) { return token_type::value_integer; } } } // this code is reached if we parse a floating-point number or if an // integer conversion above failed strtof(value_float, token_buffer.data(), &endptr); // we checked the number format before assert(endptr == token_buffer.data() + token_buffer.size()); return token_type::value_float; } /*! @param[in] literal_text the literal text to expect @param[in] length the length of the passed literal text @param[in] return_type the token type to return on success */ token_type scan_literal(const char* literal_text, const std::size_t length, token_type return_type) { assert(current == literal_text[0]); for (std::size_t i = 1; i < length; ++i) { if (JSON_UNLIKELY(get() != literal_text[i])) { error_message = "invalid literal"; return token_type::parse_error; } } return return_type; } ///////////////////// // input management ///////////////////// /// reset token_buffer; current character is beginning of token void reset() noexcept { token_buffer.clear(); token_string.clear(); token_string.push_back(std::char_traits<char>::to_char_type(current)); } /* @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a `std::char_traits<char>::eof()` in that case. Stores the scanned characters for use in error messages. @return character read from the input */ std::char_traits<char>::int_type get() { ++position.chars_read_total; ++position.chars_read_current_line; if (next_unget) { // just reset the next_unget variable and work with current next_unget = false; } else { current = ia->get_character(); } if (JSON_LIKELY(current != std::char_traits<char>::eof())) { token_string.push_back(std::char_traits<char>::to_char_type(current)); } if (current == '\n') { ++position.lines_read; position.chars_read_current_line = 0; } return current; } /*! @brief unget current character (read it again on next get) We implement unget by setting variable next_unget to true. The input is not changed - we just simulate ungetting by modifying chars_read_total, chars_read_current_line, and token_string. The next call to get() will behave as if the unget character is read again. */ void unget() { next_unget = true; --position.chars_read_total; // in case we "unget" a newline, we have to also decrement the lines_read if (position.chars_read_current_line == 0) { if (position.lines_read > 0) { --position.lines_read; } } else { --position.chars_read_current_line; } if (JSON_LIKELY(current != std::char_traits<char>::eof())) { assert(token_string.size() != 0); token_string.pop_back(); } } /// add a character to token_buffer void add(int c) { token_buffer.push_back(std::char_traits<char>::to_char_type(c)); } public: ///////////////////// // value getters ///////////////////// /// return integer value constexpr number_integer_t get_number_integer() const noexcept { return value_integer; } /// return unsigned integer value constexpr number_unsigned_t get_number_unsigned() const noexcept { return value_unsigned; } /// return floating-point value constexpr number_float_t get_number_float() const noexcept { return value_float; } /// return current string value (implicitly resets the token; useful only once) string_t& get_string() { return token_buffer; } ///////////////////// // diagnostics ///////////////////// /// return position of last read token constexpr position_t get_position() const noexcept { return position; } /// return the last read token (for errors only). Will never contain EOF /// (an arbitrary value that is not a valid char value, often -1), because /// 255 may legitimately occur. May contain NUL, which should be escaped. std::string get_token_string() const { // escape control characters std::string result; for (const auto c : token_string) { if ('\x00' <= c and c <= '\x1F') { // escape control characters char cs[9]; (std::snprintf)(cs, 9, "<U+%.4X>", static_cast<unsigned char>(c)); result += cs; } else { // add character as is result.push_back(c); } } return result; } /// return syntax error message constexpr const char* get_error_message() const noexcept { return error_message; } ///////////////////// // actual scanner ///////////////////// /*! @brief skip the UTF-8 byte order mark @return true iff there is no BOM or the correct BOM has been skipped */ bool skip_bom() { if (get() == 0xEF) { // check if we completely parse the BOM return get() == 0xBB and get() == 0xBF; } // the first character is not the beginning of the BOM; unget it to // process is later unget(); return true; } token_type scan() { // initially, skip the BOM if (position.chars_read_total == 0 and not skip_bom()) { error_message = "invalid BOM; must be 0xEF 0xBB 0xBF if given"; return token_type::parse_error; } // read next character and ignore whitespace do { get(); } while (current == ' ' or current == '\t' or current == '\n' or current == '\r'); switch (current) { // structural characters case '[': return token_type::begin_array; case ']': return token_type::end_array; case '{': return token_type::begin_object; case '}': return token_type::end_object; case ':': return token_type::name_separator; case ',': return token_type::value_separator; // literals case 't': return scan_literal("true", 4, token_type::literal_true); case 'f': return scan_literal("false", 5, token_type::literal_false); case 'n': return scan_literal("null", 4, token_type::literal_null); // string case '\"': return scan_string(); // number case '-': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': return scan_number(); // end of input (the null byte is needed when parsing from // string literals) case '\0': case std::char_traits<char>::eof(): return token_type::end_of_input; // error default: error_message = "invalid literal"; return token_type::parse_error; } } private: /// input adapter detail::input_adapter_t ia = nullptr; /// the current character std::char_traits<char>::int_type current = std::char_traits<char>::eof(); /// whether the next get() call should just return current bool next_unget = false; /// the start position of the current token position_t position; /// raw input token string (for error messages) std::vector<char> token_string {}; /// buffer for variable-length tokens (numbers, strings) string_t token_buffer {}; /// a description of occurred lexer errors const char* error_message = ""; // number values number_integer_t value_integer = 0; number_unsigned_t value_unsigned = 0; number_float_t value_float = 0; /// the decimal point const char decimal_point_char = '.'; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/parser.hpp> #include <cassert> // assert #include <cmath> // isfinite #include <cstdint> // uint8_t #include <functional> // function #include <string> // string #include <utility> // move // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/is_sax.hpp> #include <cstdint> // size_t #include <utility> // declval // #include <nlohmann/detail/meta/detected.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> namespace nlohmann { namespace detail { template <typename T> using null_function_t = decltype(std::declval<T&>().null()); template <typename T> using boolean_function_t = decltype(std::declval<T&>().boolean(std::declval<bool>())); template <typename T, typename Integer> using number_integer_function_t = decltype(std::declval<T&>().number_integer(std::declval<Integer>())); template <typename T, typename Unsigned> using number_unsigned_function_t = decltype(std::declval<T&>().number_unsigned(std::declval<Unsigned>())); template <typename T, typename Float, typename String> using number_float_function_t = decltype(std::declval<T&>().number_float( std::declval<Float>(), std::declval<const String&>())); template <typename T, typename String> using string_function_t = decltype(std::declval<T&>().string(std::declval<String&>())); template <typename T> using start_object_function_t = decltype(std::declval<T&>().start_object(std::declval<std::size_t>())); template <typename T, typename String> using key_function_t = decltype(std::declval<T&>().key(std::declval<String&>())); template <typename T> using end_object_function_t = decltype(std::declval<T&>().end_object()); template <typename T> using start_array_function_t = decltype(std::declval<T&>().start_array(std::declval<std::size_t>())); template <typename T> using end_array_function_t = decltype(std::declval<T&>().end_array()); template <typename T, typename Exception> using parse_error_function_t = decltype(std::declval<T&>().parse_error( std::declval<std::size_t>(), std::declval<const std::string&>(), std::declval<const Exception&>())); template <typename SAX, typename BasicJsonType> struct is_sax { private: static_assert(is_basic_json<BasicJsonType>::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using exception_t = typename BasicJsonType::exception; public: static constexpr bool value = is_detected_exact<bool, null_function_t, SAX>::value && is_detected_exact<bool, boolean_function_t, SAX>::value && is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value && is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value && is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value && is_detected_exact<bool, string_function_t, SAX, string_t>::value && is_detected_exact<bool, start_object_function_t, SAX>::value && is_detected_exact<bool, key_function_t, SAX, string_t>::value && is_detected_exact<bool, end_object_function_t, SAX>::value && is_detected_exact<bool, start_array_function_t, SAX>::value && is_detected_exact<bool, end_array_function_t, SAX>::value && is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value; }; template <typename SAX, typename BasicJsonType> struct is_sax_static_asserts { private: static_assert(is_basic_json<BasicJsonType>::value, "BasicJsonType must be of type basic_json<...>"); using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using exception_t = typename BasicJsonType::exception; public: static_assert(is_detected_exact<bool, null_function_t, SAX>::value, "Missing/invalid function: bool null()"); static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value, "Missing/invalid function: bool boolean(bool)"); static_assert(is_detected_exact<bool, boolean_function_t, SAX>::value, "Missing/invalid function: bool boolean(bool)"); static_assert( is_detected_exact<bool, number_integer_function_t, SAX, number_integer_t>::value, "Missing/invalid function: bool number_integer(number_integer_t)"); static_assert( is_detected_exact<bool, number_unsigned_function_t, SAX, number_unsigned_t>::value, "Missing/invalid function: bool number_unsigned(number_unsigned_t)"); static_assert(is_detected_exact<bool, number_float_function_t, SAX, number_float_t, string_t>::value, "Missing/invalid function: bool number_float(number_float_t, const string_t&)"); static_assert( is_detected_exact<bool, string_function_t, SAX, string_t>::value, "Missing/invalid function: bool string(string_t&)"); static_assert(is_detected_exact<bool, start_object_function_t, SAX>::value, "Missing/invalid function: bool start_object(std::size_t)"); static_assert(is_detected_exact<bool, key_function_t, SAX, string_t>::value, "Missing/invalid function: bool key(string_t&)"); static_assert(is_detected_exact<bool, end_object_function_t, SAX>::value, "Missing/invalid function: bool end_object()"); static_assert(is_detected_exact<bool, start_array_function_t, SAX>::value, "Missing/invalid function: bool start_array(std::size_t)"); static_assert(is_detected_exact<bool, end_array_function_t, SAX>::value, "Missing/invalid function: bool end_array()"); static_assert( is_detected_exact<bool, parse_error_function_t, SAX, exception_t>::value, "Missing/invalid function: bool parse_error(std::size_t, const " "std::string&, const exception&)"); }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/input_adapters.hpp> // #include <nlohmann/detail/input/json_sax.hpp> #include <cassert> #include <cstddef> #include <string> #include <vector> // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/macro_scope.hpp> namespace nlohmann { /*! @brief SAX interface This class describes the SAX interface used by @ref nlohmann::json::sax_parse. Each function is called in different situations while the input is parsed. The boolean return value informs the parser whether to continue processing the input. */ template<typename BasicJsonType> struct json_sax { /// type for (signed) integers using number_integer_t = typename BasicJsonType::number_integer_t; /// type for unsigned integers using number_unsigned_t = typename BasicJsonType::number_unsigned_t; /// type for floating-point numbers using number_float_t = typename BasicJsonType::number_float_t; /// type for strings using string_t = typename BasicJsonType::string_t; /*! @brief a null value was read @return whether parsing should proceed */ virtual bool null() = 0; /*! @brief a boolean value was read @param[in] val boolean value @return whether parsing should proceed */ virtual bool boolean(bool val) = 0; /*! @brief an integer number was read @param[in] val integer value @return whether parsing should proceed */ virtual bool number_integer(number_integer_t val) = 0; /*! @brief an unsigned integer number was read @param[in] val unsigned integer value @return whether parsing should proceed */ virtual bool number_unsigned(number_unsigned_t val) = 0; /*! @brief an floating-point number was read @param[in] val floating-point value @param[in] s raw token value @return whether parsing should proceed */ virtual bool number_float(number_float_t val, const string_t& s) = 0; /*! @brief a string was read @param[in] val string value @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool string(string_t& val) = 0; /*! @brief the beginning of an object was read @param[in] elements number of object elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_object(std::size_t elements) = 0; /*! @brief an object key was read @param[in] val object key @return whether parsing should proceed @note It is safe to move the passed string. */ virtual bool key(string_t& val) = 0; /*! @brief the end of an object was read @return whether parsing should proceed */ virtual bool end_object() = 0; /*! @brief the beginning of an array was read @param[in] elements number of array elements or -1 if unknown @return whether parsing should proceed @note binary formats may report the number of elements */ virtual bool start_array(std::size_t elements) = 0; /*! @brief the end of an array was read @return whether parsing should proceed */ virtual bool end_array() = 0; /*! @brief a parse error occurred @param[in] position the position in the input where the error occurs @param[in] last_token the last read token @param[in] ex an exception object describing the error @return whether parsing should proceed (must return false) */ virtual bool parse_error(std::size_t position, const std::string& last_token, const detail::exception& ex) = 0; virtual ~json_sax() = default; }; namespace detail { /*! @brief SAX implementation to create a JSON value from SAX events This class implements the @ref json_sax interface and processes the SAX events to create a JSON value which makes it basically a DOM parser. The structure or hierarchy of the JSON value is managed by the stack `ref_stack` which contains a pointer to the respective array or object for each recursion depth. After successful parsing, the value that is passed by reference to the constructor contains the parsed value. @tparam BasicJsonType the JSON type */ template<typename BasicJsonType> class json_sax_dom_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; /*! @param[in, out] r reference to a JSON value that is manipulated while parsing @param[in] allow_exceptions_ whether parse errors yield exceptions */ explicit json_sax_dom_parser(BasicJsonType& r, const bool allow_exceptions_ = true) : root(r), allow_exceptions(allow_exceptions_) {} bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool start_object(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::object)); if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len))); } return true; } bool key(string_t& val) { // add null at given key and store the reference for later object_element = &(ref_stack.back()->m_value.object->operator[](val)); return true; } bool end_object() { ref_stack.pop_back(); return true; } bool start_array(std::size_t len) { ref_stack.push_back(handle_value(BasicJsonType::value_t::array)); if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len))); } return true; } bool end_array() { ref_stack.pop_back(); return true; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& ex) { errored = true; if (allow_exceptions) { // determine the proper exception type from the id switch ((ex.id / 100) % 100) { case 1: JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex)); case 4: JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex)); // LCOV_EXCL_START case 2: JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex)); case 3: JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex)); case 5: JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex)); default: assert(false); // LCOV_EXCL_STOP } } return false; } constexpr bool is_errored() const { return errored; } private: /*! @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements */ template<typename Value> BasicJsonType* handle_value(Value&& v) { if (ref_stack.empty()) { root = BasicJsonType(std::forward<Value>(v)); return &root; } assert(ref_stack.back()->is_array() or ref_stack.back()->is_object()); if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->emplace_back(std::forward<Value>(v)); return &(ref_stack.back()->m_value.array->back()); } else { assert(object_element); *object_element = BasicJsonType(std::forward<Value>(v)); return object_element; } } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector<BasicJsonType*> ref_stack; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; template<typename BasicJsonType> class json_sax_dom_callback_parser { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using parser_callback_t = typename BasicJsonType::parser_callback_t; using parse_event_t = typename BasicJsonType::parse_event_t; json_sax_dom_callback_parser(BasicJsonType& r, const parser_callback_t cb, const bool allow_exceptions_ = true) : root(r), callback(cb), allow_exceptions(allow_exceptions_) { keep_stack.push_back(true); } bool null() { handle_value(nullptr); return true; } bool boolean(bool val) { handle_value(val); return true; } bool number_integer(number_integer_t val) { handle_value(val); return true; } bool number_unsigned(number_unsigned_t val) { handle_value(val); return true; } bool number_float(number_float_t val, const string_t& /*unused*/) { handle_value(val); return true; } bool string(string_t& val) { handle_value(val); return true; } bool start_object(std::size_t len) { // check callback for object start const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::object_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::object, true); ref_stack.push_back(val.second); // check object limit if (ref_stack.back()) { if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive object size: " + std::to_string(len))); } } return true; } bool key(string_t& val) { BasicJsonType k = BasicJsonType(val); // check callback for key const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::key, k); key_keep_stack.push_back(keep); // add discarded value at given key and store the reference for later if (keep and ref_stack.back()) { object_element = &(ref_stack.back()->m_value.object->operator[](val) = discarded); } return true; } bool end_object() { if (ref_stack.back()) { if (not callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::object_end, *ref_stack.back())) { // discard object *ref_stack.back() = discarded; } } assert(not ref_stack.empty()); assert(not keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); if (not ref_stack.empty() and ref_stack.back()) { // remove discarded value if (ref_stack.back()->is_object()) { for (auto it = ref_stack.back()->begin(); it != ref_stack.back()->end(); ++it) { if (it->is_discarded()) { ref_stack.back()->erase(it); break; } } } } return true; } bool start_array(std::size_t len) { const bool keep = callback(static_cast<int>(ref_stack.size()), parse_event_t::array_start, discarded); keep_stack.push_back(keep); auto val = handle_value(BasicJsonType::value_t::array, true); ref_stack.push_back(val.second); // check array limit if (ref_stack.back()) { if (JSON_UNLIKELY(len != std::size_t(-1) and len > ref_stack.back()->max_size())) { JSON_THROW(out_of_range::create(408, "excessive array size: " + std::to_string(len))); } } return true; } bool end_array() { bool keep = true; if (ref_stack.back()) { keep = callback(static_cast<int>(ref_stack.size()) - 1, parse_event_t::array_end, *ref_stack.back()); if (not keep) { // discard array *ref_stack.back() = discarded; } } assert(not ref_stack.empty()); assert(not keep_stack.empty()); ref_stack.pop_back(); keep_stack.pop_back(); // remove discarded value if (not keep and not ref_stack.empty()) { if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->pop_back(); } } return true; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& ex) { errored = true; if (allow_exceptions) { // determine the proper exception type from the id switch ((ex.id / 100) % 100) { case 1: JSON_THROW(*reinterpret_cast<const detail::parse_error*>(&ex)); case 4: JSON_THROW(*reinterpret_cast<const detail::out_of_range*>(&ex)); // LCOV_EXCL_START case 2: JSON_THROW(*reinterpret_cast<const detail::invalid_iterator*>(&ex)); case 3: JSON_THROW(*reinterpret_cast<const detail::type_error*>(&ex)); case 5: JSON_THROW(*reinterpret_cast<const detail::other_error*>(&ex)); default: assert(false); // LCOV_EXCL_STOP } } return false; } constexpr bool is_errored() const { return errored; } private: /*! @param[in] v value to add to the JSON value we build during parsing @param[in] skip_callback whether we should skip calling the callback function; this is required after start_array() and start_object() SAX events, because otherwise we would call the callback function with an empty array or object, respectively. @invariant If the ref stack is empty, then the passed value will be the new root. @invariant If the ref stack contains a value, then it is an array or an object to which we can add elements @return pair of boolean (whether value should be kept) and pointer (to the passed value in the ref_stack hierarchy; nullptr if not kept) */ template<typename Value> std::pair<bool, BasicJsonType*> handle_value(Value&& v, const bool skip_callback = false) { assert(not keep_stack.empty()); // do not handle this value if we know it would be added to a discarded // container if (not keep_stack.back()) { return {false, nullptr}; } // create value auto value = BasicJsonType(std::forward<Value>(v)); // check callback const bool keep = skip_callback or callback(static_cast<int>(ref_stack.size()), parse_event_t::value, value); // do not handle this value if we just learnt it shall be discarded if (not keep) { return {false, nullptr}; } if (ref_stack.empty()) { root = std::move(value); return {true, &root}; } // skip this value if we already decided to skip the parent // (https://github.com/nlohmann/json/issues/971#issuecomment-413678360) if (not ref_stack.back()) { return {false, nullptr}; } // we now only expect arrays and objects assert(ref_stack.back()->is_array() or ref_stack.back()->is_object()); if (ref_stack.back()->is_array()) { ref_stack.back()->m_value.array->push_back(std::move(value)); return {true, &(ref_stack.back()->m_value.array->back())}; } else { // check if we should store an element for the current key assert(not key_keep_stack.empty()); const bool store_element = key_keep_stack.back(); key_keep_stack.pop_back(); if (not store_element) { return {false, nullptr}; } assert(object_element); *object_element = std::move(value); return {true, object_element}; } } /// the parsed JSON value BasicJsonType& root; /// stack to model hierarchy of values std::vector<BasicJsonType*> ref_stack; /// stack to manage which values to keep std::vector<bool> keep_stack; /// stack to manage which object keys to keep std::vector<bool> key_keep_stack; /// helper to hold the reference for the next object element BasicJsonType* object_element = nullptr; /// whether a syntax error occurred bool errored = false; /// callback function const parser_callback_t callback = nullptr; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; /// a discarded value for the callback BasicJsonType discarded = BasicJsonType::value_t::discarded; }; template<typename BasicJsonType> class json_sax_acceptor { public: using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; bool null() { return true; } bool boolean(bool /*unused*/) { return true; } bool number_integer(number_integer_t /*unused*/) { return true; } bool number_unsigned(number_unsigned_t /*unused*/) { return true; } bool number_float(number_float_t /*unused*/, const string_t& /*unused*/) { return true; } bool string(string_t& /*unused*/) { return true; } bool start_object(std::size_t /*unused*/ = std::size_t(-1)) { return true; } bool key(string_t& /*unused*/) { return true; } bool end_object() { return true; } bool start_array(std::size_t /*unused*/ = std::size_t(-1)) { return true; } bool end_array() { return true; } bool parse_error(std::size_t /*unused*/, const std::string& /*unused*/, const detail::exception& /*unused*/) { return false; } }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/lexer.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { //////////// // parser // //////////// /*! @brief syntax analysis This class implements a recursive decent parser. */ template<typename BasicJsonType> class parser { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using lexer_t = lexer<BasicJsonType>; using token_type = typename lexer_t::token_type; public: enum class parse_event_t : uint8_t { /// the parser read `{` and started to process a JSON object object_start, /// the parser read `}` and finished processing a JSON object object_end, /// the parser read `[` and started to process a JSON array array_start, /// the parser read `]` and finished processing a JSON array array_end, /// the parser read a key of a value in an object key, /// the parser finished reading a JSON value value }; using parser_callback_t = std::function<bool(int depth, parse_event_t event, BasicJsonType& parsed)>; /// a parser reading from an input adapter explicit parser(detail::input_adapter_t&& adapter, const parser_callback_t cb = nullptr, const bool allow_exceptions_ = true) : callback(cb), m_lexer(std::move(adapter)), allow_exceptions(allow_exceptions_) { // read first token get_token(); } /*! @brief public parser interface @param[in] strict whether to expect the last token to be EOF @param[in,out] result parsed JSON value @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails */ void parse(const bool strict, BasicJsonType& result) { if (callback) { json_sax_dom_callback_parser<BasicJsonType> sdp(result, callback, allow_exceptions); sax_parse_internal(&sdp); result.assert_invariant(); // in strict mode, input must be completely read if (strict and (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"))); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } // set top-level value to null if it was discarded by the callback // function if (result.is_discarded()) { result = nullptr; } } else { json_sax_dom_parser<BasicJsonType> sdp(result, allow_exceptions); sax_parse_internal(&sdp); result.assert_invariant(); // in strict mode, input must be completely read if (strict and (get_token() != token_type::end_of_input)) { sdp.parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"))); } // in case of an error, return discarded value if (sdp.is_errored()) { result = value_t::discarded; return; } } } /*! @brief public accept interface @param[in] strict whether to expect the last token to be EOF @return whether the input is a proper JSON text */ bool accept(const bool strict = true) { json_sax_acceptor<BasicJsonType> sax_acceptor; return sax_parse(&sax_acceptor, strict); } template <typename SAX> bool sax_parse(SAX* sax, const bool strict = true) { (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {}; const bool result = sax_parse_internal(sax); // strict mode: next byte must be EOF if (result and strict and (get_token() != token_type::end_of_input)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_of_input, "value"))); } return result; } private: template <typename SAX> bool sax_parse_internal(SAX* sax) { // stack to remember the hierarchy of structured values we are parsing // true = array; false = object std::vector<bool> states; // value to avoid a goto (see comment where set to true) bool skip_to_state_evaluation = false; while (true) { if (not skip_to_state_evaluation) { // invariant: get_token() was called before each iteration switch (last_token) { case token_type::begin_object: { if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1)))) { return false; } // closing } -> we are done if (get_token() == token_type::end_object) { if (JSON_UNLIKELY(not sax->end_object())) { return false; } break; } // parse key if (JSON_UNLIKELY(last_token != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"))); } if (JSON_UNLIKELY(not sax->key(m_lexer.get_string()))) { return false; } // parse separator (:) if (JSON_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"))); } // remember we are now inside an object states.push_back(false); // parse values get_token(); continue; } case token_type::begin_array: { if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1)))) { return false; } // closing ] -> we are done if (get_token() == token_type::end_array) { if (JSON_UNLIKELY(not sax->end_array())) { return false; } break; } // remember we are now inside an array states.push_back(true); // parse values (no need to call get_token) continue; } case token_type::value_float: { const auto res = m_lexer.get_number_float(); if (JSON_UNLIKELY(not std::isfinite(res))) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), out_of_range::create(406, "number overflow parsing '" + m_lexer.get_token_string() + "'")); } else { if (JSON_UNLIKELY(not sax->number_float(res, m_lexer.get_string()))) { return false; } break; } } case token_type::literal_false: { if (JSON_UNLIKELY(not sax->boolean(false))) { return false; } break; } case token_type::literal_null: { if (JSON_UNLIKELY(not sax->null())) { return false; } break; } case token_type::literal_true: { if (JSON_UNLIKELY(not sax->boolean(true))) { return false; } break; } case token_type::value_integer: { if (JSON_UNLIKELY(not sax->number_integer(m_lexer.get_number_integer()))) { return false; } break; } case token_type::value_string: { if (JSON_UNLIKELY(not sax->string(m_lexer.get_string()))) { return false; } break; } case token_type::value_unsigned: { if (JSON_UNLIKELY(not sax->number_unsigned(m_lexer.get_number_unsigned()))) { return false; } break; } case token_type::parse_error: { // using "uninitialized" to avoid "expected" message return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::uninitialized, "value"))); } default: // the last token was unexpected { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::literal_or_value, "value"))); } } } else { skip_to_state_evaluation = false; } // we reached this line after we successfully parsed a value if (states.empty()) { // empty stack: we reached the end of the hierarchy: done return true; } else { if (states.back()) // array { // comma -> next value if (get_token() == token_type::value_separator) { // parse a new value get_token(); continue; } // closing ] if (JSON_LIKELY(last_token == token_type::end_array)) { if (JSON_UNLIKELY(not sax->end_array())) { return false; } // We are done with this array. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. assert(not states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } else { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_array, "array"))); } } else // object { // comma -> next value if (get_token() == token_type::value_separator) { // parse key if (JSON_UNLIKELY(get_token() != token_type::value_string)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::value_string, "object key"))); } else { if (JSON_UNLIKELY(not sax->key(m_lexer.get_string()))) { return false; } } // parse separator (:) if (JSON_UNLIKELY(get_token() != token_type::name_separator)) { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::name_separator, "object separator"))); } // parse values get_token(); continue; } // closing } if (JSON_LIKELY(last_token == token_type::end_object)) { if (JSON_UNLIKELY(not sax->end_object())) { return false; } // We are done with this object. Before we can parse a // new value, we need to evaluate the new state first. // By setting skip_to_state_evaluation to false, we // are effectively jumping to the beginning of this if. assert(not states.empty()); states.pop_back(); skip_to_state_evaluation = true; continue; } else { return sax->parse_error(m_lexer.get_position(), m_lexer.get_token_string(), parse_error::create(101, m_lexer.get_position(), exception_message(token_type::end_object, "object"))); } } } } } /// get next token from lexer token_type get_token() { return (last_token = m_lexer.scan()); } std::string exception_message(const token_type expected, const std::string& context) { std::string error_msg = "syntax error "; if (not context.empty()) { error_msg += "while parsing " + context + " "; } error_msg += "- "; if (last_token == token_type::parse_error) { error_msg += std::string(m_lexer.get_error_message()) + "; last read: '" + m_lexer.get_token_string() + "'"; } else { error_msg += "unexpected " + std::string(lexer_t::token_type_name(last_token)); } if (expected != token_type::uninitialized) { error_msg += "; expected " + std::string(lexer_t::token_type_name(expected)); } return error_msg; } private: /// callback function const parser_callback_t callback = nullptr; /// the type of the last read token token_type last_token = token_type::uninitialized; /// the lexer lexer_t m_lexer; /// whether to throw exceptions in case of errors const bool allow_exceptions = true; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/primitive_iterator.hpp> #include <cstddef> // ptrdiff_t #include <limits> // numeric_limits namespace nlohmann { namespace detail { /* @brief an iterator for primitive JSON types This class models an iterator for primitive JSON types (boolean, number, string). It's only purpose is to allow the iterator/const_iterator classes to "iterate" over primitive values. Internally, the iterator is modeled by a `difference_type` variable. Value begin_value (`0`) models the begin, end_value (`1`) models past the end. */ class primitive_iterator_t { private: using difference_type = std::ptrdiff_t; static constexpr difference_type begin_value = 0; static constexpr difference_type end_value = begin_value + 1; /// iterator as signed integer type difference_type m_it = (std::numeric_limits<std::ptrdiff_t>::min)(); public: constexpr difference_type get_value() const noexcept { return m_it; } /// set iterator to a defined beginning void set_begin() noexcept { m_it = begin_value; } /// set iterator to a defined past the end void set_end() noexcept { m_it = end_value; } /// return whether the iterator can be dereferenced constexpr bool is_begin() const noexcept { return m_it == begin_value; } /// return whether the iterator is at end constexpr bool is_end() const noexcept { return m_it == end_value; } friend constexpr bool operator==(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it == rhs.m_it; } friend constexpr bool operator<(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it < rhs.m_it; } primitive_iterator_t operator+(difference_type n) noexcept { auto result = *this; result += n; return result; } friend constexpr difference_type operator-(primitive_iterator_t lhs, primitive_iterator_t rhs) noexcept { return lhs.m_it - rhs.m_it; } primitive_iterator_t& operator++() noexcept { ++m_it; return *this; } primitive_iterator_t const operator++(int) noexcept { auto result = *this; ++m_it; return result; } primitive_iterator_t& operator--() noexcept { --m_it; return *this; } primitive_iterator_t const operator--(int) noexcept { auto result = *this; --m_it; return result; } primitive_iterator_t& operator+=(difference_type n) noexcept { m_it += n; return *this; } primitive_iterator_t& operator-=(difference_type n) noexcept { m_it -= n; return *this; } }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/internal_iterator.hpp> // #include <nlohmann/detail/iterators/primitive_iterator.hpp> namespace nlohmann { namespace detail { /*! @brief an iterator value @note This structure could easily be a union, but MSVC currently does not allow unions members with complex constructors, see https://github.com/nlohmann/json/pull/105. */ template<typename BasicJsonType> struct internal_iterator { /// iterator for JSON objects typename BasicJsonType::object_t::iterator object_iterator {}; /// iterator for JSON arrays typename BasicJsonType::array_t::iterator array_iterator {}; /// generic iterator for all other types primitive_iterator_t primitive_iterator {}; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/iter_impl.hpp> #include <ciso646> // not #include <iterator> // iterator, random_access_iterator_tag, bidirectional_iterator_tag, advance, next #include <type_traits> // conditional, is_const, remove_const // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/iterators/internal_iterator.hpp> // #include <nlohmann/detail/iterators/primitive_iterator.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/meta/type_traits.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { // forward declare, to be able to friend it later on template<typename IteratorType> class iteration_proxy; template<typename IteratorType> class iteration_proxy_value; /*! @brief a template for a bidirectional iterator for the @ref basic_json class This class implements a both iterators (iterator and const_iterator) for the @ref basic_json class. @note An iterator is called *initialized* when a pointer to a JSON value has been set (e.g., by a constructor or a copy assignment). If the iterator is default-constructed, it is *uninitialized* and most methods are undefined. **The library uses assertions to detect calls on uninitialized iterators.** @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). @since version 1.0.0, simplified in version 2.0.9, change to bidirectional iterators in version 3.0.0 (see https://github.com/nlohmann/json/issues/593) */ template<typename BasicJsonType> class iter_impl { /// allow basic_json to access private members friend iter_impl<typename std::conditional<std::is_const<BasicJsonType>::value, typename std::remove_const<BasicJsonType>::type, const BasicJsonType>::type>; friend BasicJsonType; friend iteration_proxy<iter_impl>; friend iteration_proxy_value<iter_impl>; using object_t = typename BasicJsonType::object_t; using array_t = typename BasicJsonType::array_t; // make sure BasicJsonType is basic_json or const basic_json static_assert(is_basic_json<typename std::remove_const<BasicJsonType>::type>::value, "iter_impl only accepts (const) basic_json"); public: /// The std::iterator class template (used as a base class to provide typedefs) is deprecated in C++17. /// The C++ Standard has never required user-defined iterators to derive from std::iterator. /// A user-defined iterator should provide publicly accessible typedefs named /// iterator_category, value_type, difference_type, pointer, and reference. /// Note that value_type is required to be non-const, even for constant iterators. using iterator_category = std::bidirectional_iterator_tag; /// the type of the values when the iterator is dereferenced using value_type = typename BasicJsonType::value_type; /// a type to represent differences between iterators using difference_type = typename BasicJsonType::difference_type; /// defines a pointer to the type iterated over (value_type) using pointer = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_pointer, typename BasicJsonType::pointer>::type; /// defines a reference to the type iterated over (value_type) using reference = typename std::conditional<std::is_const<BasicJsonType>::value, typename BasicJsonType::const_reference, typename BasicJsonType::reference>::type; /// default constructor iter_impl() = default; /*! @brief constructor for a given JSON instance @param[in] object pointer to a JSON object for this iterator @pre object != nullptr @post The iterator is initialized; i.e. `m_object != nullptr`. */ explicit iter_impl(pointer object) noexcept : m_object(object) { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = typename object_t::iterator(); break; } case value_t::array: { m_it.array_iterator = typename array_t::iterator(); break; } default: { m_it.primitive_iterator = primitive_iterator_t(); break; } } } /*! @note The conventional copy constructor and copy assignment are implicitly defined. Combined with the following converting constructor and assignment, they support: (1) copy from iterator to iterator, (2) copy from const iterator to const iterator, and (3) conversion from iterator to const iterator. However conversion from const iterator to iterator is not defined. */ /*! @brief converting constructor @param[in] other non-const iterator to copy from @note It is not checked whether @a other is initialized. */ iter_impl(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept : m_object(other.m_object), m_it(other.m_it) {} /*! @brief converting assignment @param[in,out] other non-const iterator to copy from @return const/non-const iterator @note It is not checked whether @a other is initialized. */ iter_impl& operator=(const iter_impl<typename std::remove_const<BasicJsonType>::type>& other) noexcept { m_object = other.m_object; m_it = other.m_it; return *this; } private: /*! @brief set the iterator to the first value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_begin() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->begin(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->begin(); break; } case value_t::null: { // set to end so begin()==end() is true: null is empty m_it.primitive_iterator.set_end(); break; } default: { m_it.primitive_iterator.set_begin(); break; } } } /*! @brief set the iterator past the last value @pre The iterator is initialized; i.e. `m_object != nullptr`. */ void set_end() noexcept { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { m_it.object_iterator = m_object->m_value.object->end(); break; } case value_t::array: { m_it.array_iterator = m_object->m_value.array->end(); break; } default: { m_it.primitive_iterator.set_end(); break; } } } public: /*! @brief return a reference to the value pointed to by the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator*() const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return m_it.object_iterator->second; } case value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return *m_it.array_iterator; } case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief dereference the iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ pointer operator->() const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { assert(m_it.object_iterator != m_object->m_value.object->end()); return &(m_it.object_iterator->second); } case value_t::array: { assert(m_it.array_iterator != m_object->m_value.array->end()); return &*m_it.array_iterator; } default: { if (JSON_LIKELY(m_it.primitive_iterator.is_begin())) { return m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief post-increment (it++) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator++(int) { auto result = *this; ++(*this); return result; } /*! @brief pre-increment (++it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator++() { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, 1); break; } case value_t::array: { std::advance(m_it.array_iterator, 1); break; } default: { ++m_it.primitive_iterator; break; } } return *this; } /*! @brief post-decrement (it--) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl const operator--(int) { auto result = *this; --(*this); return result; } /*! @brief pre-decrement (--it) @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator--() { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: { std::advance(m_it.object_iterator, -1); break; } case value_t::array: { std::advance(m_it.array_iterator, -1); break; } default: { --m_it.primitive_iterator; break; } } return *this; } /*! @brief comparison: equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator==(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: return (m_it.object_iterator == other.m_it.object_iterator); case value_t::array: return (m_it.array_iterator == other.m_it.array_iterator); default: return (m_it.primitive_iterator == other.m_it.primitive_iterator); } } /*! @brief comparison: not equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator!=(const iter_impl& other) const { return not operator==(other); } /*! @brief comparison: smaller @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<(const iter_impl& other) const { // if objects are not the same, the comparison is undefined if (JSON_UNLIKELY(m_object != other.m_object)) { JSON_THROW(invalid_iterator::create(212, "cannot compare iterators of different containers")); } assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(213, "cannot compare order of object iterators")); case value_t::array: return (m_it.array_iterator < other.m_it.array_iterator); default: return (m_it.primitive_iterator < other.m_it.primitive_iterator); } } /*! @brief comparison: less than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator<=(const iter_impl& other) const { return not other.operator < (*this); } /*! @brief comparison: greater than @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>(const iter_impl& other) const { return not operator<=(other); } /*! @brief comparison: greater than or equal @pre The iterator is initialized; i.e. `m_object != nullptr`. */ bool operator>=(const iter_impl& other) const { return not operator<(other); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator+=(difference_type i) { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: { std::advance(m_it.array_iterator, i); break; } default: { m_it.primitive_iterator += i; break; } } return *this; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl& operator-=(difference_type i) { return operator+=(-i); } /*! @brief add to iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator+(difference_type i) const { auto result = *this; result += i; return result; } /*! @brief addition of distance and iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ friend iter_impl operator+(difference_type i, const iter_impl& it) { auto result = it; result += i; return result; } /*! @brief subtract from iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ iter_impl operator-(difference_type i) const { auto result = *this; result -= i; return result; } /*! @brief return difference @pre The iterator is initialized; i.e. `m_object != nullptr`. */ difference_type operator-(const iter_impl& other) const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(209, "cannot use offsets with object iterators")); case value_t::array: return m_it.array_iterator - other.m_it.array_iterator; default: return m_it.primitive_iterator - other.m_it.primitive_iterator; } } /*! @brief access to successor @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference operator[](difference_type n) const { assert(m_object != nullptr); switch (m_object->m_type) { case value_t::object: JSON_THROW(invalid_iterator::create(208, "cannot use operator[] for object iterators")); case value_t::array: return *std::next(m_it.array_iterator, n); case value_t::null: JSON_THROW(invalid_iterator::create(214, "cannot get value")); default: { if (JSON_LIKELY(m_it.primitive_iterator.get_value() == -n)) { return *m_object; } JSON_THROW(invalid_iterator::create(214, "cannot get value")); } } } /*! @brief return the key of an object iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ const typename object_t::key_type& key() const { assert(m_object != nullptr); if (JSON_LIKELY(m_object->is_object())) { return m_it.object_iterator->first; } JSON_THROW(invalid_iterator::create(207, "cannot use key() for non-object iterators")); } /*! @brief return the value of an iterator @pre The iterator is initialized; i.e. `m_object != nullptr`. */ reference value() const { return operator*(); } private: /// associated JSON instance pointer m_object = nullptr; /// the actual iterator of the associated instance internal_iterator<typename std::remove_const<BasicJsonType>::type> m_it; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/iterators/iteration_proxy.hpp> // #include <nlohmann/detail/iterators/json_reverse_iterator.hpp> #include <cstddef> // ptrdiff_t #include <iterator> // reverse_iterator #include <utility> // declval namespace nlohmann { namespace detail { ////////////////////// // reverse_iterator // ////////////////////// /*! @brief a template for a reverse iterator class @tparam Base the base iterator type to reverse. Valid types are @ref iterator (to create @ref reverse_iterator) and @ref const_iterator (to create @ref const_reverse_iterator). @requirement The class satisfies the following concept requirements: - [BidirectionalIterator](https://en.cppreference.com/w/cpp/named_req/BidirectionalIterator): The iterator that can be moved can be moved in both directions (i.e. incremented and decremented). - [OutputIterator](https://en.cppreference.com/w/cpp/named_req/OutputIterator): It is possible to write to the pointed-to element (only if @a Base is @ref iterator). @since version 1.0.0 */ template<typename Base> class json_reverse_iterator : public std::reverse_iterator<Base> { public: using difference_type = std::ptrdiff_t; /// shortcut to the reverse iterator adapter using base_iterator = std::reverse_iterator<Base>; /// the reference type for the pointed-to element using reference = typename Base::reference; /// create reverse iterator from iterator explicit json_reverse_iterator(const typename base_iterator::iterator_type& it) noexcept : base_iterator(it) {} /// create reverse iterator from base class explicit json_reverse_iterator(const base_iterator& it) noexcept : base_iterator(it) {} /// post-increment (it++) json_reverse_iterator const operator++(int) { return static_cast<json_reverse_iterator>(base_iterator::operator++(1)); } /// pre-increment (++it) json_reverse_iterator& operator++() { return static_cast<json_reverse_iterator&>(base_iterator::operator++()); } /// post-decrement (it--) json_reverse_iterator const operator--(int) { return static_cast<json_reverse_iterator>(base_iterator::operator--(1)); } /// pre-decrement (--it) json_reverse_iterator& operator--() { return static_cast<json_reverse_iterator&>(base_iterator::operator--()); } /// add to iterator json_reverse_iterator& operator+=(difference_type i) { return static_cast<json_reverse_iterator&>(base_iterator::operator+=(i)); } /// add to iterator json_reverse_iterator operator+(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator+(i)); } /// subtract from iterator json_reverse_iterator operator-(difference_type i) const { return static_cast<json_reverse_iterator>(base_iterator::operator-(i)); } /// return difference difference_type operator-(const json_reverse_iterator& other) const { return base_iterator(*this) - base_iterator(other); } /// access to successor reference operator[](difference_type n) const { return *(this->operator+(n)); } /// return the key of an object iterator auto key() const -> decltype(std::declval<Base>().key()) { auto it = --this->base(); return it.key(); } /// return the value of an iterator reference value() const { auto it = --this->base(); return it.operator * (); } }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/output/output_adapters.hpp> #include <algorithm> // copy #include <cstddef> // size_t #include <ios> // streamsize #include <iterator> // back_inserter #include <memory> // shared_ptr, make_shared #include <ostream> // basic_ostream #include <string> // basic_string #include <vector> // vector namespace nlohmann { namespace detail { /// abstract output adapter interface template<typename CharType> struct output_adapter_protocol { virtual void write_character(CharType c) = 0; virtual void write_characters(const CharType* s, std::size_t length) = 0; virtual ~output_adapter_protocol() = default; }; /// a type to simplify interfaces template<typename CharType> using output_adapter_t = std::shared_ptr<output_adapter_protocol<CharType>>; /// output adapter for byte vectors template<typename CharType> class output_vector_adapter : public output_adapter_protocol<CharType> { public: explicit output_vector_adapter(std::vector<CharType>& vec) noexcept : v(vec) {} void write_character(CharType c) override { v.push_back(c); } void write_characters(const CharType* s, std::size_t length) override { std::copy(s, s + length, std::back_inserter(v)); } private: std::vector<CharType>& v; }; /// output adapter for output streams template<typename CharType> class output_stream_adapter : public output_adapter_protocol<CharType> { public: explicit output_stream_adapter(std::basic_ostream<CharType>& s) noexcept : stream(s) {} void write_character(CharType c) override { stream.put(c); } void write_characters(const CharType* s, std::size_t length) override { stream.write(s, static_cast<std::streamsize>(length)); } private: std::basic_ostream<CharType>& stream; }; /// output adapter for basic_string template<typename CharType, typename StringType = std::basic_string<CharType>> class output_string_adapter : public output_adapter_protocol<CharType> { public: explicit output_string_adapter(StringType& s) noexcept : str(s) {} void write_character(CharType c) override { str.push_back(c); } void write_characters(const CharType* s, std::size_t length) override { str.append(s, length); } private: StringType& str; }; template<typename CharType, typename StringType = std::basic_string<CharType>> class output_adapter { public: output_adapter(std::vector<CharType>& vec) : oa(std::make_shared<output_vector_adapter<CharType>>(vec)) {} output_adapter(std::basic_ostream<CharType>& s) : oa(std::make_shared<output_stream_adapter<CharType>>(s)) {} output_adapter(StringType& s) : oa(std::make_shared<output_string_adapter<CharType, StringType>>(s)) {} operator output_adapter_t<CharType>() { return oa; } private: output_adapter_t<CharType> oa = nullptr; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/input/binary_reader.hpp> #include <algorithm> // generate_n #include <array> // array #include <cassert> // assert #include <cmath> // ldexp #include <cstddef> // size_t #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t #include <cstdio> // snprintf #include <cstring> // memcpy #include <iterator> // back_inserter #include <limits> // numeric_limits #include <string> // char_traits, string #include <utility> // make_pair, move // #include <nlohmann/detail/input/input_adapters.hpp> // #include <nlohmann/detail/input/json_sax.hpp> // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/is_sax.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { /////////////////// // binary reader // /////////////////// /*! @brief deserialization of CBOR, MessagePack, and UBJSON values */ template<typename BasicJsonType, typename SAX = json_sax_dom_parser<BasicJsonType>> class binary_reader { using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; using number_float_t = typename BasicJsonType::number_float_t; using string_t = typename BasicJsonType::string_t; using json_sax_t = SAX; public: /*! @brief create a binary reader @param[in] adapter input adapter to read from */ explicit binary_reader(input_adapter_t adapter) : ia(std::move(adapter)) { (void)detail::is_sax_static_asserts<SAX, BasicJsonType> {}; assert(ia); } /*! @param[in] format the binary format to parse @param[in] sax_ a SAX event processor @param[in] strict whether to expect the input to be consumed completed @return */ bool sax_parse(const input_format_t format, json_sax_t* sax_, const bool strict = true) { sax = sax_; bool result = false; switch (format) { case input_format_t::bson: result = parse_bson_internal(); break; case input_format_t::cbor: result = parse_cbor_internal(); break; case input_format_t::msgpack: result = parse_msgpack_internal(); break; case input_format_t::ubjson: result = parse_ubjson_internal(); break; // LCOV_EXCL_START default: assert(false); // LCOV_EXCL_STOP } // strict mode: next byte must be EOF if (result and strict) { if (format == input_format_t::ubjson) { get_ignore_noop(); } else { get(); } if (JSON_UNLIKELY(current != std::char_traits<char>::eof())) { return sax->parse_error(chars_read, get_token_string(), parse_error::create(110, chars_read, exception_message(format, "expected end of input; last byte: 0x" + get_token_string(), "value"))); } } return result; } /*! @brief determine system byte order @return true if and only if system's byte order is little endian @note from http://stackoverflow.com/a/1001328/266378 */ static constexpr bool little_endianess(int num = 1) noexcept { return (*reinterpret_cast<char*>(&num) == 1); } private: ////////// // BSON // ////////// /*! @brief Reads in a BSON-object and passes it to the SAX-parser. @return whether a valid BSON-value was passed to the SAX parser */ bool parse_bson_internal() { std::int32_t document_size; get_number<std::int32_t, true>(input_format_t::bson, document_size); if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1)))) { return false; } if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/false))) { return false; } return sax->end_object(); } /*! @brief Parses a C-style string from the BSON input. @param[in, out] result A reference to the string variable where the read string is to be stored. @return `true` if the \x00-byte indicating the end of the string was encountered before the EOF; false` indicates an unexpected EOF. */ bool get_bson_cstr(string_t& result) { auto out = std::back_inserter(result); while (true) { get(); if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "cstring"))) { return false; } if (current == 0x00) { return true; } *out++ = static_cast<char>(current); } return true; } /*! @brief Parses a zero-terminated string of length @a len from the BSON input. @param[in] len The length (including the zero-byte at the end) of the string to be read. @param[in, out] result A reference to the string variable where the read string is to be stored. @tparam NumberType The type of the length @a len @pre len >= 1 @return `true` if the string was successfully parsed */ template<typename NumberType> bool get_bson_string(const NumberType len, string_t& result) { if (JSON_UNLIKELY(len < 1)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::bson, "string length must be at least 1, is " + std::to_string(len), "string"))); } return get_string(input_format_t::bson, len - static_cast<NumberType>(1), result) and get() != std::char_traits<char>::eof(); } /*! @brief Read a BSON document element of the given @a element_type. @param[in] element_type The BSON element type, c.f. http://bsonspec.org/spec.html @param[in] element_type_parse_position The position in the input stream, where the `element_type` was read. @warning Not all BSON element types are supported yet. An unsupported @a element_type will give rise to a parse_error.114: Unsupported BSON record type 0x... @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_internal(const int element_type, const std::size_t element_type_parse_position) { switch (element_type) { case 0x01: // double { double number; return get_number<double, true>(input_format_t::bson, number) and sax->number_float(static_cast<number_float_t>(number), ""); } case 0x02: // string { std::int32_t len; string_t value; return get_number<std::int32_t, true>(input_format_t::bson, len) and get_bson_string(len, value) and sax->string(value); } case 0x03: // object { return parse_bson_internal(); } case 0x04: // array { return parse_bson_array(); } case 0x08: // boolean { return sax->boolean(get() != 0); } case 0x0A: // null { return sax->null(); } case 0x10: // int32 { std::int32_t value; return get_number<std::int32_t, true>(input_format_t::bson, value) and sax->number_integer(value); } case 0x12: // int64 { std::int64_t value; return get_number<std::int64_t, true>(input_format_t::bson, value) and sax->number_integer(value); } default: // anything else not supported (yet) { char cr[3]; (std::snprintf)(cr, sizeof(cr), "%.2hhX", static_cast<unsigned char>(element_type)); return sax->parse_error(element_type_parse_position, std::string(cr), parse_error::create(114, element_type_parse_position, "Unsupported BSON record type 0x" + std::string(cr))); } } } /*! @brief Read a BSON element list (as specified in the BSON-spec) The same binary layout is used for objects and arrays, hence it must be indicated with the argument @a is_array which one is expected (true --> array, false --> object). @param[in] is_array Determines if the element list being read is to be treated as an object (@a is_array == false), or as an array (@a is_array == true). @return whether a valid BSON-object/array was passed to the SAX parser */ bool parse_bson_element_list(const bool is_array) { string_t key; while (int element_type = get()) { if (JSON_UNLIKELY(not unexpect_eof(input_format_t::bson, "element list"))) { return false; } const std::size_t element_type_parse_position = chars_read; if (JSON_UNLIKELY(not get_bson_cstr(key))) { return false; } if (not is_array) { if (not sax->key(key)) { return false; } } if (JSON_UNLIKELY(not parse_bson_element_internal(element_type, element_type_parse_position))) { return false; } // get_bson_cstr only appends key.clear(); } return true; } /*! @brief Reads an array from the BSON input and passes it to the SAX-parser. @return whether a valid BSON-array was passed to the SAX parser */ bool parse_bson_array() { std::int32_t document_size; get_number<std::int32_t, true>(input_format_t::bson, document_size); if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1)))) { return false; } if (JSON_UNLIKELY(not parse_bson_element_list(/*is_array*/true))) { return false; } return sax->end_array(); } ////////// // CBOR // ////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether a valid CBOR value was passed to the SAX parser */ bool parse_cbor_internal(const bool get_char = true) { switch (get_char ? get() : current) { // EOF case std::char_traits<char>::eof(): return unexpect_eof(input_format_t::cbor, "value"); // Integer 0x00..0x17 (0..23) case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: return sax->number_unsigned(static_cast<number_unsigned_t>(current)); case 0x18: // Unsigned integer (one-byte uint8_t follows) { uint8_t number; return get_number(input_format_t::cbor, number) and sax->number_unsigned(number); } case 0x19: // Unsigned integer (two-byte uint16_t follows) { uint16_t number; return get_number(input_format_t::cbor, number) and sax->number_unsigned(number); } case 0x1A: // Unsigned integer (four-byte uint32_t follows) { uint32_t number; return get_number(input_format_t::cbor, number) and sax->number_unsigned(number); } case 0x1B: // Unsigned integer (eight-byte uint64_t follows) { uint64_t number; return get_number(input_format_t::cbor, number) and sax->number_unsigned(number); } // Negative integer -1-0x00..-1-0x17 (-1..-24) case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: return sax->number_integer(static_cast<int8_t>(0x20 - 1 - current)); case 0x38: // Negative integer (one-byte uint8_t follows) { uint8_t number; return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number); } case 0x39: // Negative integer -1-n (two-byte uint16_t follows) { uint16_t number; return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number); } case 0x3A: // Negative integer -1-n (four-byte uint32_t follows) { uint32_t number; return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - number); } case 0x3B: // Negative integer -1-n (eight-byte uint64_t follows) { uint64_t number; return get_number(input_format_t::cbor, number) and sax->number_integer(static_cast<number_integer_t>(-1) - static_cast<number_integer_t>(number)); } // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: // UTF-8 string (one-byte uint8_t for n follows) case 0x79: // UTF-8 string (two-byte uint16_t for n follow) case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) case 0x7F: // UTF-8 string (indefinite length) { string_t s; return get_cbor_string(s) and sax->string(s); } // array (0x00..0x17 data items follow) case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: return get_cbor_array(static_cast<std::size_t>(current & 0x1F)); case 0x98: // array (one-byte uint8_t for n follows) { uint8_t len; return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len)); } case 0x99: // array (two-byte uint16_t for n follow) { uint16_t len; return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len)); } case 0x9A: // array (four-byte uint32_t for n follow) { uint32_t len; return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len)); } case 0x9B: // array (eight-byte uint64_t for n follow) { uint64_t len; return get_number(input_format_t::cbor, len) and get_cbor_array(static_cast<std::size_t>(len)); } case 0x9F: // array (indefinite length) return get_cbor_array(std::size_t(-1)); // map (0x00..0x17 pairs of data items follow) case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: return get_cbor_object(static_cast<std::size_t>(current & 0x1F)); case 0xB8: // map (one-byte uint8_t for n follows) { uint8_t len; return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len)); } case 0xB9: // map (two-byte uint16_t for n follow) { uint16_t len; return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len)); } case 0xBA: // map (four-byte uint32_t for n follow) { uint32_t len; return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len)); } case 0xBB: // map (eight-byte uint64_t for n follow) { uint64_t len; return get_number(input_format_t::cbor, len) and get_cbor_object(static_cast<std::size_t>(len)); } case 0xBF: // map (indefinite length) return get_cbor_object(std::size_t(-1)); case 0xF4: // false return sax->boolean(false); case 0xF5: // true return sax->boolean(true); case 0xF6: // null return sax->null(); case 0xF9: // Half-Precision Float (two-byte IEEE 754) { const int byte1_raw = get(); if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number"))) { return false; } const int byte2_raw = get(); if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "number"))) { return false; } const auto byte1 = static_cast<unsigned char>(byte1_raw); const auto byte2 = static_cast<unsigned char>(byte2_raw); // code from RFC 7049, Appendix D, Figure 3: // As half-precision floating-point numbers were only added // to IEEE 754 in 2008, today's programming platforms often // still only have limited support for them. It is very // easy to include at least decoding support for them even // without such support. An example of a small decoder for // half-precision floating-point numbers in the C language // is shown in Fig. 3. const int half = (byte1 << 8) + byte2; const double val = [&half] { const int exp = (half >> 10) & 0x1F; const int mant = half & 0x3FF; assert(0 <= exp and exp <= 32); assert(0 <= mant and mant <= 1024); switch (exp) { case 0: return std::ldexp(mant, -24); case 31: return (mant == 0) ? std::numeric_limits<double>::infinity() : std::numeric_limits<double>::quiet_NaN(); default: return std::ldexp(mant + 1024, exp - 25); } }(); return sax->number_float((half & 0x8000) != 0 ? static_cast<number_float_t>(-val) : static_cast<number_float_t>(val), ""); } case 0xFA: // Single-Precision Float (four-byte IEEE 754) { float number; return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), ""); } case 0xFB: // Double-Precision Float (eight-byte IEEE 754) { double number; return get_number(input_format_t::cbor, number) and sax->number_float(static_cast<number_float_t>(number), ""); } default: // anything else (0xFF is handled inside the other types) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::cbor, "invalid byte: 0x" + last_token, "value"))); } } } /*! @brief reads a CBOR string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. Additionally, CBOR's strings with indefinite lengths are supported. @param[out] result created string @return whether string creation completed */ bool get_cbor_string(string_t& result) { if (JSON_UNLIKELY(not unexpect_eof(input_format_t::cbor, "string"))) { return false; } switch (current) { // UTF-8 string (0x00..0x17 bytes follow) case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: { return get_string(input_format_t::cbor, current & 0x1F, result); } case 0x78: // UTF-8 string (one-byte uint8_t for n follows) { uint8_t len; return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result); } case 0x79: // UTF-8 string (two-byte uint16_t for n follow) { uint16_t len; return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result); } case 0x7A: // UTF-8 string (four-byte uint32_t for n follow) { uint32_t len; return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result); } case 0x7B: // UTF-8 string (eight-byte uint64_t for n follow) { uint64_t len; return get_number(input_format_t::cbor, len) and get_string(input_format_t::cbor, len, result); } case 0x7F: // UTF-8 string (indefinite length) { while (get() != 0xFF) { string_t chunk; if (not get_cbor_string(chunk)) { return false; } result.append(chunk); } return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::cbor, "expected length specification (0x60-0x7B) or indefinite string type (0x7F); last byte: 0x" + last_token, "string"))); } } } /*! @param[in] len the length of the array or std::size_t(-1) for an array of indefinite size @return whether array creation completed */ bool get_cbor_array(const std::size_t len) { if (JSON_UNLIKELY(not sax->start_array(len))) { return false; } if (len != std::size_t(-1)) { for (std::size_t i = 0; i < len; ++i) { if (JSON_UNLIKELY(not parse_cbor_internal())) { return false; } } } else { while (get() != 0xFF) { if (JSON_UNLIKELY(not parse_cbor_internal(false))) { return false; } } } return sax->end_array(); } /*! @param[in] len the length of the object or std::size_t(-1) for an object of indefinite size @return whether object creation completed */ bool get_cbor_object(const std::size_t len) { if (JSON_UNLIKELY(not sax->start_object(len))) { return false; } string_t key; if (len != std::size_t(-1)) { for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key))) { return false; } if (JSON_UNLIKELY(not parse_cbor_internal())) { return false; } key.clear(); } } else { while (get() != 0xFF) { if (JSON_UNLIKELY(not get_cbor_string(key) or not sax->key(key))) { return false; } if (JSON_UNLIKELY(not parse_cbor_internal())) { return false; } key.clear(); } } return sax->end_object(); } ///////////// // MsgPack // ///////////// /*! @return whether a valid MessagePack value was passed to the SAX parser */ bool parse_msgpack_internal() { switch (get()) { // EOF case std::char_traits<char>::eof(): return unexpect_eof(input_format_t::msgpack, "value"); // positive fixint case 0x00: case 0x01: case 0x02: case 0x03: case 0x04: case 0x05: case 0x06: case 0x07: case 0x08: case 0x09: case 0x0A: case 0x0B: case 0x0C: case 0x0D: case 0x0E: case 0x0F: case 0x10: case 0x11: case 0x12: case 0x13: case 0x14: case 0x15: case 0x16: case 0x17: case 0x18: case 0x19: case 0x1A: case 0x1B: case 0x1C: case 0x1D: case 0x1E: case 0x1F: case 0x20: case 0x21: case 0x22: case 0x23: case 0x24: case 0x25: case 0x26: case 0x27: case 0x28: case 0x29: case 0x2A: case 0x2B: case 0x2C: case 0x2D: case 0x2E: case 0x2F: case 0x30: case 0x31: case 0x32: case 0x33: case 0x34: case 0x35: case 0x36: case 0x37: case 0x38: case 0x39: case 0x3A: case 0x3B: case 0x3C: case 0x3D: case 0x3E: case 0x3F: case 0x40: case 0x41: case 0x42: case 0x43: case 0x44: case 0x45: case 0x46: case 0x47: case 0x48: case 0x49: case 0x4A: case 0x4B: case 0x4C: case 0x4D: case 0x4E: case 0x4F: case 0x50: case 0x51: case 0x52: case 0x53: case 0x54: case 0x55: case 0x56: case 0x57: case 0x58: case 0x59: case 0x5A: case 0x5B: case 0x5C: case 0x5D: case 0x5E: case 0x5F: case 0x60: case 0x61: case 0x62: case 0x63: case 0x64: case 0x65: case 0x66: case 0x67: case 0x68: case 0x69: case 0x6A: case 0x6B: case 0x6C: case 0x6D: case 0x6E: case 0x6F: case 0x70: case 0x71: case 0x72: case 0x73: case 0x74: case 0x75: case 0x76: case 0x77: case 0x78: case 0x79: case 0x7A: case 0x7B: case 0x7C: case 0x7D: case 0x7E: case 0x7F: return sax->number_unsigned(static_cast<number_unsigned_t>(current)); // fixmap case 0x80: case 0x81: case 0x82: case 0x83: case 0x84: case 0x85: case 0x86: case 0x87: case 0x88: case 0x89: case 0x8A: case 0x8B: case 0x8C: case 0x8D: case 0x8E: case 0x8F: return get_msgpack_object(static_cast<std::size_t>(current & 0x0F)); // fixarray case 0x90: case 0x91: case 0x92: case 0x93: case 0x94: case 0x95: case 0x96: case 0x97: case 0x98: case 0x99: case 0x9A: case 0x9B: case 0x9C: case 0x9D: case 0x9E: case 0x9F: return get_msgpack_array(static_cast<std::size_t>(current & 0x0F)); // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: { string_t s; return get_msgpack_string(s) and sax->string(s); } case 0xC0: // nil return sax->null(); case 0xC2: // false return sax->boolean(false); case 0xC3: // true return sax->boolean(true); case 0xCA: // float 32 { float number; return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), ""); } case 0xCB: // float 64 { double number; return get_number(input_format_t::msgpack, number) and sax->number_float(static_cast<number_float_t>(number), ""); } case 0xCC: // uint 8 { uint8_t number; return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number); } case 0xCD: // uint 16 { uint16_t number; return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number); } case 0xCE: // uint 32 { uint32_t number; return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number); } case 0xCF: // uint 64 { uint64_t number; return get_number(input_format_t::msgpack, number) and sax->number_unsigned(number); } case 0xD0: // int 8 { int8_t number; return get_number(input_format_t::msgpack, number) and sax->number_integer(number); } case 0xD1: // int 16 { int16_t number; return get_number(input_format_t::msgpack, number) and sax->number_integer(number); } case 0xD2: // int 32 { int32_t number; return get_number(input_format_t::msgpack, number) and sax->number_integer(number); } case 0xD3: // int 64 { int64_t number; return get_number(input_format_t::msgpack, number) and sax->number_integer(number); } case 0xD9: // str 8 case 0xDA: // str 16 case 0xDB: // str 32 { string_t s; return get_msgpack_string(s) and sax->string(s); } case 0xDC: // array 16 { uint16_t len; return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len)); } case 0xDD: // array 32 { uint32_t len; return get_number(input_format_t::msgpack, len) and get_msgpack_array(static_cast<std::size_t>(len)); } case 0xDE: // map 16 { uint16_t len; return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len)); } case 0xDF: // map 32 { uint32_t len; return get_number(input_format_t::msgpack, len) and get_msgpack_object(static_cast<std::size_t>(len)); } // negative fixint case 0xE0: case 0xE1: case 0xE2: case 0xE3: case 0xE4: case 0xE5: case 0xE6: case 0xE7: case 0xE8: case 0xE9: case 0xEA: case 0xEB: case 0xEC: case 0xED: case 0xEE: case 0xEF: case 0xF0: case 0xF1: case 0xF2: case 0xF3: case 0xF4: case 0xF5: case 0xF6: case 0xF7: case 0xF8: case 0xF9: case 0xFA: case 0xFB: case 0xFC: case 0xFD: case 0xFE: case 0xFF: return sax->number_integer(static_cast<int8_t>(current)); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::msgpack, "invalid byte: 0x" + last_token, "value"))); } } } /*! @brief reads a MessagePack string This function first reads starting bytes to determine the expected string length and then copies this number of bytes into a string. @param[out] result created string @return whether string creation completed */ bool get_msgpack_string(string_t& result) { if (JSON_UNLIKELY(not unexpect_eof(input_format_t::msgpack, "string"))) { return false; } switch (current) { // fixstr case 0xA0: case 0xA1: case 0xA2: case 0xA3: case 0xA4: case 0xA5: case 0xA6: case 0xA7: case 0xA8: case 0xA9: case 0xAA: case 0xAB: case 0xAC: case 0xAD: case 0xAE: case 0xAF: case 0xB0: case 0xB1: case 0xB2: case 0xB3: case 0xB4: case 0xB5: case 0xB6: case 0xB7: case 0xB8: case 0xB9: case 0xBA: case 0xBB: case 0xBC: case 0xBD: case 0xBE: case 0xBF: { return get_string(input_format_t::msgpack, current & 0x1F, result); } case 0xD9: // str 8 { uint8_t len; return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result); } case 0xDA: // str 16 { uint16_t len; return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result); } case 0xDB: // str 32 { uint32_t len; return get_number(input_format_t::msgpack, len) and get_string(input_format_t::msgpack, len, result); } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::msgpack, "expected length specification (0xA0-0xBF, 0xD9-0xDB); last byte: 0x" + last_token, "string"))); } } } /*! @param[in] len the length of the array @return whether array creation completed */ bool get_msgpack_array(const std::size_t len) { if (JSON_UNLIKELY(not sax->start_array(len))) { return false; } for (std::size_t i = 0; i < len; ++i) { if (JSON_UNLIKELY(not parse_msgpack_internal())) { return false; } } return sax->end_array(); } /*! @param[in] len the length of the object @return whether object creation completed */ bool get_msgpack_object(const std::size_t len) { if (JSON_UNLIKELY(not sax->start_object(len))) { return false; } string_t key; for (std::size_t i = 0; i < len; ++i) { get(); if (JSON_UNLIKELY(not get_msgpack_string(key) or not sax->key(key))) { return false; } if (JSON_UNLIKELY(not parse_msgpack_internal())) { return false; } key.clear(); } return sax->end_object(); } //////////// // UBJSON // //////////// /*! @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether a valid UBJSON value was passed to the SAX parser */ bool parse_ubjson_internal(const bool get_char = true) { return get_ubjson_value(get_char ? get_ignore_noop() : current); } /*! @brief reads a UBJSON string This function is either called after reading the 'S' byte explicitly indicating a string, or in case of an object key where the 'S' byte can be left out. @param[out] result created string @param[in] get_char whether a new character should be retrieved from the input (true, default) or whether the last read character should be considered instead @return whether string creation completed */ bool get_ubjson_string(string_t& result, const bool get_char = true) { if (get_char) { get(); // TODO: may we ignore N here? } if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value"))) { return false; } switch (current) { case 'U': { uint8_t len; return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result); } case 'i': { int8_t len; return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result); } case 'I': { int16_t len; return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result); } case 'l': { int32_t len; return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result); } case 'L': { int64_t len; return get_number(input_format_t::ubjson, len) and get_string(input_format_t::ubjson, len, result); } default: auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L); last byte: 0x" + last_token, "string"))); } } /*! @param[out] result determined size @return whether size determination completed */ bool get_ubjson_size_value(std::size_t& result) { switch (get_ignore_noop()) { case 'U': { uint8_t number; if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } case 'i': { int8_t number; if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } case 'I': { int16_t number; if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } case 'l': { int32_t number; if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } case 'L': { int64_t number; if (JSON_UNLIKELY(not get_number(input_format_t::ubjson, number))) { return false; } result = static_cast<std::size_t>(number); return true; } default: { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "expected length type specification (U, i, I, l, L) after '#'; last byte: 0x" + last_token, "size"))); } } } /*! @brief determine the type and size for a container In the optimized UBJSON format, a type and a size can be provided to allow for a more compact representation. @param[out] result pair of the size and the type @return whether pair creation completed */ bool get_ubjson_size_type(std::pair<std::size_t, int>& result) { result.first = string_t::npos; // size result.second = 0; // type get_ignore_noop(); if (current == '$') { result.second = get(); // must not ignore 'N', because 'N' maybe the type if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "type"))) { return false; } get_ignore_noop(); if (JSON_UNLIKELY(current != '#')) { if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "value"))) { return false; } auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "expected '#' after type information; last byte: 0x" + last_token, "size"))); } return get_ubjson_size_value(result.first); } else if (current == '#') { return get_ubjson_size_value(result.first); } return true; } /*! @param prefix the previously read or set type prefix @return whether value creation completed */ bool get_ubjson_value(const int prefix) { switch (prefix) { case std::char_traits<char>::eof(): // EOF return unexpect_eof(input_format_t::ubjson, "value"); case 'T': // true return sax->boolean(true); case 'F': // false return sax->boolean(false); case 'Z': // null return sax->null(); case 'U': { uint8_t number; return get_number(input_format_t::ubjson, number) and sax->number_unsigned(number); } case 'i': { int8_t number; return get_number(input_format_t::ubjson, number) and sax->number_integer(number); } case 'I': { int16_t number; return get_number(input_format_t::ubjson, number) and sax->number_integer(number); } case 'l': { int32_t number; return get_number(input_format_t::ubjson, number) and sax->number_integer(number); } case 'L': { int64_t number; return get_number(input_format_t::ubjson, number) and sax->number_integer(number); } case 'd': { float number; return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), ""); } case 'D': { double number; return get_number(input_format_t::ubjson, number) and sax->number_float(static_cast<number_float_t>(number), ""); } case 'C': // char { get(); if (JSON_UNLIKELY(not unexpect_eof(input_format_t::ubjson, "char"))) { return false; } if (JSON_UNLIKELY(current > 127)) { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(113, chars_read, exception_message(input_format_t::ubjson, "byte after 'C' must be in range 0x00..0x7F; last byte: 0x" + last_token, "char"))); } string_t s(1, static_cast<char>(current)); return sax->string(s); } case 'S': // string { string_t s; return get_ubjson_string(s) and sax->string(s); } case '[': // array return get_ubjson_array(); case '{': // object return get_ubjson_object(); default: // anything else { auto last_token = get_token_string(); return sax->parse_error(chars_read, last_token, parse_error::create(112, chars_read, exception_message(input_format_t::ubjson, "invalid byte: 0x" + last_token, "value"))); } } } /*! @return whether array creation completed */ bool get_ubjson_array() { std::pair<std::size_t, int> size_and_type; if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type))) { return false; } if (size_and_type.first != string_t::npos) { if (JSON_UNLIKELY(not sax->start_array(size_and_type.first))) { return false; } if (size_and_type.second != 0) { if (size_and_type.second != 'N') { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second))) { return false; } } } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_UNLIKELY(not parse_ubjson_internal())) { return false; } } } } else { if (JSON_UNLIKELY(not sax->start_array(std::size_t(-1)))) { return false; } while (current != ']') { if (JSON_UNLIKELY(not parse_ubjson_internal(false))) { return false; } get_ignore_noop(); } } return sax->end_array(); } /*! @return whether object creation completed */ bool get_ubjson_object() { std::pair<std::size_t, int> size_and_type; if (JSON_UNLIKELY(not get_ubjson_size_type(size_and_type))) { return false; } string_t key; if (size_and_type.first != string_t::npos) { if (JSON_UNLIKELY(not sax->start_object(size_and_type.first))) { return false; } if (size_and_type.second != 0) { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key))) { return false; } if (JSON_UNLIKELY(not get_ubjson_value(size_and_type.second))) { return false; } key.clear(); } } else { for (std::size_t i = 0; i < size_and_type.first; ++i) { if (JSON_UNLIKELY(not get_ubjson_string(key) or not sax->key(key))) { return false; } if (JSON_UNLIKELY(not parse_ubjson_internal())) { return false; } key.clear(); } } } else { if (JSON_UNLIKELY(not sax->start_object(std::size_t(-1)))) { return false; } while (current != '}') { if (JSON_UNLIKELY(not get_ubjson_string(key, false) or not sax->key(key))) { return false; } if (JSON_UNLIKELY(not parse_ubjson_internal())) { return false; } get_ignore_noop(); key.clear(); } } return sax->end_object(); } /////////////////////// // Utility functions // /////////////////////// /*! @brief get next character from the input This function provides the interface to the used input adapter. It does not throw in case the input reached EOF, but returns a -'ve valued `std::char_traits<char>::eof()` in that case. @return character read from the input */ int get() { ++chars_read; return (current = ia->get_character()); } /*! @return character read from the input after ignoring all 'N' entries */ int get_ignore_noop() { do { get(); } while (current == 'N'); return current; } /* @brief read a number from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[out] result number of type @a NumberType @return whether conversion completed @note This function needs to respect the system's endianess, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template<typename NumberType, bool InputIsLittleEndian = false> bool get_number(const input_format_t format, NumberType& result) { // step 1: read input into array with system's byte order std::array<uint8_t, sizeof(NumberType)> vec; for (std::size_t i = 0; i < sizeof(NumberType); ++i) { get(); if (JSON_UNLIKELY(not unexpect_eof(format, "number"))) { return false; } // reverse byte order prior to conversion if necessary if (is_little_endian && !InputIsLittleEndian) { vec[sizeof(NumberType) - i - 1] = static_cast<uint8_t>(current); } else { vec[i] = static_cast<uint8_t>(current); // LCOV_EXCL_LINE } } // step 2: convert array into number of type T and return std::memcpy(&result, vec.data(), sizeof(NumberType)); return true; } /*! @brief create a string by reading characters from the input @tparam NumberType the type of the number @param[in] format the current format (for diagnostics) @param[in] len number of characters to read @param[out] result string created by reading @a len bytes @return whether string creation completed @note We can not reserve @a len bytes for the result, because @a len may be too large. Usually, @ref unexpect_eof() detects the end of the input before we run out of string memory. */ template<typename NumberType> bool get_string(const input_format_t format, const NumberType len, string_t& result) { bool success = true; std::generate_n(std::back_inserter(result), len, [this, &success, &format]() { get(); if (JSON_UNLIKELY(not unexpect_eof(format, "string"))) { success = false; } return static_cast<char>(current); }); return success; } /*! @param[in] format the current format (for diagnostics) @param[in] context further context information (for diagnostics) @return whether the last read character is not EOF */ bool unexpect_eof(const input_format_t format, const char* context) const { if (JSON_UNLIKELY(current == std::char_traits<char>::eof())) { return sax->parse_error(chars_read, "<end of file>", parse_error::create(110, chars_read, exception_message(format, "unexpected end of input", context))); } return true; } /*! @return a string representation of the last read byte */ std::string get_token_string() const { char cr[3]; (std::snprintf)(cr, 3, "%.2hhX", static_cast<unsigned char>(current)); return std::string{cr}; } /*! @param[in] format the current format @param[in] detail a detailed error message @param[in] context further contect information @return a message string to use in the parse_error exceptions */ std::string exception_message(const input_format_t format, const std::string& detail, const std::string& context) const { std::string error_msg = "syntax error while parsing "; switch (format) { case input_format_t::cbor: error_msg += "CBOR"; break; case input_format_t::msgpack: error_msg += "MessagePack"; break; case input_format_t::ubjson: error_msg += "UBJSON"; break; case input_format_t::bson: error_msg += "BSON"; break; // LCOV_EXCL_START default: assert(false); // LCOV_EXCL_STOP } return error_msg + " " + context + ": " + detail; } private: /// input adapter input_adapter_t ia = nullptr; /// the current character int current = std::char_traits<char>::eof(); /// the number of characters read std::size_t chars_read = 0; /// whether we can assume little endianess const bool is_little_endian = little_endianess(); /// the SAX parser json_sax_t* sax = nullptr; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/output/binary_writer.hpp> #include <algorithm> // reverse #include <array> // array #include <cstdint> // uint8_t, uint16_t, uint32_t, uint64_t #include <cstring> // memcpy #include <limits> // numeric_limits // #include <nlohmann/detail/input/binary_reader.hpp> // #include <nlohmann/detail/output/output_adapters.hpp> namespace nlohmann { namespace detail { /////////////////// // binary writer // /////////////////// /*! @brief serialization to CBOR and MessagePack values */ template<typename BasicJsonType, typename CharType> class binary_writer { using string_t = typename BasicJsonType::string_t; public: /*! @brief create a binary writer @param[in] adapter output adapter to write to */ explicit binary_writer(output_adapter_t<CharType> adapter) : oa(adapter) { assert(oa); } /*! @param[in] j JSON value to serialize @pre j.type() == value_t::object */ void write_bson(const BasicJsonType& j) { switch (j.type()) { case value_t::object: { write_bson_object(*j.m_value.object); break; } default: { JSON_THROW(type_error::create(317, "to serialize to BSON, top-level type must be object, but is " + std::string(j.type_name()))); } } } /*! @param[in] j JSON value to serialize */ void write_cbor(const BasicJsonType& j) { switch (j.type()) { case value_t::null: { oa->write_character(to_char_type(0xF6)); break; } case value_t::boolean: { oa->write_character(j.m_value.boolean ? to_char_type(0xF5) : to_char_type(0xF4)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // CBOR does not differentiate between positive signed // integers and unsigned integers. Therefore, we used the // code from the value_t::number_unsigned case here. if (j.m_value.number_integer <= 0x17) { write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } } else { // The conversions below encode the sign in the first // byte, and the value is converted to a positive number. const auto positive_number = -1 - j.m_value.number_integer; if (j.m_value.number_integer >= -24) { write_number(static_cast<uint8_t>(0x20 + positive_number)); } else if (positive_number <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(to_char_type(0x38)); write_number(static_cast<uint8_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(to_char_type(0x39)); write_number(static_cast<uint16_t>(positive_number)); } else if (positive_number <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(to_char_type(0x3A)); write_number(static_cast<uint32_t>(positive_number)); } else { oa->write_character(to_char_type(0x3B)); write_number(static_cast<uint64_t>(positive_number)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= 0x17) { write_number(static_cast<uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(to_char_type(0x18)); write_number(static_cast<uint8_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(to_char_type(0x19)); write_number(static_cast<uint16_t>(j.m_value.number_unsigned)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(to_char_type(0x1A)); write_number(static_cast<uint32_t>(j.m_value.number_unsigned)); } else { oa->write_character(to_char_type(0x1B)); write_number(static_cast<uint64_t>(j.m_value.number_unsigned)); } break; } case value_t::number_float: { oa->write_character(get_cbor_float_prefix(j.m_value.number_float)); write_number(j.m_value.number_float); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0x60 + N)); } else if (N <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(to_char_type(0x78)); write_number(static_cast<uint8_t>(N)); } else if (N <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(to_char_type(0x79)); write_number(static_cast<uint16_t>(N)); } else if (N <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(to_char_type(0x7A)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<uint64_t>::max)()) { oa->write_character(to_char_type(0x7B)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0x80 + N)); } else if (N <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(to_char_type(0x98)); write_number(static_cast<uint8_t>(N)); } else if (N <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(to_char_type(0x99)); write_number(static_cast<uint16_t>(N)); } else if (N <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(to_char_type(0x9A)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<uint64_t>::max)()) { oa->write_character(to_char_type(0x9B)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.array) { write_cbor(el); } break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 0x17) { write_number(static_cast<uint8_t>(0xA0 + N)); } else if (N <= (std::numeric_limits<uint8_t>::max)()) { oa->write_character(to_char_type(0xB8)); write_number(static_cast<uint8_t>(N)); } else if (N <= (std::numeric_limits<uint16_t>::max)()) { oa->write_character(to_char_type(0xB9)); write_number(static_cast<uint16_t>(N)); } else if (N <= (std::numeric_limits<uint32_t>::max)()) { oa->write_character(to_char_type(0xBA)); write_number(static_cast<uint32_t>(N)); } // LCOV_EXCL_START else if (N <= (std::numeric_limits<uint64_t>::max)()) { oa->write_character(to_char_type(0xBB)); write_number(static_cast<uint64_t>(N)); } // LCOV_EXCL_STOP // step 2: write each element for (const auto& el : *j.m_value.object) { write_cbor(el.first); write_cbor(el.second); } break; } default: break; } } /*! @param[in] j JSON value to serialize */ void write_msgpack(const BasicJsonType& j) { switch (j.type()) { case value_t::null: // nil { oa->write_character(to_char_type(0xC0)); break; } case value_t::boolean: // true and false { oa->write_character(j.m_value.boolean ? to_char_type(0xC3) : to_char_type(0xC2)); break; } case value_t::number_integer: { if (j.m_value.number_integer >= 0) { // MessagePack does not differentiate between positive // signed integers and unsigned integers. Therefore, we used // the code from the value_t::number_unsigned case here. if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } } else { if (j.m_value.number_integer >= -32) { // negative fixnum write_number(static_cast<int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int8_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)()) { // int 8 oa->write_character(to_char_type(0xD0)); write_number(static_cast<int8_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int16_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)()) { // int 16 oa->write_character(to_char_type(0xD1)); write_number(static_cast<int16_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int32_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)()) { // int 32 oa->write_character(to_char_type(0xD2)); write_number(static_cast<int32_t>(j.m_value.number_integer)); } else if (j.m_value.number_integer >= (std::numeric_limits<int64_t>::min)() and j.m_value.number_integer <= (std::numeric_limits<int64_t>::max)()) { // int 64 oa->write_character(to_char_type(0xD3)); write_number(static_cast<int64_t>(j.m_value.number_integer)); } } break; } case value_t::number_unsigned: { if (j.m_value.number_unsigned < 128) { // positive fixnum write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { // uint 8 oa->write_character(to_char_type(0xCC)); write_number(static_cast<uint8_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint16_t>::max)()) { // uint 16 oa->write_character(to_char_type(0xCD)); write_number(static_cast<uint16_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint32_t>::max)()) { // uint 32 oa->write_character(to_char_type(0xCE)); write_number(static_cast<uint32_t>(j.m_value.number_integer)); } else if (j.m_value.number_unsigned <= (std::numeric_limits<uint64_t>::max)()) { // uint 64 oa->write_character(to_char_type(0xCF)); write_number(static_cast<uint64_t>(j.m_value.number_integer)); } break; } case value_t::number_float: { oa->write_character(get_msgpack_float_prefix(j.m_value.number_float)); write_number(j.m_value.number_float); break; } case value_t::string: { // step 1: write control byte and the string length const auto N = j.m_value.string->size(); if (N <= 31) { // fixstr write_number(static_cast<uint8_t>(0xA0 | N)); } else if (N <= (std::numeric_limits<uint8_t>::max)()) { // str 8 oa->write_character(to_char_type(0xD9)); write_number(static_cast<uint8_t>(N)); } else if (N <= (std::numeric_limits<uint16_t>::max)()) { // str 16 oa->write_character(to_char_type(0xDA)); write_number(static_cast<uint16_t>(N)); } else if (N <= (std::numeric_limits<uint32_t>::max)()) { // str 32 oa->write_character(to_char_type(0xDB)); write_number(static_cast<uint32_t>(N)); } // step 2: write the string oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { // step 1: write control byte and the array size const auto N = j.m_value.array->size(); if (N <= 15) { // fixarray write_number(static_cast<uint8_t>(0x90 | N)); } else if (N <= (std::numeric_limits<uint16_t>::max)()) { // array 16 oa->write_character(to_char_type(0xDC)); write_number(static_cast<uint16_t>(N)); } else if (N <= (std::numeric_limits<uint32_t>::max)()) { // array 32 oa->write_character(to_char_type(0xDD)); write_number(static_cast<uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.array) { write_msgpack(el); } break; } case value_t::object: { // step 1: write control byte and the object size const auto N = j.m_value.object->size(); if (N <= 15) { // fixmap write_number(static_cast<uint8_t>(0x80 | (N & 0xF))); } else if (N <= (std::numeric_limits<uint16_t>::max)()) { // map 16 oa->write_character(to_char_type(0xDE)); write_number(static_cast<uint16_t>(N)); } else if (N <= (std::numeric_limits<uint32_t>::max)()) { // map 32 oa->write_character(to_char_type(0xDF)); write_number(static_cast<uint32_t>(N)); } // step 2: write each element for (const auto& el : *j.m_value.object) { write_msgpack(el.first); write_msgpack(el.second); } break; } default: break; } } /*! @param[in] j JSON value to serialize @param[in] use_count whether to use '#' prefixes (optimized format) @param[in] use_type whether to use '$' prefixes (optimized format) @param[in] add_prefix whether prefixes need to be used for this value */ void write_ubjson(const BasicJsonType& j, const bool use_count, const bool use_type, const bool add_prefix = true) { switch (j.type()) { case value_t::null: { if (add_prefix) { oa->write_character(to_char_type('Z')); } break; } case value_t::boolean: { if (add_prefix) { oa->write_character(j.m_value.boolean ? to_char_type('T') : to_char_type('F')); } break; } case value_t::number_integer: { write_number_with_ubjson_prefix(j.m_value.number_integer, add_prefix); break; } case value_t::number_unsigned: { write_number_with_ubjson_prefix(j.m_value.number_unsigned, add_prefix); break; } case value_t::number_float: { write_number_with_ubjson_prefix(j.m_value.number_float, add_prefix); break; } case value_t::string: { if (add_prefix) { oa->write_character(to_char_type('S')); } write_number_with_ubjson_prefix(j.m_value.string->size(), true); oa->write_characters( reinterpret_cast<const CharType*>(j.m_value.string->c_str()), j.m_value.string->size()); break; } case value_t::array: { if (add_prefix) { oa->write_character(to_char_type('[')); } bool prefix_required = true; if (use_type and not j.m_value.array->empty()) { assert(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin() + 1, j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.array->size(), true); } for (const auto& el : *j.m_value.array) { write_ubjson(el, use_count, use_type, prefix_required); } if (not use_count) { oa->write_character(to_char_type(']')); } break; } case value_t::object: { if (add_prefix) { oa->write_character(to_char_type('{')); } bool prefix_required = true; if (use_type and not j.m_value.object->empty()) { assert(use_count); const CharType first_prefix = ubjson_prefix(j.front()); const bool same_prefix = std::all_of(j.begin(), j.end(), [this, first_prefix](const BasicJsonType & v) { return ubjson_prefix(v) == first_prefix; }); if (same_prefix) { prefix_required = false; oa->write_character(to_char_type('$')); oa->write_character(first_prefix); } } if (use_count) { oa->write_character(to_char_type('#')); write_number_with_ubjson_prefix(j.m_value.object->size(), true); } for (const auto& el : *j.m_value.object) { write_number_with_ubjson_prefix(el.first.size(), true); oa->write_characters( reinterpret_cast<const CharType*>(el.first.c_str()), el.first.size()); write_ubjson(el.second, use_count, use_type, prefix_required); } if (not use_count) { oa->write_character(to_char_type('}')); } break; } default: break; } } private: ////////// // BSON // ////////// /*! @return The size of a BSON document entry header, including the id marker and the entry name size (and its null-terminator). */ static std::size_t calc_bson_entry_header_size(const string_t& name) { const auto it = name.find(static_cast<typename string_t::value_type>(0)); if (JSON_UNLIKELY(it != BasicJsonType::string_t::npos)) { JSON_THROW(out_of_range::create(409, "BSON key cannot contain code point U+0000 (at byte " + std::to_string(it) + ")")); } return /*id*/ 1ul + name.size() + /*zero-terminator*/1u; } /*! @brief Writes the given @a element_type and @a name to the output adapter */ void write_bson_entry_header(const string_t& name, const std::uint8_t element_type) { oa->write_character(to_char_type(element_type)); // boolean oa->write_characters( reinterpret_cast<const CharType*>(name.c_str()), name.size() + 1u); } /*! @brief Writes a BSON element with key @a name and boolean value @a value */ void write_bson_boolean(const string_t& name, const bool value) { write_bson_entry_header(name, 0x08); oa->write_character(value ? to_char_type(0x01) : to_char_type(0x00)); } /*! @brief Writes a BSON element with key @a name and double value @a value */ void write_bson_double(const string_t& name, const double value) { write_bson_entry_header(name, 0x01); write_number<double, true>(value); } /*! @return The size of the BSON-encoded string in @a value */ static std::size_t calc_bson_string_size(const string_t& value) { return sizeof(std::int32_t) + value.size() + 1ul; } /*! @brief Writes a BSON element with key @a name and string value @a value */ void write_bson_string(const string_t& name, const string_t& value) { write_bson_entry_header(name, 0x02); write_number<std::int32_t, true>(static_cast<std::int32_t>(value.size() + 1ul)); oa->write_characters( reinterpret_cast<const CharType*>(value.c_str()), value.size() + 1); } /*! @brief Writes a BSON element with key @a name and null value */ void write_bson_null(const string_t& name) { write_bson_entry_header(name, 0x0A); } /*! @return The size of the BSON-encoded integer @a value */ static std::size_t calc_bson_integer_size(const std::int64_t value) { if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()) { return sizeof(std::int32_t); } else { return sizeof(std::int64_t); } } /*! @brief Writes a BSON element with key @a name and integer @a value */ void write_bson_integer(const string_t& name, const std::int64_t value) { if ((std::numeric_limits<std::int32_t>::min)() <= value and value <= (std::numeric_limits<std::int32_t>::max)()) { write_bson_entry_header(name, 0x10); // int32 write_number<std::int32_t, true>(static_cast<std::int32_t>(value)); } else { write_bson_entry_header(name, 0x12); // int64 write_number<std::int64_t, true>(static_cast<std::int64_t>(value)); } } /*! @return The size of the BSON-encoded unsigned integer in @a j */ static constexpr std::size_t calc_bson_unsigned_size(const std::uint64_t value) noexcept { return (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) ? sizeof(std::int32_t) : sizeof(std::int64_t); } /*! @brief Writes a BSON element with key @a name and unsigned @a value */ void write_bson_unsigned(const string_t& name, const std::uint64_t value) { if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int32_t>::max)())) { write_bson_entry_header(name, 0x10 /* int32 */); write_number<std::int32_t, true>(static_cast<std::int32_t>(value)); } else if (value <= static_cast<std::uint64_t>((std::numeric_limits<std::int64_t>::max)())) { write_bson_entry_header(name, 0x12 /* int64 */); write_number<std::int64_t, true>(static_cast<std::int64_t>(value)); } else { JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(value) + " cannot be represented by BSON as it does not fit int64")); } } /*! @brief Writes a BSON element with key @a name and object @a value */ void write_bson_object_entry(const string_t& name, const typename BasicJsonType::object_t& value) { write_bson_entry_header(name, 0x03); // object write_bson_object(value); } /*! @return The size of the BSON-encoded array @a value */ static std::size_t calc_bson_array_size(const typename BasicJsonType::array_t& value) { std::size_t embedded_document_size = 0ul; std::size_t array_index = 0ul; for (const auto& el : value) { embedded_document_size += calc_bson_element_size(std::to_string(array_index++), el); } return sizeof(std::int32_t) + embedded_document_size + 1ul; } /*! @brief Writes a BSON element with key @a name and array @a value */ void write_bson_array(const string_t& name, const typename BasicJsonType::array_t& value) { write_bson_entry_header(name, 0x04); // array write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_array_size(value))); std::size_t array_index = 0ul; for (const auto& el : value) { write_bson_element(std::to_string(array_index++), el); } oa->write_character(to_char_type(0x00)); } /*! @brief Calculates the size necessary to serialize the JSON value @a j with its @a name @return The calculated size for the BSON document entry for @a j with the given @a name. */ static std::size_t calc_bson_element_size(const string_t& name, const BasicJsonType& j) { const auto header_size = calc_bson_entry_header_size(name); switch (j.type()) { case value_t::object: return header_size + calc_bson_object_size(*j.m_value.object); case value_t::array: return header_size + calc_bson_array_size(*j.m_value.array); case value_t::boolean: return header_size + 1ul; case value_t::number_float: return header_size + 8ul; case value_t::number_integer: return header_size + calc_bson_integer_size(j.m_value.number_integer); case value_t::number_unsigned: return header_size + calc_bson_unsigned_size(j.m_value.number_unsigned); case value_t::string: return header_size + calc_bson_string_size(*j.m_value.string); case value_t::null: return header_size + 0ul; // LCOV_EXCL_START default: assert(false); return 0ul; // LCOV_EXCL_STOP } } /*! @brief Serializes the JSON value @a j to BSON and associates it with the key @a name. @param name The name to associate with the JSON entity @a j within the current BSON document @return The size of the BSON entry */ void write_bson_element(const string_t& name, const BasicJsonType& j) { switch (j.type()) { case value_t::object: return write_bson_object_entry(name, *j.m_value.object); case value_t::array: return write_bson_array(name, *j.m_value.array); case value_t::boolean: return write_bson_boolean(name, j.m_value.boolean); case value_t::number_float: return write_bson_double(name, j.m_value.number_float); case value_t::number_integer: return write_bson_integer(name, j.m_value.number_integer); case value_t::number_unsigned: return write_bson_unsigned(name, j.m_value.number_unsigned); case value_t::string: return write_bson_string(name, *j.m_value.string); case value_t::null: return write_bson_null(name); // LCOV_EXCL_START default: assert(false); return; // LCOV_EXCL_STOP } } /*! @brief Calculates the size of the BSON serialization of the given JSON-object @a j. @param[in] j JSON value to serialize @pre j.type() == value_t::object */ static std::size_t calc_bson_object_size(const typename BasicJsonType::object_t& value) { std::size_t document_size = std::accumulate(value.begin(), value.end(), 0ul, [](size_t result, const typename BasicJsonType::object_t::value_type & el) { return result += calc_bson_element_size(el.first, el.second); }); return sizeof(std::int32_t) + document_size + 1ul; } /*! @param[in] j JSON value to serialize @pre j.type() == value_t::object */ void write_bson_object(const typename BasicJsonType::object_t& value) { write_number<std::int32_t, true>(static_cast<std::int32_t>(calc_bson_object_size(value))); for (const auto& el : value) { write_bson_element(el.first, el.second); } oa->write_character(to_char_type(0x00)); } ////////// // CBOR // ////////// static constexpr CharType get_cbor_float_prefix(float /*unused*/) { return to_char_type(0xFA); // Single-Precision Float } static constexpr CharType get_cbor_float_prefix(double /*unused*/) { return to_char_type(0xFB); // Double-Precision Float } ///////////// // MsgPack // ///////////// static constexpr CharType get_msgpack_float_prefix(float /*unused*/) { return to_char_type(0xCA); // float 32 } static constexpr CharType get_msgpack_float_prefix(double /*unused*/) { return to_char_type(0xCB); // float 64 } //////////// // UBJSON // //////////// // UBJSON: write number (floating point) template<typename NumberType, typename std::enable_if< std::is_floating_point<NumberType>::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (add_prefix) { oa->write_character(get_ubjson_float_prefix(n)); } write_number(n); } // UBJSON: write number (unsigned integer) template<typename NumberType, typename std::enable_if< std::is_unsigned<NumberType>::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if (n <= static_cast<uint64_t>((std::numeric_limits<int8_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast<uint8_t>(n)); } else if (n <= (std::numeric_limits<uint8_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast<uint8_t>(n)); } else if (n <= static_cast<uint64_t>((std::numeric_limits<int16_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast<int16_t>(n)); } else if (n <= static_cast<uint64_t>((std::numeric_limits<int32_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast<int32_t>(n)); } else if (n <= static_cast<uint64_t>((std::numeric_limits<int64_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast<int64_t>(n)); } else { JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64")); } } // UBJSON: write number (signed integer) template<typename NumberType, typename std::enable_if< std::is_signed<NumberType>::value and not std::is_floating_point<NumberType>::value, int>::type = 0> void write_number_with_ubjson_prefix(const NumberType n, const bool add_prefix) { if ((std::numeric_limits<int8_t>::min)() <= n and n <= (std::numeric_limits<int8_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('i')); // int8 } write_number(static_cast<int8_t>(n)); } else if (static_cast<int64_t>((std::numeric_limits<uint8_t>::min)()) <= n and n <= static_cast<int64_t>((std::numeric_limits<uint8_t>::max)())) { if (add_prefix) { oa->write_character(to_char_type('U')); // uint8 } write_number(static_cast<uint8_t>(n)); } else if ((std::numeric_limits<int16_t>::min)() <= n and n <= (std::numeric_limits<int16_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('I')); // int16 } write_number(static_cast<int16_t>(n)); } else if ((std::numeric_limits<int32_t>::min)() <= n and n <= (std::numeric_limits<int32_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('l')); // int32 } write_number(static_cast<int32_t>(n)); } else if ((std::numeric_limits<int64_t>::min)() <= n and n <= (std::numeric_limits<int64_t>::max)()) { if (add_prefix) { oa->write_character(to_char_type('L')); // int64 } write_number(static_cast<int64_t>(n)); } // LCOV_EXCL_START else { JSON_THROW(out_of_range::create(407, "integer number " + std::to_string(n) + " cannot be represented by UBJSON as it does not fit int64")); } // LCOV_EXCL_STOP } /*! @brief determine the type prefix of container values @note This function does not need to be 100% accurate when it comes to integer limits. In case a number exceeds the limits of int64_t, this will be detected by a later call to function write_number_with_ubjson_prefix. Therefore, we return 'L' for any value that does not fit the previous limits. */ CharType ubjson_prefix(const BasicJsonType& j) const noexcept { switch (j.type()) { case value_t::null: return 'Z'; case value_t::boolean: return j.m_value.boolean ? 'T' : 'F'; case value_t::number_integer: { if ((std::numeric_limits<int8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int8_t>::max)()) { return 'i'; } if ((std::numeric_limits<uint8_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<uint8_t>::max)()) { return 'U'; } if ((std::numeric_limits<int16_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int16_t>::max)()) { return 'I'; } if ((std::numeric_limits<int32_t>::min)() <= j.m_value.number_integer and j.m_value.number_integer <= (std::numeric_limits<int32_t>::max)()) { return 'l'; } // no check and assume int64_t (see note above) return 'L'; } case value_t::number_unsigned: { if (j.m_value.number_unsigned <= (std::numeric_limits<int8_t>::max)()) { return 'i'; } if (j.m_value.number_unsigned <= (std::numeric_limits<uint8_t>::max)()) { return 'U'; } if (j.m_value.number_unsigned <= (std::numeric_limits<int16_t>::max)()) { return 'I'; } if (j.m_value.number_unsigned <= (std::numeric_limits<int32_t>::max)()) { return 'l'; } // no check and assume int64_t (see note above) return 'L'; } case value_t::number_float: return get_ubjson_float_prefix(j.m_value.number_float); case value_t::string: return 'S'; case value_t::array: return '['; case value_t::object: return '{'; default: // discarded values return 'N'; } } static constexpr CharType get_ubjson_float_prefix(float /*unused*/) { return 'd'; // float 32 } static constexpr CharType get_ubjson_float_prefix(double /*unused*/) { return 'D'; // float 64 } /////////////////////// // Utility functions // /////////////////////// /* @brief write a number to output input @param[in] n number of type @a NumberType @tparam NumberType the type of the number @tparam OutputIsLittleEndian Set to true if output data is required to be little endian @note This function needs to respect the system's endianess, because bytes in CBOR, MessagePack, and UBJSON are stored in network order (big endian) and therefore need reordering on little endian systems. */ template<typename NumberType, bool OutputIsLittleEndian = false> void write_number(const NumberType n) { // step 1: write number to array of length NumberType std::array<CharType, sizeof(NumberType)> vec; std::memcpy(vec.data(), &n, sizeof(NumberType)); // step 2: write array to output (with possible reordering) if (is_little_endian and not OutputIsLittleEndian) { // reverse byte order prior to conversion if necessary std::reverse(vec.begin(), vec.end()); } oa->write_characters(vec.data(), sizeof(NumberType)); } public: // The following to_char_type functions are implement the conversion // between uint8_t and CharType. In case CharType is not unsigned, // such a conversion is required to allow values greater than 128. // See <https://github.com/nlohmann/json/issues/1286> for a discussion. template < typename C = CharType, enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value > * = nullptr > static constexpr CharType to_char_type(std::uint8_t x) noexcept { return *reinterpret_cast<char*>(&x); } template < typename C = CharType, enable_if_t < std::is_signed<C>::value and std::is_unsigned<char>::value > * = nullptr > static CharType to_char_type(std::uint8_t x) noexcept { static_assert(sizeof(std::uint8_t) == sizeof(CharType), "size of CharType must be equal to std::uint8_t"); static_assert(std::is_pod<CharType>::value, "CharType must be POD"); CharType result; std::memcpy(&result, &x, sizeof(x)); return result; } template<typename C = CharType, enable_if_t<std::is_unsigned<C>::value>* = nullptr> static constexpr CharType to_char_type(std::uint8_t x) noexcept { return x; } template < typename InputCharType, typename C = CharType, enable_if_t < std::is_signed<C>::value and std::is_signed<char>::value and std::is_same<char, typename std::remove_cv<InputCharType>::type>::value > * = nullptr > static constexpr CharType to_char_type(InputCharType x) noexcept { return x; } private: /// whether we can assume little endianess const bool is_little_endian = binary_reader<BasicJsonType>::little_endianess(); /// the output output_adapter_t<CharType> oa = nullptr; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/output/serializer.hpp> #include <algorithm> // reverse, remove, fill, find, none_of #include <array> // array #include <cassert> // assert #include <ciso646> // and, or #include <clocale> // localeconv, lconv #include <cmath> // labs, isfinite, isnan, signbit #include <cstddef> // size_t, ptrdiff_t #include <cstdint> // uint8_t #include <cstdio> // snprintf #include <limits> // numeric_limits #include <string> // string #include <type_traits> // is_same // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/conversions/to_chars.hpp> #include <cassert> // assert #include <ciso646> // or, and, not #include <cmath> // signbit, isfinite #include <cstdint> // intN_t, uintN_t #include <cstring> // memcpy, memmove #include <limits> // numeric_limits #include <type_traits> // conditional namespace nlohmann { namespace detail { /*! @brief implements the Grisu2 algorithm for binary to decimal floating-point conversion. This implementation is a slightly modified version of the reference implementation which may be obtained from http://florian.loitsch.com/publications (bench.tar.gz). The code is distributed under the MIT license, Copyright (c) 2009 Florian Loitsch. For a detailed description of the algorithm see: [1] Loitsch, "Printing Floating-Point Numbers Quickly and Accurately with Integers", Proceedings of the ACM SIGPLAN 2010 Conference on Programming Language Design and Implementation, PLDI 2010 [2] Burger, Dybvig, "Printing Floating-Point Numbers Quickly and Accurately", Proceedings of the ACM SIGPLAN 1996 Conference on Programming Language Design and Implementation, PLDI 1996 */ namespace dtoa_impl { template <typename Target, typename Source> Target reinterpret_bits(const Source source) { static_assert(sizeof(Target) == sizeof(Source), "size mismatch"); Target target; std::memcpy(&target, &source, sizeof(Source)); return target; } struct diyfp // f * 2^e { static constexpr int kPrecision = 64; // = q uint64_t f = 0; int e = 0; constexpr diyfp(uint64_t f_, int e_) noexcept : f(f_), e(e_) {} /*! @brief returns x - y @pre x.e == y.e and x.f >= y.f */ static diyfp sub(const diyfp& x, const diyfp& y) noexcept { assert(x.e == y.e); assert(x.f >= y.f); return {x.f - y.f, x.e}; } /*! @brief returns x * y @note The result is rounded. (Only the upper q bits are returned.) */ static diyfp mul(const diyfp& x, const diyfp& y) noexcept { static_assert(kPrecision == 64, "internal error"); // Computes: // f = round((x.f * y.f) / 2^q) // e = x.e + y.e + q // Emulate the 64-bit * 64-bit multiplication: // // p = u * v // = (u_lo + 2^32 u_hi) (v_lo + 2^32 v_hi) // = (u_lo v_lo ) + 2^32 ((u_lo v_hi ) + (u_hi v_lo )) + 2^64 (u_hi v_hi ) // = (p0 ) + 2^32 ((p1 ) + (p2 )) + 2^64 (p3 ) // = (p0_lo + 2^32 p0_hi) + 2^32 ((p1_lo + 2^32 p1_hi) + (p2_lo + 2^32 p2_hi)) + 2^64 (p3 ) // = (p0_lo ) + 2^32 (p0_hi + p1_lo + p2_lo ) + 2^64 (p1_hi + p2_hi + p3) // = (p0_lo ) + 2^32 (Q ) + 2^64 (H ) // = (p0_lo ) + 2^32 (Q_lo + 2^32 Q_hi ) + 2^64 (H ) // // (Since Q might be larger than 2^32 - 1) // // = (p0_lo + 2^32 Q_lo) + 2^64 (Q_hi + H) // // (Q_hi + H does not overflow a 64-bit int) // // = p_lo + 2^64 p_hi const uint64_t u_lo = x.f & 0xFFFFFFFF; const uint64_t u_hi = x.f >> 32; const uint64_t v_lo = y.f & 0xFFFFFFFF; const uint64_t v_hi = y.f >> 32; const uint64_t p0 = u_lo * v_lo; const uint64_t p1 = u_lo * v_hi; const uint64_t p2 = u_hi * v_lo; const uint64_t p3 = u_hi * v_hi; const uint64_t p0_hi = p0 >> 32; const uint64_t p1_lo = p1 & 0xFFFFFFFF; const uint64_t p1_hi = p1 >> 32; const uint64_t p2_lo = p2 & 0xFFFFFFFF; const uint64_t p2_hi = p2 >> 32; uint64_t Q = p0_hi + p1_lo + p2_lo; // The full product might now be computed as // // p_hi = p3 + p2_hi + p1_hi + (Q >> 32) // p_lo = p0_lo + (Q << 32) // // But in this particular case here, the full p_lo is not required. // Effectively we only need to add the highest bit in p_lo to p_hi (and // Q_hi + 1 does not overflow). Q += uint64_t{1} << (64 - 32 - 1); // round, ties up const uint64_t h = p3 + p2_hi + p1_hi + (Q >> 32); return {h, x.e + y.e + 64}; } /*! @brief normalize x such that the significand is >= 2^(q-1) @pre x.f != 0 */ static diyfp normalize(diyfp x) noexcept { assert(x.f != 0); while ((x.f >> 63) == 0) { x.f <<= 1; x.e--; } return x; } /*! @brief normalize x such that the result has the exponent E @pre e >= x.e and the upper e - x.e bits of x.f must be zero. */ static diyfp normalize_to(const diyfp& x, const int target_exponent) noexcept { const int delta = x.e - target_exponent; assert(delta >= 0); assert(((x.f << delta) >> delta) == x.f); return {x.f << delta, target_exponent}; } }; struct boundaries { diyfp w; diyfp minus; diyfp plus; }; /*! Compute the (normalized) diyfp representing the input number 'value' and its boundaries. @pre value must be finite and positive */ template <typename FloatType> boundaries compute_boundaries(FloatType value) { assert(std::isfinite(value)); assert(value > 0); // Convert the IEEE representation into a diyfp. // // If v is denormal: // value = 0.F * 2^(1 - bias) = ( F) * 2^(1 - bias - (p-1)) // If v is normalized: // value = 1.F * 2^(E - bias) = (2^(p-1) + F) * 2^(E - bias - (p-1)) static_assert(std::numeric_limits<FloatType>::is_iec559, "internal error: dtoa_short requires an IEEE-754 floating-point implementation"); constexpr int kPrecision = std::numeric_limits<FloatType>::digits; // = p (includes the hidden bit) constexpr int kBias = std::numeric_limits<FloatType>::max_exponent - 1 + (kPrecision - 1); constexpr int kMinExp = 1 - kBias; constexpr uint64_t kHiddenBit = uint64_t{1} << (kPrecision - 1); // = 2^(p-1) using bits_type = typename std::conditional< kPrecision == 24, uint32_t, uint64_t >::type; const uint64_t bits = reinterpret_bits<bits_type>(value); const uint64_t E = bits >> (kPrecision - 1); const uint64_t F = bits & (kHiddenBit - 1); const bool is_denormal = (E == 0); const diyfp v = is_denormal ? diyfp(F, kMinExp) : diyfp(F + kHiddenBit, static_cast<int>(E) - kBias); // Compute the boundaries m- and m+ of the floating-point value // v = f * 2^e. // // Determine v- and v+, the floating-point predecessor and successor if v, // respectively. // // v- = v - 2^e if f != 2^(p-1) or e == e_min (A) // = v - 2^(e-1) if f == 2^(p-1) and e > e_min (B) // // v+ = v + 2^e // // Let m- = (v- + v) / 2 and m+ = (v + v+) / 2. All real numbers _strictly_ // between m- and m+ round to v, regardless of how the input rounding // algorithm breaks ties. // // ---+-------------+-------------+-------------+-------------+--- (A) // v- m- v m+ v+ // // -----------------+------+------+-------------+-------------+--- (B) // v- m- v m+ v+ const bool lower_boundary_is_closer = (F == 0 and E > 1); const diyfp m_plus = diyfp(2 * v.f + 1, v.e - 1); const diyfp m_minus = lower_boundary_is_closer ? diyfp(4 * v.f - 1, v.e - 2) // (B) : diyfp(2 * v.f - 1, v.e - 1); // (A) // Determine the normalized w+ = m+. const diyfp w_plus = diyfp::normalize(m_plus); // Determine w- = m- such that e_(w-) = e_(w+). const diyfp w_minus = diyfp::normalize_to(m_minus, w_plus.e); return {diyfp::normalize(v), w_minus, w_plus}; } // Given normalized diyfp w, Grisu needs to find a (normalized) cached // power-of-ten c, such that the exponent of the product c * w = f * 2^e lies // within a certain range [alpha, gamma] (Definition 3.2 from [1]) // // alpha <= e = e_c + e_w + q <= gamma // // or // // f_c * f_w * 2^alpha <= f_c 2^(e_c) * f_w 2^(e_w) * 2^q // <= f_c * f_w * 2^gamma // // Since c and w are normalized, i.e. 2^(q-1) <= f < 2^q, this implies // // 2^(q-1) * 2^(q-1) * 2^alpha <= c * w * 2^q < 2^q * 2^q * 2^gamma // // or // // 2^(q - 2 + alpha) <= c * w < 2^(q + gamma) // // The choice of (alpha,gamma) determines the size of the table and the form of // the digit generation procedure. Using (alpha,gamma)=(-60,-32) works out well // in practice: // // The idea is to cut the number c * w = f * 2^e into two parts, which can be // processed independently: An integral part p1, and a fractional part p2: // // f * 2^e = ( (f div 2^-e) * 2^-e + (f mod 2^-e) ) * 2^e // = (f div 2^-e) + (f mod 2^-e) * 2^e // = p1 + p2 * 2^e // // The conversion of p1 into decimal form requires a series of divisions and // modulos by (a power of) 10. These operations are faster for 32-bit than for // 64-bit integers, so p1 should ideally fit into a 32-bit integer. This can be // achieved by choosing // // -e >= 32 or e <= -32 := gamma // // In order to convert the fractional part // // p2 * 2^e = p2 / 2^-e = d[-1] / 10^1 + d[-2] / 10^2 + ... // // into decimal form, the fraction is repeatedly multiplied by 10 and the digits // d[-i] are extracted in order: // // (10 * p2) div 2^-e = d[-1] // (10 * p2) mod 2^-e = d[-2] / 10^1 + ... // // The multiplication by 10 must not overflow. It is sufficient to choose // // 10 * p2 < 16 * p2 = 2^4 * p2 <= 2^64. // // Since p2 = f mod 2^-e < 2^-e, // // -e <= 60 or e >= -60 := alpha constexpr int kAlpha = -60; constexpr int kGamma = -32; struct cached_power // c = f * 2^e ~= 10^k { uint64_t f; int e; int k; }; /*! For a normalized diyfp w = f * 2^e, this function returns a (normalized) cached power-of-ten c = f_c * 2^e_c, such that the exponent of the product w * c satisfies (Definition 3.2 from [1]) alpha <= e_c + e + q <= gamma. */ inline cached_power get_cached_power_for_binary_exponent(int e) { // Now // // alpha <= e_c + e + q <= gamma (1) // ==> f_c * 2^alpha <= c * 2^e * 2^q // // and since the c's are normalized, 2^(q-1) <= f_c, // // ==> 2^(q - 1 + alpha) <= c * 2^(e + q) // ==> 2^(alpha - e - 1) <= c // // If c were an exakt power of ten, i.e. c = 10^k, one may determine k as // // k = ceil( log_10( 2^(alpha - e - 1) ) ) // = ceil( (alpha - e - 1) * log_10(2) ) // // From the paper: // "In theory the result of the procedure could be wrong since c is rounded, // and the computation itself is approximated [...]. In practice, however, // this simple function is sufficient." // // For IEEE double precision floating-point numbers converted into // normalized diyfp's w = f * 2^e, with q = 64, // // e >= -1022 (min IEEE exponent) // -52 (p - 1) // -52 (p - 1, possibly normalize denormal IEEE numbers) // -11 (normalize the diyfp) // = -1137 // // and // // e <= +1023 (max IEEE exponent) // -52 (p - 1) // -11 (normalize the diyfp) // = 960 // // This binary exponent range [-1137,960] results in a decimal exponent // range [-307,324]. One does not need to store a cached power for each // k in this range. For each such k it suffices to find a cached power // such that the exponent of the product lies in [alpha,gamma]. // This implies that the difference of the decimal exponents of adjacent // table entries must be less than or equal to // // floor( (gamma - alpha) * log_10(2) ) = 8. // // (A smaller distance gamma-alpha would require a larger table.) // NB: // Actually this function returns c, such that -60 <= e_c + e + 64 <= -34. constexpr int kCachedPowersSize = 79; constexpr int kCachedPowersMinDecExp = -300; constexpr int kCachedPowersDecStep = 8; static constexpr cached_power kCachedPowers[] = { { 0xAB70FE17C79AC6CA, -1060, -300 }, { 0xFF77B1FCBEBCDC4F, -1034, -292 }, { 0xBE5691EF416BD60C, -1007, -284 }, { 0x8DD01FAD907FFC3C, -980, -276 }, { 0xD3515C2831559A83, -954, -268 }, { 0x9D71AC8FADA6C9B5, -927, -260 }, { 0xEA9C227723EE8BCB, -901, -252 }, { 0xAECC49914078536D, -874, -244 }, { 0x823C12795DB6CE57, -847, -236 }, { 0xC21094364DFB5637, -821, -228 }, { 0x9096EA6F3848984F, -794, -220 }, { 0xD77485CB25823AC7, -768, -212 }, { 0xA086CFCD97BF97F4, -741, -204 }, { 0xEF340A98172AACE5, -715, -196 }, { 0xB23867FB2A35B28E, -688, -188 }, { 0x84C8D4DFD2C63F3B, -661, -180 }, { 0xC5DD44271AD3CDBA, -635, -172 }, { 0x936B9FCEBB25C996, -608, -164 }, { 0xDBAC6C247D62A584, -582, -156 }, { 0xA3AB66580D5FDAF6, -555, -148 }, { 0xF3E2F893DEC3F126, -529, -140 }, { 0xB5B5ADA8AAFF80B8, -502, -132 }, { 0x87625F056C7C4A8B, -475, -124 }, { 0xC9BCFF6034C13053, -449, -116 }, { 0x964E858C91BA2655, -422, -108 }, { 0xDFF9772470297EBD, -396, -100 }, { 0xA6DFBD9FB8E5B88F, -369, -92 }, { 0xF8A95FCF88747D94, -343, -84 }, { 0xB94470938FA89BCF, -316, -76 }, { 0x8A08F0F8BF0F156B, -289, -68 }, { 0xCDB02555653131B6, -263, -60 }, { 0x993FE2C6D07B7FAC, -236, -52 }, { 0xE45C10C42A2B3B06, -210, -44 }, { 0xAA242499697392D3, -183, -36 }, { 0xFD87B5F28300CA0E, -157, -28 }, { 0xBCE5086492111AEB, -130, -20 }, { 0x8CBCCC096F5088CC, -103, -12 }, { 0xD1B71758E219652C, -77, -4 }, { 0x9C40000000000000, -50, 4 }, { 0xE8D4A51000000000, -24, 12 }, { 0xAD78EBC5AC620000, 3, 20 }, { 0x813F3978F8940984, 30, 28 }, { 0xC097CE7BC90715B3, 56, 36 }, { 0x8F7E32CE7BEA5C70, 83, 44 }, { 0xD5D238A4ABE98068, 109, 52 }, { 0x9F4F2726179A2245, 136, 60 }, { 0xED63A231D4C4FB27, 162, 68 }, { 0xB0DE65388CC8ADA8, 189, 76 }, { 0x83C7088E1AAB65DB, 216, 84 }, { 0xC45D1DF942711D9A, 242, 92 }, { 0x924D692CA61BE758, 269, 100 }, { 0xDA01EE641A708DEA, 295, 108 }, { 0xA26DA3999AEF774A, 322, 116 }, { 0xF209787BB47D6B85, 348, 124 }, { 0xB454E4A179DD1877, 375, 132 }, { 0x865B86925B9BC5C2, 402, 140 }, { 0xC83553C5C8965D3D, 428, 148 }, { 0x952AB45CFA97A0B3, 455, 156 }, { 0xDE469FBD99A05FE3, 481, 164 }, { 0xA59BC234DB398C25, 508, 172 }, { 0xF6C69A72A3989F5C, 534, 180 }, { 0xB7DCBF5354E9BECE, 561, 188 }, { 0x88FCF317F22241E2, 588, 196 }, { 0xCC20CE9BD35C78A5, 614, 204 }, { 0x98165AF37B2153DF, 641, 212 }, { 0xE2A0B5DC971F303A, 667, 220 }, { 0xA8D9D1535CE3B396, 694, 228 }, { 0xFB9B7CD9A4A7443C, 720, 236 }, { 0xBB764C4CA7A44410, 747, 244 }, { 0x8BAB8EEFB6409C1A, 774, 252 }, { 0xD01FEF10A657842C, 800, 260 }, { 0x9B10A4E5E9913129, 827, 268 }, { 0xE7109BFBA19C0C9D, 853, 276 }, { 0xAC2820D9623BF429, 880, 284 }, { 0x80444B5E7AA7CF85, 907, 292 }, { 0xBF21E44003ACDD2D, 933, 300 }, { 0x8E679C2F5E44FF8F, 960, 308 }, { 0xD433179D9C8CB841, 986, 316 }, { 0x9E19DB92B4E31BA9, 1013, 324 }, }; // This computation gives exactly the same results for k as // k = ceil((kAlpha - e - 1) * 0.30102999566398114) // for |e| <= 1500, but doesn't require floating-point operations. // NB: log_10(2) ~= 78913 / 2^18 assert(e >= -1500); assert(e <= 1500); const int f = kAlpha - e - 1; const int k = (f * 78913) / (1 << 18) + static_cast<int>(f > 0); const int index = (-kCachedPowersMinDecExp + k + (kCachedPowersDecStep - 1)) / kCachedPowersDecStep; assert(index >= 0); assert(index < kCachedPowersSize); static_cast<void>(kCachedPowersSize); // Fix warning. const cached_power cached = kCachedPowers[index]; assert(kAlpha <= cached.e + e + 64); assert(kGamma >= cached.e + e + 64); return cached; } /*! For n != 0, returns k, such that pow10 := 10^(k-1) <= n < 10^k. For n == 0, returns 1 and sets pow10 := 1. */ inline int find_largest_pow10(const uint32_t n, uint32_t& pow10) { // LCOV_EXCL_START if (n >= 1000000000) { pow10 = 1000000000; return 10; } // LCOV_EXCL_STOP else if (n >= 100000000) { pow10 = 100000000; return 9; } else if (n >= 10000000) { pow10 = 10000000; return 8; } else if (n >= 1000000) { pow10 = 1000000; return 7; } else if (n >= 100000) { pow10 = 100000; return 6; } else if (n >= 10000) { pow10 = 10000; return 5; } else if (n >= 1000) { pow10 = 1000; return 4; } else if (n >= 100) { pow10 = 100; return 3; } else if (n >= 10) { pow10 = 10; return 2; } else { pow10 = 1; return 1; } } inline void grisu2_round(char* buf, int len, uint64_t dist, uint64_t delta, uint64_t rest, uint64_t ten_k) { assert(len >= 1); assert(dist <= delta); assert(rest <= delta); assert(ten_k > 0); // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // ten_k // <------> // <---- rest ----> // --------------[------------------+----+--------------]-------------- // w V // = buf * 10^k // // ten_k represents a unit-in-the-last-place in the decimal representation // stored in buf. // Decrement buf by ten_k while this takes buf closer to w. // The tests are written in this order to avoid overflow in unsigned // integer arithmetic. while (rest < dist and delta - rest >= ten_k and (rest + ten_k < dist or dist - rest > rest + ten_k - dist)) { assert(buf[len - 1] != '0'); buf[len - 1]--; rest += ten_k; } } /*! Generates V = buffer * 10^decimal_exponent, such that M- <= V <= M+. M- and M+ must be normalized and share the same exponent -60 <= e <= -32. */ inline void grisu2_digit_gen(char* buffer, int& length, int& decimal_exponent, diyfp M_minus, diyfp w, diyfp M_plus) { static_assert(kAlpha >= -60, "internal error"); static_assert(kGamma <= -32, "internal error"); // Generates the digits (and the exponent) of a decimal floating-point // number V = buffer * 10^decimal_exponent in the range [M-, M+]. The diyfp's // w, M- and M+ share the same exponent e, which satisfies alpha <= e <= gamma. // // <--------------------------- delta ----> // <---- dist ---------> // --------------[------------------+-------------------]-------------- // M- w M+ // // Grisu2 generates the digits of M+ from left to right and stops as soon as // V is in [M-,M+]. assert(M_plus.e >= kAlpha); assert(M_plus.e <= kGamma); uint64_t delta = diyfp::sub(M_plus, M_minus).f; // (significand of (M+ - M-), implicit exponent is e) uint64_t dist = diyfp::sub(M_plus, w ).f; // (significand of (M+ - w ), implicit exponent is e) // Split M+ = f * 2^e into two parts p1 and p2 (note: e < 0): // // M+ = f * 2^e // = ((f div 2^-e) * 2^-e + (f mod 2^-e)) * 2^e // = ((p1 ) * 2^-e + (p2 )) * 2^e // = p1 + p2 * 2^e const diyfp one(uint64_t{1} << -M_plus.e, M_plus.e); auto p1 = static_cast<uint32_t>(M_plus.f >> -one.e); // p1 = f div 2^-e (Since -e >= 32, p1 fits into a 32-bit int.) uint64_t p2 = M_plus.f & (one.f - 1); // p2 = f mod 2^-e // 1) // // Generate the digits of the integral part p1 = d[n-1]...d[1]d[0] assert(p1 > 0); uint32_t pow10; const int k = find_largest_pow10(p1, pow10); // 10^(k-1) <= p1 < 10^k, pow10 = 10^(k-1) // // p1 = (p1 div 10^(k-1)) * 10^(k-1) + (p1 mod 10^(k-1)) // = (d[k-1] ) * 10^(k-1) + (p1 mod 10^(k-1)) // // M+ = p1 + p2 * 2^e // = d[k-1] * 10^(k-1) + (p1 mod 10^(k-1)) + p2 * 2^e // = d[k-1] * 10^(k-1) + ((p1 mod 10^(k-1)) * 2^-e + p2) * 2^e // = d[k-1] * 10^(k-1) + ( rest) * 2^e // // Now generate the digits d[n] of p1 from left to right (n = k-1,...,0) // // p1 = d[k-1]...d[n] * 10^n + d[n-1]...d[0] // // but stop as soon as // // rest * 2^e = (d[n-1]...d[0] * 2^-e + p2) * 2^e <= delta * 2^e int n = k; while (n > 0) { // Invariants: // M+ = buffer * 10^n + (p1 + p2 * 2^e) (buffer = 0 for n = k) // pow10 = 10^(n-1) <= p1 < 10^n // const uint32_t d = p1 / pow10; // d = p1 div 10^(n-1) const uint32_t r = p1 % pow10; // r = p1 mod 10^(n-1) // // M+ = buffer * 10^n + (d * 10^(n-1) + r) + p2 * 2^e // = (buffer * 10 + d) * 10^(n-1) + (r + p2 * 2^e) // assert(d <= 9); buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(n-1) + (r + p2 * 2^e) // p1 = r; n--; // // M+ = buffer * 10^n + (p1 + p2 * 2^e) // pow10 = 10^n // // Now check if enough digits have been generated. // Compute // // p1 + p2 * 2^e = (p1 * 2^-e + p2) * 2^e = rest * 2^e // // Note: // Since rest and delta share the same exponent e, it suffices to // compare the significands. const uint64_t rest = (uint64_t{p1} << -one.e) + p2; if (rest <= delta) { // V = buffer * 10^n, with M- <= V <= M+. decimal_exponent += n; // We may now just stop. But instead look if the buffer could be // decremented to bring V closer to w. // // pow10 = 10^n is now 1 ulp in the decimal representation V. // The rounding procedure works with diyfp's with an implicit // exponent of e. // // 10^n = (10^n * 2^-e) * 2^e = ulp * 2^e // const uint64_t ten_n = uint64_t{pow10} << -one.e; grisu2_round(buffer, length, dist, delta, rest, ten_n); return; } pow10 /= 10; // // pow10 = 10^(n-1) <= p1 < 10^n // Invariants restored. } // 2) // // The digits of the integral part have been generated: // // M+ = d[k-1]...d[1]d[0] + p2 * 2^e // = buffer + p2 * 2^e // // Now generate the digits of the fractional part p2 * 2^e. // // Note: // No decimal point is generated: the exponent is adjusted instead. // // p2 actually represents the fraction // // p2 * 2^e // = p2 / 2^-e // = d[-1] / 10^1 + d[-2] / 10^2 + ... // // Now generate the digits d[-m] of p1 from left to right (m = 1,2,...) // // p2 * 2^e = d[-1]d[-2]...d[-m] * 10^-m // + 10^-m * (d[-m-1] / 10^1 + d[-m-2] / 10^2 + ...) // // using // // 10^m * p2 = ((10^m * p2) div 2^-e) * 2^-e + ((10^m * p2) mod 2^-e) // = ( d) * 2^-e + ( r) // // or // 10^m * p2 * 2^e = d + r * 2^e // // i.e. // // M+ = buffer + p2 * 2^e // = buffer + 10^-m * (d + r * 2^e) // = (buffer * 10^m + d) * 10^-m + 10^-m * r * 2^e // // and stop as soon as 10^-m * r * 2^e <= delta * 2^e assert(p2 > delta); int m = 0; for (;;) { // Invariant: // M+ = buffer * 10^-m + 10^-m * (d[-m-1] / 10 + d[-m-2] / 10^2 + ...) * 2^e // = buffer * 10^-m + 10^-m * (p2 ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (10 * p2) ) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * ((10*p2 div 2^-e) * 2^-e + (10*p2 mod 2^-e)) * 2^e // assert(p2 <= UINT64_MAX / 10); p2 *= 10; const uint64_t d = p2 >> -one.e; // d = (10 * p2) div 2^-e const uint64_t r = p2 & (one.f - 1); // r = (10 * p2) mod 2^-e // // M+ = buffer * 10^-m + 10^-m * (1/10 * (d * 2^-e + r) * 2^e // = buffer * 10^-m + 10^-m * (1/10 * (d + r * 2^e)) // = (buffer * 10 + d) * 10^(-m-1) + 10^(-m-1) * r * 2^e // assert(d <= 9); buffer[length++] = static_cast<char>('0' + d); // buffer := buffer * 10 + d // // M+ = buffer * 10^(-m-1) + 10^(-m-1) * r * 2^e // p2 = r; m++; // // M+ = buffer * 10^-m + 10^-m * p2 * 2^e // Invariant restored. // Check if enough digits have been generated. // // 10^-m * p2 * 2^e <= delta * 2^e // p2 * 2^e <= 10^m * delta * 2^e // p2 <= 10^m * delta delta *= 10; dist *= 10; if (p2 <= delta) { break; } } // V = buffer * 10^-m, with M- <= V <= M+. decimal_exponent -= m; // 1 ulp in the decimal representation is now 10^-m. // Since delta and dist are now scaled by 10^m, we need to do the // same with ulp in order to keep the units in sync. // // 10^m * 10^-m = 1 = 2^-e * 2^e = ten_m * 2^e // const uint64_t ten_m = one.f; grisu2_round(buffer, length, dist, delta, p2, ten_m); // By construction this algorithm generates the shortest possible decimal // number (Loitsch, Theorem 6.2) which rounds back to w. // For an input number of precision p, at least // // N = 1 + ceil(p * log_10(2)) // // decimal digits are sufficient to identify all binary floating-point // numbers (Matula, "In-and-Out conversions"). // This implies that the algorithm does not produce more than N decimal // digits. // // N = 17 for p = 53 (IEEE double precision) // N = 9 for p = 24 (IEEE single precision) } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ inline void grisu2(char* buf, int& len, int& decimal_exponent, diyfp m_minus, diyfp v, diyfp m_plus) { assert(m_plus.e == m_minus.e); assert(m_plus.e == v.e); // --------(-----------------------+-----------------------)-------- (A) // m- v m+ // // --------------------(-----------+-----------------------)-------- (B) // m- v m+ // // First scale v (and m- and m+) such that the exponent is in the range // [alpha, gamma]. const cached_power cached = get_cached_power_for_binary_exponent(m_plus.e); const diyfp c_minus_k(cached.f, cached.e); // = c ~= 10^-k // The exponent of the products is = v.e + c_minus_k.e + q and is in the range [alpha,gamma] const diyfp w = diyfp::mul(v, c_minus_k); const diyfp w_minus = diyfp::mul(m_minus, c_minus_k); const diyfp w_plus = diyfp::mul(m_plus, c_minus_k); // ----(---+---)---------------(---+---)---------------(---+---)---- // w- w w+ // = c*m- = c*v = c*m+ // // diyfp::mul rounds its result and c_minus_k is approximated too. w, w- and // w+ are now off by a small amount. // In fact: // // w - v * 10^k < 1 ulp // // To account for this inaccuracy, add resp. subtract 1 ulp. // // --------+---[---------------(---+---)---------------]---+-------- // w- M- w M+ w+ // // Now any number in [M-, M+] (bounds included) will round to w when input, // regardless of how the input rounding algorithm breaks ties. // // And digit_gen generates the shortest possible such number in [M-, M+]. // Note that this does not mean that Grisu2 always generates the shortest // possible number in the interval (m-, m+). const diyfp M_minus(w_minus.f + 1, w_minus.e); const diyfp M_plus (w_plus.f - 1, w_plus.e ); decimal_exponent = -cached.k; // = -(-k) = k grisu2_digit_gen(buf, len, decimal_exponent, M_minus, w, M_plus); } /*! v = buf * 10^decimal_exponent len is the length of the buffer (number of decimal digits) The buffer must be large enough, i.e. >= max_digits10. */ template <typename FloatType> void grisu2(char* buf, int& len, int& decimal_exponent, FloatType value) { static_assert(diyfp::kPrecision >= std::numeric_limits<FloatType>::digits + 3, "internal error: not enough precision"); assert(std::isfinite(value)); assert(value > 0); // If the neighbors (and boundaries) of 'value' are always computed for double-precision // numbers, all float's can be recovered using strtod (and strtof). However, the resulting // decimal representations are not exactly "short". // // The documentation for 'std::to_chars' (https://en.cppreference.com/w/cpp/utility/to_chars) // says "value is converted to a string as if by std::sprintf in the default ("C") locale" // and since sprintf promotes float's to double's, I think this is exactly what 'std::to_chars' // does. // On the other hand, the documentation for 'std::to_chars' requires that "parsing the // representation using the corresponding std::from_chars function recovers value exactly". That // indicates that single precision floating-point numbers should be recovered using // 'std::strtof'. // // NB: If the neighbors are computed for single-precision numbers, there is a single float // (7.0385307e-26f) which can't be recovered using strtod. The resulting double precision // value is off by 1 ulp. #if 0 const boundaries w = compute_boundaries(static_cast<double>(value)); #else const boundaries w = compute_boundaries(value); #endif grisu2(buf, len, decimal_exponent, w.minus, w.w, w.plus); } /*! @brief appends a decimal representation of e to buf @return a pointer to the element following the exponent. @pre -1000 < e < 1000 */ inline char* append_exponent(char* buf, int e) { assert(e > -1000); assert(e < 1000); if (e < 0) { e = -e; *buf++ = '-'; } else { *buf++ = '+'; } auto k = static_cast<uint32_t>(e); if (k < 10) { // Always print at least two digits in the exponent. // This is for compatibility with printf("%g"). *buf++ = '0'; *buf++ = static_cast<char>('0' + k); } else if (k < 100) { *buf++ = static_cast<char>('0' + k / 10); k %= 10; *buf++ = static_cast<char>('0' + k); } else { *buf++ = static_cast<char>('0' + k / 100); k %= 100; *buf++ = static_cast<char>('0' + k / 10); k %= 10; *buf++ = static_cast<char>('0' + k); } return buf; } /*! @brief prettify v = buf * 10^decimal_exponent If v is in the range [10^min_exp, 10^max_exp) it will be printed in fixed-point notation. Otherwise it will be printed in exponential notation. @pre min_exp < 0 @pre max_exp > 0 */ inline char* format_buffer(char* buf, int len, int decimal_exponent, int min_exp, int max_exp) { assert(min_exp < 0); assert(max_exp > 0); const int k = len; const int n = len + decimal_exponent; // v = buf * 10^(n-k) // k is the length of the buffer (number of decimal digits) // n is the position of the decimal point relative to the start of the buffer. if (k <= n and n <= max_exp) { // digits[000] // len <= max_exp + 2 std::memset(buf + k, '0', static_cast<size_t>(n - k)); // Make it look like a floating-point number (#362, #378) buf[n + 0] = '.'; buf[n + 1] = '0'; return buf + (n + 2); } if (0 < n and n <= max_exp) { // dig.its // len <= max_digits10 + 1 assert(k > n); std::memmove(buf + (n + 1), buf + n, static_cast<size_t>(k - n)); buf[n] = '.'; return buf + (k + 1); } if (min_exp < n and n <= 0) { // 0.[000]digits // len <= 2 + (-min_exp - 1) + max_digits10 std::memmove(buf + (2 + -n), buf, static_cast<size_t>(k)); buf[0] = '0'; buf[1] = '.'; std::memset(buf + 2, '0', static_cast<size_t>(-n)); return buf + (2 + (-n) + k); } if (k == 1) { // dE+123 // len <= 1 + 5 buf += 1; } else { // d.igitsE+123 // len <= max_digits10 + 1 + 5 std::memmove(buf + 2, buf + 1, static_cast<size_t>(k - 1)); buf[1] = '.'; buf += 1 + k; } *buf++ = 'e'; return append_exponent(buf, n - 1); } } // namespace dtoa_impl /*! @brief generates a decimal representation of the floating-point number value in [first, last). The format of the resulting decimal representation is similar to printf's %g format. Returns an iterator pointing past-the-end of the decimal representation. @note The input number must be finite, i.e. NaN's and Inf's are not supported. @note The buffer must be large enough. @note The result is NOT null-terminated. */ template <typename FloatType> char* to_chars(char* first, const char* last, FloatType value) { static_cast<void>(last); // maybe unused - fix warning assert(std::isfinite(value)); // Use signbit(value) instead of (value < 0) since signbit works for -0. if (std::signbit(value)) { value = -value; *first++ = '-'; } if (value == 0) // +-0 { *first++ = '0'; // Make it look like a floating-point number (#362, #378) *first++ = '.'; *first++ = '0'; return first; } assert(last - first >= std::numeric_limits<FloatType>::max_digits10); // Compute v = buffer * 10^decimal_exponent. // The decimal digits are stored in the buffer, which needs to be interpreted // as an unsigned decimal integer. // len is the length of the buffer, i.e. the number of decimal digits. int len = 0; int decimal_exponent = 0; dtoa_impl::grisu2(first, len, decimal_exponent, value); assert(len <= std::numeric_limits<FloatType>::max_digits10); // Format the buffer like printf("%.*g", prec, value) constexpr int kMinExp = -4; // Use digits10 here to increase compatibility with version 2. constexpr int kMaxExp = std::numeric_limits<FloatType>::digits10; assert(last - first >= kMaxExp + 2); assert(last - first >= 2 + (-kMinExp - 1) + std::numeric_limits<FloatType>::max_digits10); assert(last - first >= std::numeric_limits<FloatType>::max_digits10 + 6); return dtoa_impl::format_buffer(first, len, decimal_exponent, kMinExp, kMaxExp); } } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/meta/cpp_future.hpp> // #include <nlohmann/detail/output/binary_writer.hpp> // #include <nlohmann/detail/output/output_adapters.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { namespace detail { /////////////////// // serialization // /////////////////// /// how to treat decoding errors enum class error_handler_t { strict, ///< throw a type_error exception in case of invalid UTF-8 replace, ///< replace invalid UTF-8 sequences with U+FFFD ignore ///< ignore invalid UTF-8 sequences }; template<typename BasicJsonType> class serializer { using string_t = typename BasicJsonType::string_t; using number_float_t = typename BasicJsonType::number_float_t; using number_integer_t = typename BasicJsonType::number_integer_t; using number_unsigned_t = typename BasicJsonType::number_unsigned_t; static constexpr uint8_t UTF8_ACCEPT = 0; static constexpr uint8_t UTF8_REJECT = 1; public: /*! @param[in] s output stream to serialize to @param[in] ichar indentation character to use @param[in] error_handler_ how to react on decoding errors */ serializer(output_adapter_t<char> s, const char ichar, error_handler_t error_handler_ = error_handler_t::strict) : o(std::move(s)) , loc(std::localeconv()) , thousands_sep(loc->thousands_sep == nullptr ? '\0' : * (loc->thousands_sep)) , decimal_point(loc->decimal_point == nullptr ? '\0' : * (loc->decimal_point)) , indent_char(ichar) , indent_string(512, indent_char) , error_handler(error_handler_) {} // delete because of pointer members serializer(const serializer&) = delete; serializer& operator=(const serializer&) = delete; serializer(serializer&&) = delete; serializer& operator=(serializer&&) = delete; ~serializer() = default; /*! @brief internal implementation of the serialization function This function is called by the public member function dump and organizes the serialization internally. The indentation level is propagated as additional parameter. In case of arrays and objects, the function is called recursively. - strings and object keys are escaped using `escape_string()` - integer numbers are converted implicitly via `operator<<` - floating-point numbers are converted to a string using `"%g"` format @param[in] val value to serialize @param[in] pretty_print whether the output shall be pretty-printed @param[in] indent_step the indent level @param[in] current_indent the current indent level (only used internally) */ void dump(const BasicJsonType& val, const bool pretty_print, const bool ensure_ascii, const unsigned int indent_step, const unsigned int current_indent = 0) { switch (val.m_type) { case value_t::object: { if (val.m_value.object->empty()) { o->write_characters("{}", 2); return; } if (pretty_print) { o->write_characters("{\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element assert(i != val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend()); o->write_characters(indent_string.c_str(), new_indent); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\": ", 3); dump(i->second, true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character('}'); } else { o->write_character('{'); // first n-1 elements auto i = val.m_value.object->cbegin(); for (std::size_t cnt = 0; cnt < val.m_value.object->size() - 1; ++cnt, ++i) { o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element assert(i != val.m_value.object->cend()); assert(std::next(i) == val.m_value.object->cend()); o->write_character('\"'); dump_escaped(i->first, ensure_ascii); o->write_characters("\":", 2); dump(i->second, false, ensure_ascii, indent_step, current_indent); o->write_character('}'); } return; } case value_t::array: { if (val.m_value.array->empty()) { o->write_characters("[]", 2); return; } if (pretty_print) { o->write_characters("[\n", 2); // variable to hold indentation for recursive calls const auto new_indent = current_indent + indent_step; if (JSON_UNLIKELY(indent_string.size() < new_indent)) { indent_string.resize(indent_string.size() * 2, ' '); } // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { o->write_characters(indent_string.c_str(), new_indent); dump(*i, true, ensure_ascii, indent_step, new_indent); o->write_characters(",\n", 2); } // last element assert(not val.m_value.array->empty()); o->write_characters(indent_string.c_str(), new_indent); dump(val.m_value.array->back(), true, ensure_ascii, indent_step, new_indent); o->write_character('\n'); o->write_characters(indent_string.c_str(), current_indent); o->write_character(']'); } else { o->write_character('['); // first n-1 elements for (auto i = val.m_value.array->cbegin(); i != val.m_value.array->cend() - 1; ++i) { dump(*i, false, ensure_ascii, indent_step, current_indent); o->write_character(','); } // last element assert(not val.m_value.array->empty()); dump(val.m_value.array->back(), false, ensure_ascii, indent_step, current_indent); o->write_character(']'); } return; } case value_t::string: { o->write_character('\"'); dump_escaped(*val.m_value.string, ensure_ascii); o->write_character('\"'); return; } case value_t::boolean: { if (val.m_value.boolean) { o->write_characters("true", 4); } else { o->write_characters("false", 5); } return; } case value_t::number_integer: { dump_integer(val.m_value.number_integer); return; } case value_t::number_unsigned: { dump_integer(val.m_value.number_unsigned); return; } case value_t::number_float: { dump_float(val.m_value.number_float); return; } case value_t::discarded: { o->write_characters("<discarded>", 11); return; } case value_t::null: { o->write_characters("null", 4); return; } } } private: /*! @brief dump escaped string Escape a string by replacing certain special characters by a sequence of an escape character (backslash) and another character and other control characters by a sequence of "\u" followed by a four-digit hex representation. The escaped string is written to output stream @a o. @param[in] s the string to escape @param[in] ensure_ascii whether to escape non-ASCII characters with \uXXXX sequences @complexity Linear in the length of string @a s. */ void dump_escaped(const string_t& s, const bool ensure_ascii) { uint32_t codepoint; uint8_t state = UTF8_ACCEPT; std::size_t bytes = 0; // number of bytes written to string_buffer // number of bytes written at the point of the last valid byte std::size_t bytes_after_last_accept = 0; std::size_t undumped_chars = 0; for (std::size_t i = 0; i < s.size(); ++i) { const auto byte = static_cast<uint8_t>(s[i]); switch (decode(state, codepoint, byte)) { case UTF8_ACCEPT: // decode found a new code point { switch (codepoint) { case 0x08: // backspace { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'b'; break; } case 0x09: // horizontal tab { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 't'; break; } case 0x0A: // newline { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'n'; break; } case 0x0C: // formfeed { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'f'; break; } case 0x0D: // carriage return { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'r'; break; } case 0x22: // quotation mark { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\"'; break; } case 0x5C: // reverse solidus { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = '\\'; break; } default: { // escape control characters (0x00..0x1F) or, if // ensure_ascii parameter is used, non-ASCII characters if ((codepoint <= 0x1F) or (ensure_ascii and (codepoint >= 0x7F))) { if (codepoint <= 0xFFFF) { (std::snprintf)(string_buffer.data() + bytes, 7, "\\u%04x", static_cast<uint16_t>(codepoint)); bytes += 6; } else { (std::snprintf)(string_buffer.data() + bytes, 13, "\\u%04x\\u%04x", static_cast<uint16_t>(0xD7C0 + (codepoint >> 10)), static_cast<uint16_t>(0xDC00 + (codepoint & 0x3FF))); bytes += 12; } } else { // copy byte to buffer (all previous bytes // been copied have in default case above) string_buffer[bytes++] = s[i]; } break; } } // write buffer and reset index; there must be 13 bytes // left, as this is the maximal number of bytes to be // written ("\uxxxx\uxxxx\0") for one code point if (string_buffer.size() - bytes < 13) { o->write_characters(string_buffer.data(), bytes); bytes = 0; } // remember the byte position of this accept bytes_after_last_accept = bytes; undumped_chars = 0; break; } case UTF8_REJECT: // decode found invalid UTF-8 byte { switch (error_handler) { case error_handler_t::strict: { std::string sn(3, '\0'); (std::snprintf)(&sn[0], sn.size(), "%.2X", byte); JSON_THROW(type_error::create(316, "invalid UTF-8 byte at index " + std::to_string(i) + ": 0x" + sn)); } case error_handler_t::ignore: case error_handler_t::replace: { // in case we saw this character the first time, we // would like to read it again, because the byte // may be OK for itself, but just not OK for the // previous sequence if (undumped_chars > 0) { --i; } // reset length buffer to the last accepted index; // thus removing/ignoring the invalid characters bytes = bytes_after_last_accept; if (error_handler == error_handler_t::replace) { // add a replacement character if (ensure_ascii) { string_buffer[bytes++] = '\\'; string_buffer[bytes++] = 'u'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'f'; string_buffer[bytes++] = 'd'; } else { string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xEF'); string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBF'); string_buffer[bytes++] = detail::binary_writer<BasicJsonType, char>::to_char_type('\xBD'); } bytes_after_last_accept = bytes; } undumped_chars = 0; // continue processing the string state = UTF8_ACCEPT; break; } } break; } default: // decode found yet incomplete multi-byte code point { if (not ensure_ascii) { // code point will not be escaped - copy byte to buffer string_buffer[bytes++] = s[i]; } ++undumped_chars; break; } } } // we finished processing the string if (JSON_LIKELY(state == UTF8_ACCEPT)) { // write buffer if (bytes > 0) { o->write_characters(string_buffer.data(), bytes); } } else { // we finish reading, but do not accept: string was incomplete switch (error_handler) { case error_handler_t::strict: { std::string sn(3, '\0'); (std::snprintf)(&sn[0], sn.size(), "%.2X", static_cast<uint8_t>(s.back())); JSON_THROW(type_error::create(316, "incomplete UTF-8 string; last byte: 0x" + sn)); } case error_handler_t::ignore: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); break; } case error_handler_t::replace: { // write all accepted bytes o->write_characters(string_buffer.data(), bytes_after_last_accept); // add a replacement character if (ensure_ascii) { o->write_characters("\\ufffd", 6); } else { o->write_characters("\xEF\xBF\xBD", 3); } break; } } } } /*! @brief count digits Count the number of decimal (base 10) digits for an input unsigned integer. @param[in] x unsigned integer number to count its digits @return number of decimal digits */ inline unsigned int count_digits(number_unsigned_t x) noexcept { unsigned int n_digits = 1; for (;;) { if (x < 10) { return n_digits; } if (x < 100) { return n_digits + 1; } if (x < 1000) { return n_digits + 2; } if (x < 10000) { return n_digits + 3; } x = x / 10000u; n_digits += 4; } } /*! @brief dump an integer Dump a given integer to output stream @a o. Works internally with @a number_buffer. @param[in] x integer number (signed or unsigned) to dump @tparam NumberType either @a number_integer_t or @a number_unsigned_t */ template<typename NumberType, detail::enable_if_t< std::is_same<NumberType, number_unsigned_t>::value or std::is_same<NumberType, number_integer_t>::value, int> = 0> void dump_integer(NumberType x) { static constexpr std::array<std::array<char, 2>, 100> digits_to_99 { { {'0', '0'}, {'0', '1'}, {'0', '2'}, {'0', '3'}, {'0', '4'}, {'0', '5'}, {'0', '6'}, {'0', '7'}, {'0', '8'}, {'0', '9'}, {'1', '0'}, {'1', '1'}, {'1', '2'}, {'1', '3'}, {'1', '4'}, {'1', '5'}, {'1', '6'}, {'1', '7'}, {'1', '8'}, {'1', '9'}, {'2', '0'}, {'2', '1'}, {'2', '2'}, {'2', '3'}, {'2', '4'}, {'2', '5'}, {'2', '6'}, {'2', '7'}, {'2', '8'}, {'2', '9'}, {'3', '0'}, {'3', '1'}, {'3', '2'}, {'3', '3'}, {'3', '4'}, {'3', '5'}, {'3', '6'}, {'3', '7'}, {'3', '8'}, {'3', '9'}, {'4', '0'}, {'4', '1'}, {'4', '2'}, {'4', '3'}, {'4', '4'}, {'4', '5'}, {'4', '6'}, {'4', '7'}, {'4', '8'}, {'4', '9'}, {'5', '0'}, {'5', '1'}, {'5', '2'}, {'5', '3'}, {'5', '4'}, {'5', '5'}, {'5', '6'}, {'5', '7'}, {'5', '8'}, {'5', '9'}, {'6', '0'}, {'6', '1'}, {'6', '2'}, {'6', '3'}, {'6', '4'}, {'6', '5'}, {'6', '6'}, {'6', '7'}, {'6', '8'}, {'6', '9'}, {'7', '0'}, {'7', '1'}, {'7', '2'}, {'7', '3'}, {'7', '4'}, {'7', '5'}, {'7', '6'}, {'7', '7'}, {'7', '8'}, {'7', '9'}, {'8', '0'}, {'8', '1'}, {'8', '2'}, {'8', '3'}, {'8', '4'}, {'8', '5'}, {'8', '6'}, {'8', '7'}, {'8', '8'}, {'8', '9'}, {'9', '0'}, {'9', '1'}, {'9', '2'}, {'9', '3'}, {'9', '4'}, {'9', '5'}, {'9', '6'}, {'9', '7'}, {'9', '8'}, {'9', '9'}, } }; // special case for "0" if (x == 0) { o->write_character('0'); return; } // use a pointer to fill the buffer auto buffer_ptr = begin(number_buffer); const bool is_negative = std::is_same<NumberType, number_integer_t>::value and not(x >= 0); // see issue #755 number_unsigned_t abs_value; unsigned int n_chars; if (is_negative) { *buffer_ptr = '-'; abs_value = static_cast<number_unsigned_t>(0 - x); // account one more byte for the minus sign n_chars = 1 + count_digits(abs_value); } else { abs_value = static_cast<number_unsigned_t>(x); n_chars = count_digits(abs_value); } // spare 1 byte for '\0' assert(n_chars < number_buffer.size() - 1); // jump to the end to generate the string from backward // so we later avoid reversing the result buffer_ptr += n_chars; // Fast int2ascii implementation inspired by "Fastware" talk by Andrei Alexandrescu // See: https://www.youtube.com/watch?v=o4-CwDo2zpg while (abs_value >= 100) { const auto digits_index = static_cast<unsigned>((abs_value % 100)); abs_value /= 100; *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } if (abs_value >= 10) { const auto digits_index = static_cast<unsigned>(abs_value); *(--buffer_ptr) = digits_to_99[digits_index][1]; *(--buffer_ptr) = digits_to_99[digits_index][0]; } else { *(--buffer_ptr) = static_cast<char>('0' + abs_value); } o->write_characters(number_buffer.data(), n_chars); } /*! @brief dump a floating-point number Dump a given floating-point number to output stream @a o. Works internally with @a number_buffer. @param[in] x floating-point number to dump */ void dump_float(number_float_t x) { // NaN / inf if (not std::isfinite(x)) { o->write_characters("null", 4); return; } // If number_float_t is an IEEE-754 single or double precision number, // use the Grisu2 algorithm to produce short numbers which are // guaranteed to round-trip, using strtof and strtod, resp. // // NB: The test below works if <long double> == <double>. static constexpr bool is_ieee_single_or_double = (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 24 and std::numeric_limits<number_float_t>::max_exponent == 128) or (std::numeric_limits<number_float_t>::is_iec559 and std::numeric_limits<number_float_t>::digits == 53 and std::numeric_limits<number_float_t>::max_exponent == 1024); dump_float(x, std::integral_constant<bool, is_ieee_single_or_double>()); } void dump_float(number_float_t x, std::true_type /*is_ieee_single_or_double*/) { char* begin = number_buffer.data(); char* end = ::nlohmann::detail::to_chars(begin, begin + number_buffer.size(), x); o->write_characters(begin, static_cast<size_t>(end - begin)); } void dump_float(number_float_t x, std::false_type /*is_ieee_single_or_double*/) { // get number of digits for a float -> text -> float round-trip static constexpr auto d = std::numeric_limits<number_float_t>::max_digits10; // the actual conversion std::ptrdiff_t len = (std::snprintf)(number_buffer.data(), number_buffer.size(), "%.*g", d, x); // negative value indicates an error assert(len > 0); // check if buffer was large enough assert(static_cast<std::size_t>(len) < number_buffer.size()); // erase thousands separator if (thousands_sep != '\0') { const auto end = std::remove(number_buffer.begin(), number_buffer.begin() + len, thousands_sep); std::fill(end, number_buffer.end(), '\0'); assert((end - number_buffer.begin()) <= len); len = (end - number_buffer.begin()); } // convert decimal point to '.' if (decimal_point != '\0' and decimal_point != '.') { const auto dec_pos = std::find(number_buffer.begin(), number_buffer.end(), decimal_point); if (dec_pos != number_buffer.end()) { *dec_pos = '.'; } } o->write_characters(number_buffer.data(), static_cast<std::size_t>(len)); // determine if need to append ".0" const bool value_is_int_like = std::none_of(number_buffer.begin(), number_buffer.begin() + len + 1, [](char c) { return (c == '.' or c == 'e'); }); if (value_is_int_like) { o->write_characters(".0", 2); } } /*! @brief check whether a string is UTF-8 encoded The function checks each byte of a string whether it is UTF-8 encoded. The result of the check is stored in the @a state parameter. The function must be called initially with state 0 (accept). State 1 means the string must be rejected, because the current byte is not allowed. If the string is completely processed, but the state is non-zero, the string ended prematurely; that is, the last byte indicated more bytes should have followed. @param[in,out] state the state of the decoding @param[in,out] codep codepoint (valid only if resulting state is UTF8_ACCEPT) @param[in] byte next byte to decode @return new state @note The function has been edited: a std::array is used. @copyright Copyright (c) 2008-2009 Bjoern Hoehrmann <bjoern@hoehrmann.de> @sa http://bjoern.hoehrmann.de/utf-8/decoder/dfa/ */ static uint8_t decode(uint8_t& state, uint32_t& codep, const uint8_t byte) noexcept { static const std::array<uint8_t, 400> utf8d = { { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 00..1F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 20..3F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 40..5F 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 60..7F 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, 9, // 80..9F 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, 7, // A0..BF 8, 8, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, // C0..DF 0xA, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x3, 0x4, 0x3, 0x3, // E0..EF 0xB, 0x6, 0x6, 0x6, 0x5, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, 0x8, // F0..FF 0x0, 0x1, 0x2, 0x3, 0x5, 0x8, 0x7, 0x1, 0x1, 0x1, 0x4, 0x6, 0x1, 0x1, 0x1, 0x1, // s0..s0 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, 1, 1, 0, 1, 0, 1, 1, 1, 1, 1, 1, // s1..s2 1, 2, 1, 1, 1, 1, 1, 2, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, // s3..s4 1, 2, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, // s5..s6 1, 3, 1, 1, 1, 1, 1, 3, 1, 3, 1, 1, 1, 1, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 // s7..s8 } }; const uint8_t type = utf8d[byte]; codep = (state != UTF8_ACCEPT) ? (byte & 0x3fu) | (codep << 6) : static_cast<uint32_t>(0xff >> type) & (byte); state = utf8d[256u + state * 16u + type]; return state; } private: /// the output of the serializer output_adapter_t<char> o = nullptr; /// a (hopefully) large enough character buffer std::array<char, 64> number_buffer{{}}; /// the locale const std::lconv* loc = nullptr; /// the locale's thousand separator character const char thousands_sep = '\0'; /// the locale's decimal point character const char decimal_point = '\0'; /// string buffer std::array<char, 512> string_buffer{{}}; /// the indentation character const char indent_char; /// the indentation string string_t indent_string; /// error_handler how to react on decoding errors const error_handler_t error_handler; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/json_ref.hpp> #include <initializer_list> #include <utility> // #include <nlohmann/detail/meta/type_traits.hpp> namespace nlohmann { namespace detail { template<typename BasicJsonType> class json_ref { public: using value_type = BasicJsonType; json_ref(value_type&& value) : owned_value(std::move(value)), value_ref(&owned_value), is_rvalue(true) {} json_ref(const value_type& value) : value_ref(const_cast<value_type*>(&value)), is_rvalue(false) {} json_ref(std::initializer_list<json_ref> init) : owned_value(init), value_ref(&owned_value), is_rvalue(true) {} template < class... Args, enable_if_t<std::is_constructible<value_type, Args...>::value, int> = 0 > json_ref(Args && ... args) : owned_value(std::forward<Args>(args)...), value_ref(&owned_value), is_rvalue(true) {} // class should be movable only json_ref(json_ref&&) = default; json_ref(const json_ref&) = delete; json_ref& operator=(const json_ref&) = delete; json_ref& operator=(json_ref&&) = delete; ~json_ref() = default; value_type moved_or_copied() const { if (is_rvalue) { return std::move(*value_ref); } return *value_ref; } value_type const& operator*() const { return *static_cast<value_type const*>(value_ref); } value_type const* operator->() const { return static_cast<value_type const*>(value_ref); } private: mutable value_type owned_value = nullptr; value_type* value_ref = nullptr; const bool is_rvalue; }; } // namespace detail } // namespace nlohmann // #include <nlohmann/detail/json_pointer.hpp> #include <algorithm> // all_of #include <cassert> // assert #include <numeric> // accumulate #include <string> // string #include <vector> // vector // #include <nlohmann/detail/macro_scope.hpp> // #include <nlohmann/detail/exceptions.hpp> // #include <nlohmann/detail/value_t.hpp> namespace nlohmann { template<typename BasicJsonType> class json_pointer { // allow basic_json to access private members NLOHMANN_BASIC_JSON_TPL_DECLARATION friend class basic_json; public: /*! @brief create JSON pointer Create a JSON pointer according to the syntax described in [Section 3 of RFC6901](https://tools.ietf.org/html/rfc6901#section-3). @param[in] s string representing the JSON pointer; if omitted, the empty string is assumed which references the whole JSON value @throw parse_error.107 if the given JSON pointer @a s is nonempty and does not begin with a slash (`/`); see example below @throw parse_error.108 if a tilde (`~`) in the given JSON pointer @a s is not followed by `0` (representing `~`) or `1` (representing `/`); see example below @liveexample{The example shows the construction several valid JSON pointers as well as the exceptional behavior.,json_pointer} @since version 2.0.0 */ explicit json_pointer(const std::string& s = "") : reference_tokens(split(s)) {} /*! @brief return a string representation of the JSON pointer @invariant For each JSON pointer `ptr`, it holds: @code {.cpp} ptr == json_pointer(ptr.to_string()); @endcode @return a string representation of the JSON pointer @liveexample{The example shows the result of `to_string`., json_pointer__to_string} @since version 2.0.0 */ std::string to_string() const { return std::accumulate(reference_tokens.begin(), reference_tokens.end(), std::string{}, [](const std::string & a, const std::string & b) { return a + "/" + escape(b); }); } /// @copydoc to_string() operator std::string() const { return to_string(); } /*! @param[in] s reference token to be converted into an array index @return integer representation of @a s @throw out_of_range.404 if string @a s could not be converted to an integer */ static int array_index(const std::string& s) { std::size_t processed_chars = 0; const int res = std::stoi(s, &processed_chars); // check if the string was completely read if (JSON_UNLIKELY(processed_chars != s.size())) { JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + s + "'")); } return res; } private: /*! @brief remove and return last reference pointer @throw out_of_range.405 if JSON pointer has no parent */ std::string pop_back() { if (JSON_UNLIKELY(is_root())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } auto last = reference_tokens.back(); reference_tokens.pop_back(); return last; } /// return whether pointer points to the root document bool is_root() const noexcept { return reference_tokens.empty(); } json_pointer top() const { if (JSON_UNLIKELY(is_root())) { JSON_THROW(detail::out_of_range::create(405, "JSON pointer has no parent")); } json_pointer result = *this; result.reference_tokens = {reference_tokens[0]}; return result; } /*! @brief create and return a reference to the pointed to value @complexity Linear in the number of reference tokens. @throw parse_error.109 if array index is not a number @throw type_error.313 if value cannot be unflattened */ BasicJsonType& get_and_create(BasicJsonType& j) const { using size_type = typename BasicJsonType::size_type; auto result = &j; // in case no reference tokens exist, return a reference to the JSON value // j which will be overwritten by a primitive value for (const auto& reference_token : reference_tokens) { switch (result->m_type) { case detail::value_t::null: { if (reference_token == "0") { // start a new array if reference token is 0 result = &result->operator[](0); } else { // start a new object otherwise result = &result->operator[](reference_token); } break; } case detail::value_t::object: { // create an entry in the object result = &result->operator[](reference_token); break; } case detail::value_t::array: { // create an entry in the array JSON_TRY { result = &result->operator[](static_cast<size_type>(array_index(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } /* The following code is only reached if there exists a reference token _and_ the current value is primitive. In this case, we have an error situation, because primitive values may only occur as single value; that is, with an empty list of reference tokens. */ default: JSON_THROW(detail::type_error::create(313, "invalid value to unflatten")); } } return *result; } /*! @brief return a reference to the pointed to value @note This version does not throw if a value is not present, but tries to create nested values instead. For instance, calling this function with pointer `"/this/that"` on a null value is equivalent to calling `operator[]("this").operator[]("that")` on that value, effectively changing the null value to an object. @param[in] ptr a JSON value @return reference to the JSON value pointed to by the JSON pointer @complexity Linear in the length of the JSON pointer. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_unchecked(BasicJsonType* ptr) const { using size_type = typename BasicJsonType::size_type; for (const auto& reference_token : reference_tokens) { // convert null values to arrays or objects before continuing if (ptr->m_type == detail::value_t::null) { // check if reference token is a number const bool nums = std::all_of(reference_token.begin(), reference_token.end(), [](const char x) { return (x >= '0' and x <= '9'); }); // change value to array for numbers or "-" or to object otherwise *ptr = (nums or reference_token == "-") ? detail::value_t::array : detail::value_t::object; } switch (ptr->m_type) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } if (reference_token == "-") { // explicitly treat "-" as index beyond the end ptr = &ptr->operator[](ptr->m_value.array->size()); } else { // convert array index to number; unchecked access JSON_TRY { ptr = &ptr->operator[]( static_cast<size_type>(array_index(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ BasicJsonType& get_checked(BasicJsonType* ptr) const { using size_type = typename BasicJsonType::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // note: at performs range check JSON_TRY { ptr = &ptr->at(static_cast<size_type>(array_index(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @brief return a const reference to the pointed to value @param[in] ptr a JSON value @return const reference to the JSON value pointed to by the JSON pointer @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_unchecked(const BasicJsonType* ptr) const { using size_type = typename BasicJsonType::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // use unchecked object access ptr = &ptr->operator[](reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" cannot be used for const access JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // use unchecked array access JSON_TRY { ptr = &ptr->operator[]( static_cast<size_type>(array_index(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved */ const BasicJsonType& get_checked(const BasicJsonType* ptr) const { using size_type = typename BasicJsonType::size_type; for (const auto& reference_token : reference_tokens) { switch (ptr->m_type) { case detail::value_t::object: { // note: at performs range check ptr = &ptr->at(reference_token); break; } case detail::value_t::array: { if (JSON_UNLIKELY(reference_token == "-")) { // "-" always fails the range check JSON_THROW(detail::out_of_range::create(402, "array index '-' (" + std::to_string(ptr->m_value.array->size()) + ") is out of range")); } // error condition (cf. RFC 6901, Sect. 4) if (JSON_UNLIKELY(reference_token.size() > 1 and reference_token[0] == '0')) { JSON_THROW(detail::parse_error::create(106, 0, "array index '" + reference_token + "' must not begin with '0'")); } // note: at performs range check JSON_TRY { ptr = &ptr->at(static_cast<size_type>(array_index(reference_token))); } JSON_CATCH(std::invalid_argument&) { JSON_THROW(detail::parse_error::create(109, 0, "array index '" + reference_token + "' is not a number")); } break; } default: JSON_THROW(detail::out_of_range::create(404, "unresolved reference token '" + reference_token + "'")); } } return *ptr; } /*! @brief split the string input to reference tokens @note This function is only called by the json_pointer constructor. All exceptions below are documented there. @throw parse_error.107 if the pointer is not empty or begins with '/' @throw parse_error.108 if character '~' is not followed by '0' or '1' */ static std::vector<std::string> split(const std::string& reference_string) { std::vector<std::string> result; // special case: empty reference string -> no reference tokens if (reference_string.empty()) { return result; } // check if nonempty reference string begins with slash if (JSON_UNLIKELY(reference_string[0] != '/')) { JSON_THROW(detail::parse_error::create(107, 1, "JSON pointer must be empty or begin with '/' - was: '" + reference_string + "'")); } // extract the reference tokens: // - slash: position of the last read slash (or end of string) // - start: position after the previous slash for ( // search for the first slash after the first character std::size_t slash = reference_string.find_first_of('/', 1), // set the beginning of the first reference token start = 1; // we can stop if start == 0 (if slash == std::string::npos) start != 0; // set the beginning of the next reference token // (will eventually be 0 if slash == std::string::npos) start = (slash == std::string::npos) ? 0 : slash + 1, // find next slash slash = reference_string.find_first_of('/', start)) { // use the text between the beginning of the reference token // (start) and the last slash (slash). auto reference_token = reference_string.substr(start, slash - start); // check reference tokens are properly escaped for (std::size_t pos = reference_token.find_first_of('~'); pos != std::string::npos; pos = reference_token.find_first_of('~', pos + 1)) { assert(reference_token[pos] == '~'); // ~ must be followed by 0 or 1 if (JSON_UNLIKELY(pos == reference_token.size() - 1 or (reference_token[pos + 1] != '0' and reference_token[pos + 1] != '1'))) { JSON_THROW(detail::parse_error::create(108, 0, "escape character '~' must be followed with '0' or '1'")); } } // finally, store the reference token unescape(reference_token); result.push_back(reference_token); } return result; } /*! @brief replace all occurrences of a substring by another string @param[in,out] s the string to manipulate; changed so that all occurrences of @a f are replaced with @a t @param[in] f the substring to replace with @a t @param[in] t the string to replace @a f @pre The search string @a f must not be empty. **This precondition is enforced with an assertion.** @since version 2.0.0 */ static void replace_substring(std::string& s, const std::string& f, const std::string& t) { assert(not f.empty()); for (auto pos = s.find(f); // find first occurrence of f pos != std::string::npos; // make sure f was found s.replace(pos, f.size(), t), // replace with t, and pos = s.find(f, pos + t.size())) // find next occurrence of f {} } /// escape "~" to "~0" and "/" to "~1" static std::string escape(std::string s) { replace_substring(s, "~", "~0"); replace_substring(s, "/", "~1"); return s; } /// unescape "~1" to tilde and "~0" to slash (order is important!) static void unescape(std::string& s) { replace_substring(s, "~1", "/"); replace_substring(s, "~0", "~"); } /*! @param[in] reference_string the reference string to the current value @param[in] value the value to consider @param[in,out] result the result object to insert values to @note Empty objects or arrays are flattened to `null`. */ static void flatten(const std::string& reference_string, const BasicJsonType& value, BasicJsonType& result) { switch (value.m_type) { case detail::value_t::array: { if (value.m_value.array->empty()) { // flatten empty array as null result[reference_string] = nullptr; } else { // iterate array and use index as reference string for (std::size_t i = 0; i < value.m_value.array->size(); ++i) { flatten(reference_string + "/" + std::to_string(i), value.m_value.array->operator[](i), result); } } break; } case detail::value_t::object: { if (value.m_value.object->empty()) { // flatten empty object as null result[reference_string] = nullptr; } else { // iterate object and use keys as reference string for (const auto& element : *value.m_value.object) { flatten(reference_string + "/" + escape(element.first), element.second, result); } } break; } default: { // add primitive value with its reference string result[reference_string] = value; break; } } } /*! @param[in] value flattened JSON @return unflattened JSON @throw parse_error.109 if array index is not a number @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @throw type_error.313 if value cannot be unflattened */ static BasicJsonType unflatten(const BasicJsonType& value) { if (JSON_UNLIKELY(not value.is_object())) { JSON_THROW(detail::type_error::create(314, "only objects can be unflattened")); } BasicJsonType result; // iterate the JSON object values for (const auto& element : *value.m_value.object) { if (JSON_UNLIKELY(not element.second.is_primitive())) { JSON_THROW(detail::type_error::create(315, "values in object must be primitive")); } // assign value to reference pointed to by JSON pointer; Note that if // the JSON pointer is "" (i.e., points to the whole value), function // get_and_create returns a reference to result itself. An assignment // will then create a primitive value. json_pointer(element.first).get_and_create(result) = element.second; } return result; } friend bool operator==(json_pointer const& lhs, json_pointer const& rhs) noexcept { return (lhs.reference_tokens == rhs.reference_tokens); } friend bool operator!=(json_pointer const& lhs, json_pointer const& rhs) noexcept { return not (lhs == rhs); } /// the reference tokens std::vector<std::string> reference_tokens; }; } // namespace nlohmann // #include <nlohmann/adl_serializer.hpp> #include <utility> // #include <nlohmann/detail/conversions/from_json.hpp> // #include <nlohmann/detail/conversions/to_json.hpp> namespace nlohmann { template<typename, typename> struct adl_serializer { /*! @brief convert a JSON value to any value type This function is usually called by the `get()` function of the @ref basic_json class (either explicit or via conversion operators). @param[in] j JSON value to read from @param[in,out] val value to write to */ template<typename BasicJsonType, typename ValueType> static auto from_json(BasicJsonType&& j, ValueType& val) noexcept( noexcept(::nlohmann::from_json(std::forward<BasicJsonType>(j), val))) -> decltype(::nlohmann::from_json(std::forward<BasicJsonType>(j), val), void()) { ::nlohmann::from_json(std::forward<BasicJsonType>(j), val); } /*! @brief convert any value type to a JSON value This function is usually called by the constructors of the @ref basic_json class. @param[in,out] j JSON value to write to @param[in] val value to read from */ template <typename BasicJsonType, typename ValueType> static auto to_json(BasicJsonType& j, ValueType&& val) noexcept( noexcept(::nlohmann::to_json(j, std::forward<ValueType>(val)))) -> decltype(::nlohmann::to_json(j, std::forward<ValueType>(val)), void()) { ::nlohmann::to_json(j, std::forward<ValueType>(val)); } }; } // namespace nlohmann /*! @brief namespace for Niels Lohmann @see https://github.com/nlohmann @since version 1.0.0 */ namespace nlohmann { /*! @brief a class to store JSON values @tparam ObjectType type for JSON objects (`std::map` by default; will be used in @ref object_t) @tparam ArrayType type for JSON arrays (`std::vector` by default; will be used in @ref array_t) @tparam StringType type for JSON strings and object keys (`std::string` by default; will be used in @ref string_t) @tparam BooleanType type for JSON booleans (`bool` by default; will be used in @ref boolean_t) @tparam NumberIntegerType type for JSON integer numbers (`int64_t` by default; will be used in @ref number_integer_t) @tparam NumberUnsignedType type for JSON unsigned integer numbers (@c `uint64_t` by default; will be used in @ref number_unsigned_t) @tparam NumberFloatType type for JSON floating-point numbers (`double` by default; will be used in @ref number_float_t) @tparam AllocatorType type of the allocator to use (`std::allocator` by default) @tparam JSONSerializer the serializer to resolve internal calls to `to_json()` and `from_json()` (@ref adl_serializer by default) @requirement The class satisfies the following concept requirements: - Basic - [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible): JSON values can be default constructed. The result will be a JSON null value. - [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible): A JSON value can be constructed from an rvalue argument. - [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible): A JSON value can be copy-constructed from an lvalue expression. - [MoveAssignable](https://en.cppreference.com/w/cpp/named_req/MoveAssignable): A JSON value van be assigned from an rvalue argument. - [CopyAssignable](https://en.cppreference.com/w/cpp/named_req/CopyAssignable): A JSON value can be copy-assigned from an lvalue expression. - [Destructible](https://en.cppreference.com/w/cpp/named_req/Destructible): JSON values can be destructed. - Layout - [StandardLayoutType](https://en.cppreference.com/w/cpp/named_req/StandardLayoutType): JSON values have [standard layout](https://en.cppreference.com/w/cpp/language/data_members#Standard_layout): All non-static data members are private and standard layout types, the class has no virtual functions or (virtual) base classes. - Library-wide - [EqualityComparable](https://en.cppreference.com/w/cpp/named_req/EqualityComparable): JSON values can be compared with `==`, see @ref operator==(const_reference,const_reference). - [LessThanComparable](https://en.cppreference.com/w/cpp/named_req/LessThanComparable): JSON values can be compared with `<`, see @ref operator<(const_reference,const_reference). - [Swappable](https://en.cppreference.com/w/cpp/named_req/Swappable): Any JSON lvalue or rvalue of can be swapped with any lvalue or rvalue of other compatible types, using unqualified function call @ref swap(). - [NullablePointer](https://en.cppreference.com/w/cpp/named_req/NullablePointer): JSON values can be compared against `std::nullptr_t` objects which are used to model the `null` value. - Container - [Container](https://en.cppreference.com/w/cpp/named_req/Container): JSON values can be used like STL containers and provide iterator access. - [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer); JSON values can be used like STL containers and provide reverse iterator access. @invariant The member variables @a m_value and @a m_type have the following relationship: - If `m_type == value_t::object`, then `m_value.object != nullptr`. - If `m_type == value_t::array`, then `m_value.array != nullptr`. - If `m_type == value_t::string`, then `m_value.string != nullptr`. The invariants are checked by member function assert_invariant(). @internal @note ObjectType trick from http://stackoverflow.com/a/9860911 @endinternal @see [RFC 7159: The JavaScript Object Notation (JSON) Data Interchange Format](http://rfc7159.net/rfc7159) @since version 1.0.0 @nosubgrouping */ NLOHMANN_BASIC_JSON_TPL_DECLARATION class basic_json { private: template<detail::value_t> friend struct detail::external_constructor; friend ::nlohmann::json_pointer<basic_json>; friend ::nlohmann::detail::parser<basic_json>; friend ::nlohmann::detail::serializer<basic_json>; template<typename BasicJsonType> friend class ::nlohmann::detail::iter_impl; template<typename BasicJsonType, typename CharType> friend class ::nlohmann::detail::binary_writer; template<typename BasicJsonType, typename SAX> friend class ::nlohmann::detail::binary_reader; template<typename BasicJsonType> friend class ::nlohmann::detail::json_sax_dom_parser; template<typename BasicJsonType> friend class ::nlohmann::detail::json_sax_dom_callback_parser; /// workaround type for MSVC using basic_json_t = NLOHMANN_BASIC_JSON_TPL; // convenience aliases for types residing in namespace detail; using lexer = ::nlohmann::detail::lexer<basic_json>; using parser = ::nlohmann::detail::parser<basic_json>; using primitive_iterator_t = ::nlohmann::detail::primitive_iterator_t; template<typename BasicJsonType> using internal_iterator = ::nlohmann::detail::internal_iterator<BasicJsonType>; template<typename BasicJsonType> using iter_impl = ::nlohmann::detail::iter_impl<BasicJsonType>; template<typename Iterator> using iteration_proxy = ::nlohmann::detail::iteration_proxy<Iterator>; template<typename Base> using json_reverse_iterator = ::nlohmann::detail::json_reverse_iterator<Base>; template<typename CharType> using output_adapter_t = ::nlohmann::detail::output_adapter_t<CharType>; using binary_reader = ::nlohmann::detail::binary_reader<basic_json>; template<typename CharType> using binary_writer = ::nlohmann::detail::binary_writer<basic_json, CharType>; using serializer = ::nlohmann::detail::serializer<basic_json>; public: using value_t = detail::value_t; /// JSON Pointer, see @ref nlohmann::json_pointer using json_pointer = ::nlohmann::json_pointer<basic_json>; template<typename T, typename SFINAE> using json_serializer = JSONSerializer<T, SFINAE>; /// how to treat decoding errors using error_handler_t = detail::error_handler_t; /// helper type for initializer lists of basic_json values using initializer_list_t = std::initializer_list<detail::json_ref<basic_json>>; using input_format_t = detail::input_format_t; /// SAX interface type, see @ref nlohmann::json_sax using json_sax_t = json_sax<basic_json>; //////////////// // exceptions // //////////////// /// @name exceptions /// Classes to implement user-defined exceptions. /// @{ /// @copydoc detail::exception using exception = detail::exception; /// @copydoc detail::parse_error using parse_error = detail::parse_error; /// @copydoc detail::invalid_iterator using invalid_iterator = detail::invalid_iterator; /// @copydoc detail::type_error using type_error = detail::type_error; /// @copydoc detail::out_of_range using out_of_range = detail::out_of_range; /// @copydoc detail::other_error using other_error = detail::other_error; /// @} ///////////////////// // container types // ///////////////////// /// @name container types /// The canonic container types to use @ref basic_json like any other STL /// container. /// @{ /// the type of elements in a basic_json container using value_type = basic_json; /// the type of an element reference using reference = value_type&; /// the type of an element const reference using const_reference = const value_type&; /// a type to represent differences between iterators using difference_type = std::ptrdiff_t; /// a type to represent container sizes using size_type = std::size_t; /// the allocator type using allocator_type = AllocatorType<basic_json>; /// the type of an element pointer using pointer = typename std::allocator_traits<allocator_type>::pointer; /// the type of an element const pointer using const_pointer = typename std::allocator_traits<allocator_type>::const_pointer; /// an iterator for a basic_json container using iterator = iter_impl<basic_json>; /// a const iterator for a basic_json container using const_iterator = iter_impl<const basic_json>; /// a reverse iterator for a basic_json container using reverse_iterator = json_reverse_iterator<typename basic_json::iterator>; /// a const reverse iterator for a basic_json container using const_reverse_iterator = json_reverse_iterator<typename basic_json::const_iterator>; /// @} /*! @brief returns the allocator associated with the container */ static allocator_type get_allocator() { return allocator_type(); } /*! @brief returns version information on the library This function returns a JSON object with information about the library, including the version number and information on the platform and compiler. @return JSON object holding version information key | description ----------- | --------------- `compiler` | Information on the used compiler. It is an object with the following keys: `c++` (the used C++ standard), `family` (the compiler family; possible values are `clang`, `icc`, `gcc`, `ilecpp`, `msvc`, `pgcpp`, `sunpro`, and `unknown`), and `version` (the compiler version). `copyright` | The copyright line for the library as string. `name` | The name of the library as string. `platform` | The used platform as string. Possible values are `win32`, `linux`, `apple`, `unix`, and `unknown`. `url` | The URL of the project as string. `version` | The version of the library. It is an object with the following keys: `major`, `minor`, and `patch` as defined by [Semantic Versioning](http://semver.org), and `string` (the version string). @liveexample{The following code shows an example output of the `meta()` function.,meta} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @complexity Constant. @since 2.1.0 */ static basic_json meta() { basic_json result; result["copyright"] = "(C) 2013-2017 Niels Lohmann"; result["name"] = "JSON for Modern C++"; result["url"] = "https://github.com/nlohmann/json"; result["version"]["string"] = std::to_string(NLOHMANN_JSON_VERSION_MAJOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_MINOR) + "." + std::to_string(NLOHMANN_JSON_VERSION_PATCH); result["version"]["major"] = NLOHMANN_JSON_VERSION_MAJOR; result["version"]["minor"] = NLOHMANN_JSON_VERSION_MINOR; result["version"]["patch"] = NLOHMANN_JSON_VERSION_PATCH; #ifdef _WIN32 result["platform"] = "win32"; #elif defined __linux__ result["platform"] = "linux"; #elif defined __APPLE__ result["platform"] = "apple"; #elif defined __unix__ result["platform"] = "unix"; #else result["platform"] = "unknown"; #endif #if defined(__ICC) || defined(__INTEL_COMPILER) result["compiler"] = {{"family", "icc"}, {"version", __INTEL_COMPILER}}; #elif defined(__clang__) result["compiler"] = {{"family", "clang"}, {"version", __clang_version__}}; #elif defined(__GNUC__) || defined(__GNUG__) result["compiler"] = {{"family", "gcc"}, {"version", std::to_string(__GNUC__) + "." + std::to_string(__GNUC_MINOR__) + "." + std::to_string(__GNUC_PATCHLEVEL__)}}; #elif defined(__HP_cc) || defined(__HP_aCC) result["compiler"] = "hp" #elif defined(__IBMCPP__) result["compiler"] = {{"family", "ilecpp"}, {"version", __IBMCPP__}}; #elif defined(_MSC_VER) result["compiler"] = {{"family", "msvc"}, {"version", _MSC_VER}}; #elif defined(__PGI) result["compiler"] = {{"family", "pgcpp"}, {"version", __PGI}}; #elif defined(__SUNPRO_CC) result["compiler"] = {{"family", "sunpro"}, {"version", __SUNPRO_CC}}; #else result["compiler"] = {{"family", "unknown"}, {"version", "unknown"}}; #endif #ifdef __cplusplus result["compiler"]["c++"] = std::to_string(__cplusplus); #else result["compiler"]["c++"] = "unknown"; #endif return result; } /////////////////////////// // JSON value data types // /////////////////////////// /// @name JSON value data types /// The data types to store a JSON value. These types are derived from /// the template arguments passed to class @ref basic_json. /// @{ #if defined(JSON_HAS_CPP_14) // Use transparent comparator if possible, combined with perfect forwarding // on find() and count() calls prevents unnecessary string construction. using object_comparator_t = std::less<>; #else using object_comparator_t = std::less<StringType>; #endif /*! @brief a type for an object [RFC 7159](http://rfc7159.net/rfc7159) describes JSON objects as follows: > An object is an unordered collection of zero or more name/value pairs, > where a name is a string and a value is a string, number, boolean, null, > object, or array. To store objects in C++, a type is defined by the template parameters described below. @tparam ObjectType the container to store objects (e.g., `std::map` or `std::unordered_map`) @tparam StringType the type of the keys or names (e.g., `std::string`). The comparison function `std::less<StringType>` is used to order elements inside the container. @tparam AllocatorType the allocator to use for objects (e.g., `std::allocator`) #### Default type With the default values for @a ObjectType (`std::map`), @a StringType (`std::string`), and @a AllocatorType (`std::allocator`), the default value for @a object_t is: @code {.cpp} std::map< std::string, // key_type basic_json, // value_type std::less<std::string>, // key_compare std::allocator<std::pair<const std::string, basic_json>> // allocator_type > @endcode #### Behavior The choice of @a object_t influences the behavior of the JSON class. With the default type, objects have the following behavior: - When all names are unique, objects will be interoperable in the sense that all software implementations receiving that object will agree on the name-value mappings. - When the names within an object are not unique, it is unspecified which one of the values for a given key will be chosen. For instance, `{"key": 2, "key": 1}` could be equal to either `{"key": 1}` or `{"key": 2}`. - Internally, name/value pairs are stored in lexicographical order of the names. Objects will also be serialized (see @ref dump) in this order. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be stored and serialized as `{"a": 2, "b": 1}`. - When comparing objects, the order of the name/value pairs is irrelevant. This makes objects interoperable in the sense that they will not be affected by these differences. For instance, `{"b": 1, "a": 2}` and `{"a": 2, "b": 1}` will be treated as equal. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the object's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON object. #### Storage Objects are stored as pointers in a @ref basic_json type. That is, for any access to object values, a pointer of type `object_t*` must be dereferenced. @sa @ref array_t -- type for an array value @since version 1.0.0 @note The order name/value pairs are added to the object is *not* preserved by the library. Therefore, iterating an object may return name/value pairs in a different order than they were originally stored. In fact, keys will be traversed in alphabetical order as `std::map` with `std::less` is used by default. Please note this behavior conforms to [RFC 7159](http://rfc7159.net/rfc7159), because any order implements the specified "unordered" nature of JSON objects. */ using object_t = ObjectType<StringType, basic_json, object_comparator_t, AllocatorType<std::pair<const StringType, basic_json>>>; /*! @brief a type for an array [RFC 7159](http://rfc7159.net/rfc7159) describes JSON arrays as follows: > An array is an ordered sequence of zero or more values. To store objects in C++, a type is defined by the template parameters explained below. @tparam ArrayType container type to store arrays (e.g., `std::vector` or `std::list`) @tparam AllocatorType allocator to use for arrays (e.g., `std::allocator`) #### Default type With the default values for @a ArrayType (`std::vector`) and @a AllocatorType (`std::allocator`), the default value for @a array_t is: @code {.cpp} std::vector< basic_json, // value_type std::allocator<basic_json> // allocator_type > @endcode #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the maximum depth of nesting. In this class, the array's limit of nesting is not explicitly constrained. However, a maximum depth of nesting may be introduced by the compiler or runtime environment. A theoretical limit can be queried by calling the @ref max_size function of a JSON array. #### Storage Arrays are stored as pointers in a @ref basic_json type. That is, for any access to array values, a pointer of type `array_t*` must be dereferenced. @sa @ref object_t -- type for an object value @since version 1.0.0 */ using array_t = ArrayType<basic_json, AllocatorType<basic_json>>; /*! @brief a type for a string [RFC 7159](http://rfc7159.net/rfc7159) describes JSON strings as follows: > A string is a sequence of zero or more Unicode characters. To store objects in C++, a type is defined by the template parameter described below. Unicode values are split by the JSON class into byte-sized characters during deserialization. @tparam StringType the container to store strings (e.g., `std::string`). Note this container is used for keys/names in objects, see @ref object_t. #### Default type With the default values for @a StringType (`std::string`), the default value for @a string_t is: @code {.cpp} std::string @endcode #### Encoding Strings are stored in UTF-8 encoding. Therefore, functions like `std::string::size()` or `std::string::length()` return the number of bytes in the string rather than the number of characters or glyphs. #### String comparison [RFC 7159](http://rfc7159.net/rfc7159) states: > Software implementations are typically required to test names of object > members for equality. Implementations that transform the textual > representation into sequences of Unicode code units and then perform the > comparison numerically, code unit by code unit, are interoperable in the > sense that implementations will agree in all cases on equality or > inequality of two strings. For example, implementations that compare > strings with escaped characters unconverted may incorrectly find that > `"a\\b"` and `"a\u005Cb"` are not equal. This implementation is interoperable as it does compare strings code unit by code unit. #### Storage String values are stored as pointers in a @ref basic_json type. That is, for any access to string values, a pointer of type `string_t*` must be dereferenced. @since version 1.0.0 */ using string_t = StringType; /*! @brief a type for a boolean [RFC 7159](http://rfc7159.net/rfc7159) implicitly describes a boolean as a type which differentiates the two literals `true` and `false`. To store objects in C++, a type is defined by the template parameter @a BooleanType which chooses the type to use. #### Default type With the default values for @a BooleanType (`bool`), the default value for @a boolean_t is: @code {.cpp} bool @endcode #### Storage Boolean values are stored directly inside a @ref basic_json type. @since version 1.0.0 */ using boolean_t = BooleanType; /*! @brief a type for a number (integer) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store integer numbers in C++, a type is defined by the template parameter @a NumberIntegerType which chooses the type to use. #### Default type With the default values for @a NumberIntegerType (`int64_t`), the default value for @a number_integer_t is: @code {.cpp} int64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `9223372036854775807` (INT64_MAX) and the minimal integer number that can be stored is `-9223372036854775808` (INT64_MIN). Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_unsigned_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange of the exactly supported range [INT64_MIN, INT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_integer_t = NumberIntegerType; /*! @brief a type for a number (unsigned) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store unsigned integer numbers in C++, a type is defined by the template parameter @a NumberUnsignedType which chooses the type to use. #### Default type With the default values for @a NumberUnsignedType (`uint64_t`), the default value for @a number_unsigned_t is: @code {.cpp} uint64_t @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in integer literals lead to an interpretation as octal number. Internally, the value will be stored as decimal number. For instance, the C++ integer literal `010` will be serialized to `8`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) specifies: > An implementation may set limits on the range and precision of numbers. When the default type is used, the maximal integer number that can be stored is `18446744073709551615` (UINT64_MAX) and the minimal integer number that can be stored is `0`. Integer numbers that are out of range will yield over/underflow when used in a constructor. During deserialization, too large or small integer numbers will be automatically be stored as @ref number_integer_t or @ref number_float_t. [RFC 7159](http://rfc7159.net/rfc7159) further states: > Note that when such software is used, numbers that are integers and are > in the range \f$[-2^{53}+1, 2^{53}-1]\f$ are interoperable in the sense > that implementations will agree exactly on their numeric values. As this range is a subrange (when considered in conjunction with the number_integer_t type) of the exactly supported range [0, UINT64_MAX], this class's integer type is interoperable. #### Storage Integer number values are stored directly inside a @ref basic_json type. @sa @ref number_float_t -- type for number values (floating-point) @sa @ref number_integer_t -- type for number values (integer) @since version 2.0.0 */ using number_unsigned_t = NumberUnsignedType; /*! @brief a type for a number (floating-point) [RFC 7159](http://rfc7159.net/rfc7159) describes numbers as follows: > The representation of numbers is similar to that used in most > programming languages. A number is represented in base 10 using decimal > digits. It contains an integer component that may be prefixed with an > optional minus sign, which may be followed by a fraction part and/or an > exponent part. Leading zeros are not allowed. (...) Numeric values that > cannot be represented in the grammar below (such as Infinity and NaN) > are not permitted. This description includes both integer and floating-point numbers. However, C++ allows more precise storage if it is known whether the number is a signed integer, an unsigned integer or a floating-point number. Therefore, three different types, @ref number_integer_t, @ref number_unsigned_t and @ref number_float_t are used. To store floating-point numbers in C++, a type is defined by the template parameter @a NumberFloatType which chooses the type to use. #### Default type With the default values for @a NumberFloatType (`double`), the default value for @a number_float_t is: @code {.cpp} double @endcode #### Default behavior - The restrictions about leading zeros is not enforced in C++. Instead, leading zeros in floating-point literals will be ignored. Internally, the value will be stored as decimal number. For instance, the C++ floating-point literal `01.2` will be serialized to `1.2`. During deserialization, leading zeros yield an error. - Not-a-number (NaN) values will be serialized to `null`. #### Limits [RFC 7159](http://rfc7159.net/rfc7159) states: > This specification allows implementations to set limits on the range and > precision of numbers accepted. Since software that implements IEEE > 754-2008 binary64 (double precision) numbers is generally available and > widely used, good interoperability can be achieved by implementations > that expect no more precision or range than these provide, in the sense > that implementations will approximate JSON numbers within the expected > precision. This implementation does exactly follow this approach, as it uses double precision floating-point numbers. Note values smaller than `-1.79769313486232e+308` and values greater than `1.79769313486232e+308` will be stored as NaN internally and be serialized to `null`. #### Storage Floating-point number values are stored directly inside a @ref basic_json type. @sa @ref number_integer_t -- type for number values (integer) @sa @ref number_unsigned_t -- type for number values (unsigned integer) @since version 1.0.0 */ using number_float_t = NumberFloatType; /// @} private: /// helper for exception-safe object creation template<typename T, typename... Args> static T* create(Args&& ... args) { AllocatorType<T> alloc; using AllocatorTraits = std::allocator_traits<AllocatorType<T>>; auto deleter = [&](T * object) { AllocatorTraits::deallocate(alloc, object, 1); }; std::unique_ptr<T, decltype(deleter)> object(AllocatorTraits::allocate(alloc, 1), deleter); AllocatorTraits::construct(alloc, object.get(), std::forward<Args>(args)...); assert(object != nullptr); return object.release(); } //////////////////////// // JSON value storage // //////////////////////// /*! @brief a JSON value The actual storage for a JSON value of the @ref basic_json class. This union combines the different storage types for the JSON value types defined in @ref value_t. JSON type | value_t type | used type --------- | --------------- | ------------------------ object | object | pointer to @ref object_t array | array | pointer to @ref array_t string | string | pointer to @ref string_t boolean | boolean | @ref boolean_t number | number_integer | @ref number_integer_t number | number_unsigned | @ref number_unsigned_t number | number_float | @ref number_float_t null | null | *no value is stored* @note Variable-length types (objects, arrays, and strings) are stored as pointers. The size of the union should not exceed 64 bits if the default value types are used. @since version 1.0.0 */ union json_value { /// object (stored with pointer to save storage) object_t* object; /// array (stored with pointer to save storage) array_t* array; /// string (stored with pointer to save storage) string_t* string; /// boolean boolean_t boolean; /// number (integer) number_integer_t number_integer; /// number (unsigned integer) number_unsigned_t number_unsigned; /// number (floating-point) number_float_t number_float; /// default constructor (for null values) json_value() = default; /// constructor for booleans json_value(boolean_t v) noexcept : boolean(v) {} /// constructor for numbers (integer) json_value(number_integer_t v) noexcept : number_integer(v) {} /// constructor for numbers (unsigned) json_value(number_unsigned_t v) noexcept : number_unsigned(v) {} /// constructor for numbers (floating-point) json_value(number_float_t v) noexcept : number_float(v) {} /// constructor for empty values of a given type json_value(value_t t) { switch (t) { case value_t::object: { object = create<object_t>(); break; } case value_t::array: { array = create<array_t>(); break; } case value_t::string: { string = create<string_t>(""); break; } case value_t::boolean: { boolean = boolean_t(false); break; } case value_t::number_integer: { number_integer = number_integer_t(0); break; } case value_t::number_unsigned: { number_unsigned = number_unsigned_t(0); break; } case value_t::number_float: { number_float = number_float_t(0.0); break; } case value_t::null: { object = nullptr; // silence warning, see #821 break; } default: { object = nullptr; // silence warning, see #821 if (JSON_UNLIKELY(t == value_t::null)) { JSON_THROW(other_error::create(500, "961c151d2e87f2686a955a9be24d316f1362bf21 3.5.0")); // LCOV_EXCL_LINE } break; } } } /// constructor for strings json_value(const string_t& value) { string = create<string_t>(value); } /// constructor for rvalue strings json_value(string_t&& value) { string = create<string_t>(std::move(value)); } /// constructor for objects json_value(const object_t& value) { object = create<object_t>(value); } /// constructor for rvalue objects json_value(object_t&& value) { object = create<object_t>(std::move(value)); } /// constructor for arrays json_value(const array_t& value) { array = create<array_t>(value); } /// constructor for rvalue arrays json_value(array_t&& value) { array = create<array_t>(std::move(value)); } void destroy(value_t t) noexcept { switch (t) { case value_t::object: { AllocatorType<object_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, object); std::allocator_traits<decltype(alloc)>::deallocate(alloc, object, 1); break; } case value_t::array: { AllocatorType<array_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, array); std::allocator_traits<decltype(alloc)>::deallocate(alloc, array, 1); break; } case value_t::string: { AllocatorType<string_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, string); std::allocator_traits<decltype(alloc)>::deallocate(alloc, string, 1); break; } default: { break; } } } }; /*! @brief checks the class invariants This function asserts the class invariants. It needs to be called at the end of every constructor to make sure that created objects respect the invariant. Furthermore, it has to be called each time the type of a JSON value is changed, because the invariant expresses a relationship between @a m_type and @a m_value. */ void assert_invariant() const noexcept { assert(m_type != value_t::object or m_value.object != nullptr); assert(m_type != value_t::array or m_value.array != nullptr); assert(m_type != value_t::string or m_value.string != nullptr); } public: ////////////////////////// // JSON parser callback // ////////////////////////// /*! @brief parser event types The parser callback distinguishes the following events: - `object_start`: the parser read `{` and started to process a JSON object - `key`: the parser read a key of a value in an object - `object_end`: the parser read `}` and finished processing a JSON object - `array_start`: the parser read `[` and started to process a JSON array - `array_end`: the parser read `]` and finished processing a JSON array - `value`: the parser finished reading a JSON value @image html callback_events.png "Example when certain parse events are triggered" @sa @ref parser_callback_t for more information and examples */ using parse_event_t = typename parser::parse_event_t; /*! @brief per-element parser callback type With a parser callback function, the result of parsing a JSON text can be influenced. When passed to @ref parse, it is called on certain events (passed as @ref parse_event_t via parameter @a event) with a set recursion depth @a depth and context JSON value @a parsed. The return value of the callback function is a boolean indicating whether the element that emitted the callback shall be kept or not. We distinguish six scenarios (determined by the event type) in which the callback function can be called. The following table describes the values of the parameters @a depth, @a event, and @a parsed. parameter @a event | description | parameter @a depth | parameter @a parsed ------------------ | ----------- | ------------------ | ------------------- parse_event_t::object_start | the parser read `{` and started to process a JSON object | depth of the parent of the JSON object | a JSON value with type discarded parse_event_t::key | the parser read a key of a value in an object | depth of the currently parsed JSON object | a JSON string containing the key parse_event_t::object_end | the parser read `}` and finished processing a JSON object | depth of the parent of the JSON object | the parsed JSON object parse_event_t::array_start | the parser read `[` and started to process a JSON array | depth of the parent of the JSON array | a JSON value with type discarded parse_event_t::array_end | the parser read `]` and finished processing a JSON array | depth of the parent of the JSON array | the parsed JSON array parse_event_t::value | the parser finished reading a JSON value | depth of the value | the parsed JSON value @image html callback_events.png "Example when certain parse events are triggered" Discarding a value (i.e., returning `false`) has different effects depending on the context in which function was called: - Discarded values in structured types are skipped. That is, the parser will behave as if the discarded value was never read. - In case a value outside a structured type is skipped, it is replaced with `null`. This case happens if the top-level element is skipped. @param[in] depth the depth of the recursion during parsing @param[in] event an event of type parse_event_t indicating the context in the callback function has been called @param[in,out] parsed the current intermediate parse result; note that writing to this value has no effect for parse_event_t::key events @return Whether the JSON value which called the function during parsing should be kept (`true`) or not (`false`). In the latter case, it is either skipped completely or replaced by an empty discarded object. @sa @ref parse for examples @since version 1.0.0 */ using parser_callback_t = typename parser::parser_callback_t; ////////////////// // constructors // ////////////////// /// @name constructors and destructors /// Constructors of class @ref basic_json, copy/move constructor, copy /// assignment, static functions creating objects, and the destructor. /// @{ /*! @brief create an empty value with a given type Create an empty JSON value with a given type. The value will be default initialized with an empty value which depends on the type: Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @param[in] v the type of the value to create @complexity Constant. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor for different @ref value_t values,basic_json__value_t} @sa @ref clear() -- restores the postcondition of this constructor @since version 1.0.0 */ basic_json(const value_t v) : m_type(v), m_value(v) { assert_invariant(); } /*! @brief create a null object Create a `null` JSON value. It either takes a null pointer as parameter (explicitly creating `null`) or no parameter (implicitly creating `null`). The passed null pointer itself is not read -- it is only used to choose the right constructor. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @liveexample{The following code shows the constructor with and without a null pointer parameter.,basic_json__nullptr_t} @since version 1.0.0 */ basic_json(std::nullptr_t = nullptr) noexcept : basic_json(value_t::null) { assert_invariant(); } /*! @brief create a JSON value This is a "catch all" constructor for all compatible JSON types; that is, types for which a `to_json()` method exists. The constructor forwards the parameter @a val to that method (to `json_serializer<U>::to_json` method with `U = uncvref_t<CompatibleType>`, to be exact). Template type @a CompatibleType includes, but is not limited to, the following types: - **arrays**: @ref array_t and all kinds of compatible containers such as `std::vector`, `std::deque`, `std::list`, `std::forward_list`, `std::array`, `std::valarray`, `std::set`, `std::unordered_set`, `std::multiset`, and `std::unordered_multiset` with a `value_type` from which a @ref basic_json value can be constructed. - **objects**: @ref object_t and all kinds of compatible associative containers such as `std::map`, `std::unordered_map`, `std::multimap`, and `std::unordered_multimap` with a `key_type` compatible to @ref string_t and a `value_type` from which a @ref basic_json value can be constructed. - **strings**: @ref string_t, string literals, and all compatible string containers can be used. - **numbers**: @ref number_integer_t, @ref number_unsigned_t, @ref number_float_t, and all convertible number types such as `int`, `size_t`, `int64_t`, `float` or `double` can be used. - **boolean**: @ref boolean_t / `bool` can be used. See the examples below. @tparam CompatibleType a type such that: - @a CompatibleType is not derived from `std::istream`, - @a CompatibleType is not @ref basic_json (to avoid hijacking copy/move constructors), - @a CompatibleType is not a different @ref basic_json type (i.e. with different template arguments) - @a CompatibleType is not a @ref basic_json nested type (e.g., @ref json_pointer, @ref iterator, etc ...) - @ref @ref json_serializer<U> has a `to_json(basic_json_t&, CompatibleType&&)` method @tparam U = `uncvref_t<CompatibleType>` @param[in] val the value to be forwarded to the respective constructor @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows the constructor with several compatible types.,basic_json__CompatibleType} @since version 2.1.0 */ template <typename CompatibleType, typename U = detail::uncvref_t<CompatibleType>, detail::enable_if_t< not detail::is_basic_json<U>::value and detail::is_compatible_type<basic_json_t, U>::value, int> = 0> basic_json(CompatibleType && val) noexcept(noexcept( JSONSerializer<U>::to_json(std::declval<basic_json_t&>(), std::forward<CompatibleType>(val)))) { JSONSerializer<U>::to_json(*this, std::forward<CompatibleType>(val)); assert_invariant(); } /*! @brief create a JSON value from an existing one This is a constructor for existing @ref basic_json types. It does not hijack copy/move constructors, since the parameter has different template arguments than the current ones. The constructor tries to convert the internal @ref m_value of the parameter. @tparam BasicJsonType a type such that: - @a BasicJsonType is a @ref basic_json type. - @a BasicJsonType has different template arguments than @ref basic_json_t. @param[in] val the @ref basic_json value to be converted. @complexity Usually linear in the size of the passed @a val, also depending on the implementation of the called `to_json()` method. @exceptionsafety Depends on the called constructor. For types directly supported by the library (i.e., all types for which no `to_json()` function was provided), strong guarantee holds: if an exception is thrown, there are no changes to any JSON value. @since version 3.2.0 */ template <typename BasicJsonType, detail::enable_if_t< detail::is_basic_json<BasicJsonType>::value and not std::is_same<basic_json, BasicJsonType>::value, int> = 0> basic_json(const BasicJsonType& val) { using other_boolean_t = typename BasicJsonType::boolean_t; using other_number_float_t = typename BasicJsonType::number_float_t; using other_number_integer_t = typename BasicJsonType::number_integer_t; using other_number_unsigned_t = typename BasicJsonType::number_unsigned_t; using other_string_t = typename BasicJsonType::string_t; using other_object_t = typename BasicJsonType::object_t; using other_array_t = typename BasicJsonType::array_t; switch (val.type()) { case value_t::boolean: JSONSerializer<other_boolean_t>::to_json(*this, val.template get<other_boolean_t>()); break; case value_t::number_float: JSONSerializer<other_number_float_t>::to_json(*this, val.template get<other_number_float_t>()); break; case value_t::number_integer: JSONSerializer<other_number_integer_t>::to_json(*this, val.template get<other_number_integer_t>()); break; case value_t::number_unsigned: JSONSerializer<other_number_unsigned_t>::to_json(*this, val.template get<other_number_unsigned_t>()); break; case value_t::string: JSONSerializer<other_string_t>::to_json(*this, val.template get_ref<const other_string_t&>()); break; case value_t::object: JSONSerializer<other_object_t>::to_json(*this, val.template get_ref<const other_object_t&>()); break; case value_t::array: JSONSerializer<other_array_t>::to_json(*this, val.template get_ref<const other_array_t&>()); break; case value_t::null: *this = nullptr; break; case value_t::discarded: m_type = value_t::discarded; break; } assert_invariant(); } /*! @brief create a container (array or object) from an initializer list Creates a JSON value of type array or object from the passed initializer list @a init. In case @a type_deduction is `true` (default), the type of the JSON value to be created is deducted from the initializer list @a init according to the following rules: 1. If the list is empty, an empty JSON object value `{}` is created. 2. If the list consists of pairs whose first element is a string, a JSON object value is created where the first elements of the pairs are treated as keys and the second elements are as values. 3. In all other cases, an array is created. The rules aim to create the best fit between a C++ initializer list and JSON values. The rationale is as follows: 1. The empty initializer list is written as `{}` which is exactly an empty JSON object. 2. C++ has no way of describing mapped types other than to list a list of pairs. As JSON requires that keys must be of type string, rule 2 is the weakest constraint one can pose on initializer lists to interpret them as an object. 3. In all other cases, the initializer list could not be interpreted as JSON object type, so interpreting it as JSON array type is safe. With the rules described above, the following JSON values cannot be expressed by an initializer list: - the empty array (`[]`): use @ref array(initializer_list_t) with an empty initializer list in this case - arrays whose elements satisfy rule 2: use @ref array(initializer_list_t) with the same initializer list in this case @note When used without parentheses around an empty initializer list, @ref basic_json() is called instead of this function, yielding the JSON null value. @param[in] init initializer list with JSON values @param[in] type_deduction internal parameter; when set to `true`, the type of the JSON value is deducted from the initializer list @a init; when set to `false`, the type provided via @a manual_type is forced. This mode is used by the functions @ref array(initializer_list_t) and @ref object(initializer_list_t). @param[in] manual_type internal parameter; when @a type_deduction is set to `false`, the created JSON value will use the provided type (only @ref value_t::array and @ref value_t::object are valid); when @a type_deduction is set to `true`, this parameter has no effect @throw type_error.301 if @a type_deduction is `false`, @a manual_type is `value_t::object`, but @a init contains an element which is not a pair whose first element is a string. In this case, the constructor could not create an object. If @a type_deduction would have be `true`, an array would have been created. See @ref object(initializer_list_t) for an example. @complexity Linear in the size of the initializer list @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows how JSON values are created from initializer lists.,basic_json__list_init_t} @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ basic_json(initializer_list_t init, bool type_deduction = true, value_t manual_type = value_t::array) { // check if each element is an array with two elements whose first // element is a string bool is_an_object = std::all_of(init.begin(), init.end(), [](const detail::json_ref<basic_json>& element_ref) { return (element_ref->is_array() and element_ref->size() == 2 and (*element_ref)[0].is_string()); }); // adjust type if type deduction is not wanted if (not type_deduction) { // if array is wanted, do not create an object though possible if (manual_type == value_t::array) { is_an_object = false; } // if object is wanted but impossible, throw an exception if (JSON_UNLIKELY(manual_type == value_t::object and not is_an_object)) { JSON_THROW(type_error::create(301, "cannot create object from initializer list")); } } if (is_an_object) { // the initializer list is a list of pairs -> create object m_type = value_t::object; m_value = value_t::object; std::for_each(init.begin(), init.end(), [this](const detail::json_ref<basic_json>& element_ref) { auto element = element_ref.moved_or_copied(); m_value.object->emplace( std::move(*((*element.m_value.array)[0].m_value.string)), std::move((*element.m_value.array)[1])); }); } else { // the initializer list describes an array -> create array m_type = value_t::array; m_value.array = create<array_t>(init.begin(), init.end()); } assert_invariant(); } /*! @brief explicitly create an array from an initializer list Creates a JSON array value from a given initializer list. That is, given a list of values `a, b, c`, creates the JSON value `[a, b, c]`. If the initializer list is empty, the empty array `[]` is created. @note This function is only needed to express two edge cases that cannot be realized with the initializer list constructor (@ref basic_json(initializer_list_t, bool, value_t)). These cases are: 1. creating an array whose elements are all pairs whose first element is a string -- in this case, the initializer list constructor would create an object, taking the first elements as keys 2. creating an empty array -- passing the empty initializer list to the initializer list constructor yields an empty object @param[in] init initializer list with JSON values to create an array from (optional) @return JSON array value @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `array` function.,array} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref object(initializer_list_t) -- create a JSON object value from an initializer list @since version 1.0.0 */ static basic_json array(initializer_list_t init = {}) { return basic_json(init, false, value_t::array); } /*! @brief explicitly create an object from an initializer list Creates a JSON object value from a given initializer list. The initializer lists elements must be pairs, and their first elements must be strings. If the initializer list is empty, the empty object `{}` is created. @note This function is only added for symmetry reasons. In contrast to the related function @ref array(initializer_list_t), there are no cases which can only be expressed by this function. That is, any initializer list @a init can also be passed to the initializer list constructor @ref basic_json(initializer_list_t, bool, value_t). @param[in] init initializer list to create an object from (optional) @return JSON object value @throw type_error.301 if @a init is not a list of pairs whose first elements are strings. In this case, no object can be created. When such a value is passed to @ref basic_json(initializer_list_t, bool, value_t), an array would have been created from the passed initializer list @a init. See example below. @complexity Linear in the size of @a init. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows an example for the `object` function.,object} @sa @ref basic_json(initializer_list_t, bool, value_t) -- create a JSON value from an initializer list @sa @ref array(initializer_list_t) -- create a JSON array value from an initializer list @since version 1.0.0 */ static basic_json object(initializer_list_t init = {}) { return basic_json(init, false, value_t::object); } /*! @brief construct an array with count copies of given value Constructs a JSON array value by creating @a cnt copies of a passed value. In case @a cnt is `0`, an empty array is created. @param[in] cnt the number of JSON copies of @a val to create @param[in] val the JSON value to copy @post `std::distance(begin(),end()) == cnt` holds. @complexity Linear in @a cnt. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The following code shows examples for the @ref basic_json(size_type\, const basic_json&) constructor.,basic_json__size_type_basic_json} @since version 1.0.0 */ basic_json(size_type cnt, const basic_json& val) : m_type(value_t::array) { m_value.array = create<array_t>(cnt, val); assert_invariant(); } /*! @brief construct a JSON container given an iterator range Constructs the JSON value with the contents of the range `[first, last)`. The semantics depends on the different types a JSON value can have: - In case of a null type, invalid_iterator.206 is thrown. - In case of other primitive types (number, boolean, or string), @a first must be `begin()` and @a last must be `end()`. In this case, the value is copied. Otherwise, invalid_iterator.204 is thrown. - In case of structured types (array, object), the constructor behaves as similar versions for `std::vector` or `std::map`; that is, a JSON array or object is constructed from the values in the range. @tparam InputIT an input iterator type (@ref iterator or @ref const_iterator) @param[in] first begin of the range to copy from (included) @param[in] last end of the range to copy from (excluded) @pre Iterators @a first and @a last must be initialized. **This precondition is enforced with an assertion (see warning).** If assertions are switched off, a violation of this precondition yields undefined behavior. @pre Range `[first, last)` is valid. Usually, this precondition cannot be checked efficiently. Only certain edge cases are detected; see the description of the exceptions below. A violation of this precondition yields undefined behavior. @warning A precondition is enforced with a runtime assertion that will result in calling `std::abort` if this precondition is not met. Assertions can be disabled by defining `NDEBUG` at compile time. See https://en.cppreference.com/w/cpp/error/assert for more information. @throw invalid_iterator.201 if iterators @a first and @a last are not compatible (i.e., do not belong to the same JSON value). In this case, the range `[first, last)` is undefined. @throw invalid_iterator.204 if iterators @a first and @a last belong to a primitive type (number, boolean, or string), but @a first does not point to the first element any more. In this case, the range `[first, last)` is undefined. See example code below. @throw invalid_iterator.206 if iterators @a first and @a last belong to a null value. In this case, the range `[first, last)` is undefined. @complexity Linear in distance between @a first and @a last. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @liveexample{The example below shows several ways to create JSON values by specifying a subrange with iterators.,basic_json__InputIt_InputIt} @since version 1.0.0 */ template<class InputIT, typename std::enable_if< std::is_same<InputIT, typename basic_json_t::iterator>::value or std::is_same<InputIT, typename basic_json_t::const_iterator>::value, int>::type = 0> basic_json(InputIT first, InputIT last) { assert(first.m_object != nullptr); assert(last.m_object != nullptr); // make sure iterator fits the current value if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(201, "iterators are not compatible")); } // copy type from first iterator m_type = first.m_object->m_type; // check if iterator range is complete for primitive values switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_UNLIKELY(not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } break; } default: break; } switch (m_type) { case value_t::number_integer: { m_value.number_integer = first.m_object->m_value.number_integer; break; } case value_t::number_unsigned: { m_value.number_unsigned = first.m_object->m_value.number_unsigned; break; } case value_t::number_float: { m_value.number_float = first.m_object->m_value.number_float; break; } case value_t::boolean: { m_value.boolean = first.m_object->m_value.boolean; break; } case value_t::string: { m_value = *first.m_object->m_value.string; break; } case value_t::object: { m_value.object = create<object_t>(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { m_value.array = create<array_t>(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(invalid_iterator::create(206, "cannot construct with iterators from " + std::string(first.m_object->type_name()))); } assert_invariant(); } /////////////////////////////////////// // other constructors and destructor // /////////////////////////////////////// /// @private basic_json(const detail::json_ref<basic_json>& ref) : basic_json(ref.moved_or_copied()) {} /*! @brief copy constructor Creates a copy of a given JSON value. @param[in] other the JSON value to copy @post `*this == other` @complexity Linear in the size of @a other. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes to any JSON value. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. - As postcondition, it holds: `other == basic_json(other)`. @liveexample{The following code shows an example for the copy constructor.,basic_json__basic_json} @since version 1.0.0 */ basic_json(const basic_json& other) : m_type(other.m_type) { // check of passed value is valid other.assert_invariant(); switch (m_type) { case value_t::object: { m_value = *other.m_value.object; break; } case value_t::array: { m_value = *other.m_value.array; break; } case value_t::string: { m_value = *other.m_value.string; break; } case value_t::boolean: { m_value = other.m_value.boolean; break; } case value_t::number_integer: { m_value = other.m_value.number_integer; break; } case value_t::number_unsigned: { m_value = other.m_value.number_unsigned; break; } case value_t::number_float: { m_value = other.m_value.number_float; break; } default: break; } assert_invariant(); } /*! @brief move constructor Move constructor. Constructs a JSON value with the contents of the given value @a other using move semantics. It "steals" the resources from @a other and leaves it as JSON null value. @param[in,out] other value to move to this object @post `*this` has the same value as @a other before the call. @post @a other is a JSON null value. @complexity Constant. @exceptionsafety No-throw guarantee: this constructor never throws exceptions. @requirement This function helps `basic_json` satisfying the [MoveConstructible](https://en.cppreference.com/w/cpp/named_req/MoveConstructible) requirements. @liveexample{The code below shows the move constructor explicitly called via std::move.,basic_json__moveconstructor} @since version 1.0.0 */ basic_json(basic_json&& other) noexcept : m_type(std::move(other.m_type)), m_value(std::move(other.m_value)) { // check that passed value is valid other.assert_invariant(); // invalidate payload other.m_type = value_t::null; other.m_value = {}; assert_invariant(); } /*! @brief copy assignment Copy assignment operator. Copies a JSON value via the "copy and swap" strategy: It is expressed in terms of the copy constructor, destructor, and the `swap()` member function. @param[in] other value to copy from @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. @liveexample{The code below shows and example for the copy assignment. It creates a copy of value `a` which is then swapped with `b`. Finally\, the copy of `a` (which is the null value after the swap) is destroyed.,basic_json__copyassignment} @since version 1.0.0 */ basic_json& operator=(basic_json other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { // check that passed value is valid other.assert_invariant(); using std::swap; swap(m_type, other.m_type); swap(m_value, other.m_value); assert_invariant(); return *this; } /*! @brief destructor Destroys the JSON value and frees all allocated memory. @complexity Linear. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is linear. - All stored elements are destroyed and all memory is freed. @since version 1.0.0 */ ~basic_json() noexcept { assert_invariant(); m_value.destroy(m_type); } /// @} public: /////////////////////// // object inspection // /////////////////////// /// @name object inspection /// Functions to inspect the type of a JSON value. /// @{ /*! @brief serialization Serialization function for JSON values. The function tries to mimic Python's `json.dumps()` function, and currently supports its @a indent and @a ensure_ascii parameters. @param[in] indent If indent is nonnegative, then array elements and object members will be pretty-printed with that indent level. An indent level of `0` will only insert newlines. `-1` (the default) selects the most compact representation. @param[in] indent_char The character to use for indentation if @a indent is greater than `0`. The default is ` ` (space). @param[in] ensure_ascii If @a ensure_ascii is true, all non-ASCII characters in the output are escaped with `\uXXXX` sequences, and the result consists of ASCII characters only. @param[in] error_handler how to react on decoding errors; there are three possible values: `strict` (throws and exception in case a decoding error occurs; default), `replace` (replace invalid UTF-8 sequences with U+FFFD), and `ignore` (ignore invalid UTF-8 sequences during serialization). @return string containing the serialization of the JSON value @throw type_error.316 if a string stored inside the JSON value is not UTF-8 encoded @complexity Linear. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @liveexample{The following example shows the effect of different @a indent\, @a indent_char\, and @a ensure_ascii parameters to the result of the serialization.,dump} @see https://docs.python.org/2/library/json.html#json.dump @since version 1.0.0; indentation character @a indent_char, option @a ensure_ascii and exceptions added in version 3.0.0; error handlers added in version 3.4.0. */ string_t dump(const int indent = -1, const char indent_char = ' ', const bool ensure_ascii = false, const error_handler_t error_handler = error_handler_t::strict) const { string_t result; serializer s(detail::output_adapter<char, string_t>(result), indent_char, error_handler); if (indent >= 0) { s.dump(*this, true, ensure_ascii, static_cast<unsigned int>(indent)); } else { s.dump(*this, false, ensure_ascii, 0); } return result; } /*! @brief return the type of the JSON value (explicit) Return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value Value type | return value ------------------------- | ------------------------- null | value_t::null boolean | value_t::boolean string | value_t::string number (integer) | value_t::number_integer number (unsigned integer) | value_t::number_unsigned number (floating-point) | value_t::number_float object | value_t::object array | value_t::array discarded | value_t::discarded @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `type()` for all JSON types.,type} @sa @ref operator value_t() -- return the type of the JSON value (implicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr value_t type() const noexcept { return m_type; } /*! @brief return whether type is primitive This function returns true if and only if the JSON type is primitive (string, number, boolean, or null). @return `true` if type is primitive (string, number, boolean, or null), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_primitive()` for all JSON types.,is_primitive} @sa @ref is_structured() -- returns whether JSON value is structured @sa @ref is_null() -- returns whether JSON value is `null` @sa @ref is_string() -- returns whether JSON value is a string @sa @ref is_boolean() -- returns whether JSON value is a boolean @sa @ref is_number() -- returns whether JSON value is a number @since version 1.0.0 */ constexpr bool is_primitive() const noexcept { return is_null() or is_string() or is_boolean() or is_number(); } /*! @brief return whether type is structured This function returns true if and only if the JSON type is structured (array or object). @return `true` if type is structured (array or object), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_structured()` for all JSON types.,is_structured} @sa @ref is_primitive() -- returns whether value is primitive @sa @ref is_array() -- returns whether value is an array @sa @ref is_object() -- returns whether value is an object @since version 1.0.0 */ constexpr bool is_structured() const noexcept { return is_array() or is_object(); } /*! @brief return whether value is null This function returns true if and only if the JSON value is null. @return `true` if type is null, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_null()` for all JSON types.,is_null} @since version 1.0.0 */ constexpr bool is_null() const noexcept { return (m_type == value_t::null); } /*! @brief return whether value is a boolean This function returns true if and only if the JSON value is a boolean. @return `true` if type is boolean, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_boolean()` for all JSON types.,is_boolean} @since version 1.0.0 */ constexpr bool is_boolean() const noexcept { return (m_type == value_t::boolean); } /*! @brief return whether value is a number This function returns true if and only if the JSON value is a number. This includes both integer (signed and unsigned) and floating-point values. @return `true` if type is number (regardless whether integer, unsigned integer or floating-type), `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number()` for all JSON types.,is_number} @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number() const noexcept { return is_number_integer() or is_number_float(); } /*! @brief return whether value is an integer number This function returns true if and only if the JSON value is a signed or unsigned integer number. This excludes floating-point values. @return `true` if type is an integer or unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_integer()` for all JSON types.,is_number_integer} @sa @ref is_number() -- check if value is a number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 1.0.0 */ constexpr bool is_number_integer() const noexcept { return (m_type == value_t::number_integer or m_type == value_t::number_unsigned); } /*! @brief return whether value is an unsigned integer number This function returns true if and only if the JSON value is an unsigned integer number. This excludes floating-point and signed integer values. @return `true` if type is an unsigned integer number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_unsigned()` for all JSON types.,is_number_unsigned} @sa @ref is_number() -- check if value is a number @sa @ref is_number_integer() -- check if value is an integer or unsigned integer number @sa @ref is_number_float() -- check if value is a floating-point number @since version 2.0.0 */ constexpr bool is_number_unsigned() const noexcept { return (m_type == value_t::number_unsigned); } /*! @brief return whether value is a floating-point number This function returns true if and only if the JSON value is a floating-point number. This excludes signed and unsigned integer values. @return `true` if type is a floating-point number, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_number_float()` for all JSON types.,is_number_float} @sa @ref is_number() -- check if value is number @sa @ref is_number_integer() -- check if value is an integer number @sa @ref is_number_unsigned() -- check if value is an unsigned integer number @since version 1.0.0 */ constexpr bool is_number_float() const noexcept { return (m_type == value_t::number_float); } /*! @brief return whether value is an object This function returns true if and only if the JSON value is an object. @return `true` if type is object, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_object()` for all JSON types.,is_object} @since version 1.0.0 */ constexpr bool is_object() const noexcept { return (m_type == value_t::object); } /*! @brief return whether value is an array This function returns true if and only if the JSON value is an array. @return `true` if type is array, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_array()` for all JSON types.,is_array} @since version 1.0.0 */ constexpr bool is_array() const noexcept { return (m_type == value_t::array); } /*! @brief return whether value is a string This function returns true if and only if the JSON value is a string. @return `true` if type is string, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_string()` for all JSON types.,is_string} @since version 1.0.0 */ constexpr bool is_string() const noexcept { return (m_type == value_t::string); } /*! @brief return whether value is discarded This function returns true if and only if the JSON value was discarded during parsing with a callback function (see @ref parser_callback_t). @note This function will always be `false` for JSON values after parsing. That is, discarded values can only occur during parsing, but will be removed when inside a structured value or replaced by null in other cases. @return `true` if type is discarded, `false` otherwise. @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies `is_discarded()` for all JSON types.,is_discarded} @since version 1.0.0 */ constexpr bool is_discarded() const noexcept { return (m_type == value_t::discarded); } /*! @brief return the type of the JSON value (implicit) Implicitly return the type of the JSON value as a value from the @ref value_t enumeration. @return the type of the JSON value @complexity Constant. @exceptionsafety No-throw guarantee: this member function never throws exceptions. @liveexample{The following code exemplifies the @ref value_t operator for all JSON types.,operator__value_t} @sa @ref type() -- return the type of the JSON value (explicit) @sa @ref type_name() -- return the type as string @since version 1.0.0 */ constexpr operator value_t() const noexcept { return m_type; } /// @} private: ////////////////// // value access // ////////////////// /// get a boolean (explicit) boolean_t get_impl(boolean_t* /*unused*/) const { if (JSON_LIKELY(is_boolean())) { return m_value.boolean; } JSON_THROW(type_error::create(302, "type must be boolean, but is " + std::string(type_name()))); } /// get a pointer to the value (object) object_t* get_impl_ptr(object_t* /*unused*/) noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (object) constexpr const object_t* get_impl_ptr(const object_t* /*unused*/) const noexcept { return is_object() ? m_value.object : nullptr; } /// get a pointer to the value (array) array_t* get_impl_ptr(array_t* /*unused*/) noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (array) constexpr const array_t* get_impl_ptr(const array_t* /*unused*/) const noexcept { return is_array() ? m_value.array : nullptr; } /// get a pointer to the value (string) string_t* get_impl_ptr(string_t* /*unused*/) noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (string) constexpr const string_t* get_impl_ptr(const string_t* /*unused*/) const noexcept { return is_string() ? m_value.string : nullptr; } /// get a pointer to the value (boolean) boolean_t* get_impl_ptr(boolean_t* /*unused*/) noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (boolean) constexpr const boolean_t* get_impl_ptr(const boolean_t* /*unused*/) const noexcept { return is_boolean() ? &m_value.boolean : nullptr; } /// get a pointer to the value (integer number) number_integer_t* get_impl_ptr(number_integer_t* /*unused*/) noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (integer number) constexpr const number_integer_t* get_impl_ptr(const number_integer_t* /*unused*/) const noexcept { return is_number_integer() ? &m_value.number_integer : nullptr; } /// get a pointer to the value (unsigned number) number_unsigned_t* get_impl_ptr(number_unsigned_t* /*unused*/) noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (unsigned number) constexpr const number_unsigned_t* get_impl_ptr(const number_unsigned_t* /*unused*/) const noexcept { return is_number_unsigned() ? &m_value.number_unsigned : nullptr; } /// get a pointer to the value (floating-point number) number_float_t* get_impl_ptr(number_float_t* /*unused*/) noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /// get a pointer to the value (floating-point number) constexpr const number_float_t* get_impl_ptr(const number_float_t* /*unused*/) const noexcept { return is_number_float() ? &m_value.number_float : nullptr; } /*! @brief helper function to implement get_ref() This function helps to implement get_ref() without code duplication for const and non-const overloads @tparam ThisType will be deduced as `basic_json` or `const basic_json` @throw type_error.303 if ReferenceType does not match underlying value type of the current JSON */ template<typename ReferenceType, typename ThisType> static ReferenceType get_ref_impl(ThisType& obj) { // delegate the call to get_ptr<>() auto ptr = obj.template get_ptr<typename std::add_pointer<ReferenceType>::type>(); if (JSON_LIKELY(ptr != nullptr)) { return *ptr; } JSON_THROW(type_error::create(303, "incompatible ReferenceType for get_ref, actual type is " + std::string(obj.type_name()))); } public: /// @name value access /// Direct access to the stored value of a JSON value. /// @{ /*! @brief get special-case overload This overloads avoids a lot of template boilerplate, it can be seen as the identity method @tparam BasicJsonType == @ref basic_json @return a copy of *this @complexity Constant. @since version 2.1.0 */ template<typename BasicJsonType, detail::enable_if_t< std::is_same<typename std::remove_const<BasicJsonType>::type, basic_json_t>::value, int> = 0> basic_json get() const { return *this; } /*! @brief get special-case overload This overloads converts the current @ref basic_json in a different @ref basic_json type @tparam BasicJsonType == @ref basic_json @return a copy of *this, converted into @tparam BasicJsonType @complexity Depending on the implementation of the called `from_json()` method. @since version 3.2.0 */ template<typename BasicJsonType, detail::enable_if_t< not std::is_same<BasicJsonType, basic_json>::value and detail::is_basic_json<BasicJsonType>::value, int> = 0> BasicJsonType get() const { return *this; } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value which is [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer<ValueType> has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and - @ref json_serializer<ValueType> does not have a `from_json()` method of the form `ValueType from_json(const basic_json&)` @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,get__ValueType_const} @since version 2.1.0 */ template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t < not detail::is_basic_json<ValueType>::value and detail::has_from_json<basic_json_t, ValueType>::value and not detail::has_non_default_from_json<basic_json_t, ValueType>::value, int> = 0> ValueType get() const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), std::declval<ValueType&>()))) { // we cannot static_assert on ValueTypeCV being non-const, because // there is support for get<const basic_json_t>(), which is why we // still need the uncvref static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); static_assert(std::is_default_constructible<ValueType>::value, "types must be DefaultConstructible when used with get()"); ValueType ret; JSONSerializer<ValueType>::from_json(*this, ret); return ret; } /*! @brief get a value (explicit); special case Explicit type conversion between the JSON value and a compatible value which is **not** [CopyConstructible](https://en.cppreference.com/w/cpp/named_req/CopyConstructible) and **not** [DefaultConstructible](https://en.cppreference.com/w/cpp/named_req/DefaultConstructible). The value is converted by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} return JSONSerializer<ValueTypeCV>::from_json(*this); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json and - @ref json_serializer<ValueType> has a `from_json()` method of the form `ValueType from_json(const basic_json&)` @note If @ref json_serializer<ValueType> has both overloads of `from_json()`, this one is chosen. @tparam ValueTypeCV the provided value type @tparam ValueType the returned value type @return copy of the JSON value, converted to @a ValueType @throw what @ref json_serializer<ValueType> `from_json()` method throws @since version 2.1.0 */ template<typename ValueTypeCV, typename ValueType = detail::uncvref_t<ValueTypeCV>, detail::enable_if_t<not std::is_same<basic_json_t, ValueType>::value and detail::has_non_default_from_json<basic_json_t, ValueType>::value, int> = 0> ValueType get() const noexcept(noexcept( JSONSerializer<ValueTypeCV>::from_json(std::declval<const basic_json_t&>()))) { static_assert(not std::is_reference<ValueTypeCV>::value, "get() cannot be used with reference types, you might want to use get_ref()"); return JSONSerializer<ValueTypeCV>::from_json(*this); } /*! @brief get a value (explicit) Explicit type conversion between the JSON value and a compatible value. The value is filled into the input parameter by calling the @ref json_serializer<ValueType> `from_json()` method. The function is equivalent to executing @code {.cpp} ValueType v; JSONSerializer<ValueType>::from_json(*this, v); @endcode This overloads is chosen if: - @a ValueType is not @ref basic_json, - @ref json_serializer<ValueType> has a `from_json()` method of the form `void from_json(const basic_json&, ValueType&)`, and @tparam ValueType the input parameter type. @return the input parameter, allowing chaining calls. @throw what @ref json_serializer<ValueType> `from_json()` method throws @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,get_to} @since version 3.3.0 */ template<typename ValueType, detail::enable_if_t < not detail::is_basic_json<ValueType>::value and detail::has_from_json<basic_json_t, ValueType>::value, int> = 0> ValueType & get_to(ValueType& v) const noexcept(noexcept( JSONSerializer<ValueType>::from_json(std::declval<const basic_json_t&>(), v))) { JSONSerializer<ValueType>::from_json(*this, v); return v; } /*! @brief get a pointer value (implicit) Implicit pointer access to the internally stored JSON value. No copies are made. @warning Writing data to the pointee of the result yields an undefined state. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. Enforced by a static assertion. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get_ptr} @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> auto get_ptr() noexcept -> decltype(std::declval<basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) { // delegate the call to get_impl_ptr<>() return get_impl_ptr(static_cast<PointerType>(nullptr)); } /*! @brief get a pointer value (implicit) @copydoc get_ptr() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value and std::is_const<typename std::remove_pointer<PointerType>::type>::value, int>::type = 0> constexpr auto get_ptr() const noexcept -> decltype(std::declval<const basic_json_t&>().get_impl_ptr(std::declval<PointerType>())) { // delegate the call to get_impl_ptr<>() const return get_impl_ptr(static_cast<PointerType>(nullptr)); } /*! @brief get a pointer value (explicit) Explicit pointer access to the internally stored JSON value. No copies are made. @warning The pointer becomes invalid if the underlying JSON object changes. @tparam PointerType pointer type; must be a pointer to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, @ref number_unsigned_t, or @ref number_float_t. @return pointer to the internally stored JSON value if the requested pointer type @a PointerType fits to the JSON value; `nullptr` otherwise @complexity Constant. @liveexample{The example below shows how pointers to internal values of a JSON value can be requested. Note that no type conversions are made and a `nullptr` is returned if the value and the requested pointer type does not match.,get__PointerType} @sa @ref get_ptr() for explicit pointer-member access @since version 1.0.0 */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> auto get() noexcept -> decltype(std::declval<basic_json_t&>().template get_ptr<PointerType>()) { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a pointer value (explicit) @copydoc get() */ template<typename PointerType, typename std::enable_if< std::is_pointer<PointerType>::value, int>::type = 0> constexpr auto get() const noexcept -> decltype(std::declval<const basic_json_t&>().template get_ptr<PointerType>()) { // delegate the call to get_ptr return get_ptr<PointerType>(); } /*! @brief get a reference value (implicit) Implicit reference access to the internally stored JSON value. No copies are made. @warning Writing data to the referee of the result yields an undefined state. @tparam ReferenceType reference type; must be a reference to @ref array_t, @ref object_t, @ref string_t, @ref boolean_t, @ref number_integer_t, or @ref number_float_t. Enforced by static assertion. @return reference to the internally stored JSON value if the requested reference type @a ReferenceType fits to the JSON value; throws type_error.303 otherwise @throw type_error.303 in case passed type @a ReferenceType is incompatible with the stored JSON value; see example below @complexity Constant. @liveexample{The example shows several calls to `get_ref()`.,get_ref} @since version 1.1.0 */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value, int>::type = 0> ReferenceType get_ref() { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a reference value (implicit) @copydoc get_ref() */ template<typename ReferenceType, typename std::enable_if< std::is_reference<ReferenceType>::value and std::is_const<typename std::remove_reference<ReferenceType>::type>::value, int>::type = 0> ReferenceType get_ref() const { // delegate call to get_ref_impl return get_ref_impl<ReferenceType>(*this); } /*! @brief get a value (implicit) Implicit type conversion between the JSON value and a compatible value. The call is realized by calling @ref get() const. @tparam ValueType non-pointer type compatible to the JSON value, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. The character type of @ref string_t as well as an initializer list of this type is excluded to avoid ambiguities as these types implicitly convert to `std::string`. @return copy of the JSON value, converted to type @a ValueType @throw type_error.302 in case passed type @a ValueType is incompatible to the JSON value type (e.g., the JSON value is of type boolean, but a string is requested); see example below @complexity Linear in the size of the JSON value. @liveexample{The example below shows several conversions from JSON values to other types. There a few things to note: (1) Floating-point numbers can be converted to integers\, (2) A JSON array can be converted to a standard `std::vector<short>`\, (3) A JSON object can be converted to C++ associative containers such as `std::unordered_map<std::string\, json>`.,operator__ValueType} @since version 1.0.0 */ template < typename ValueType, typename std::enable_if < not std::is_pointer<ValueType>::value and not std::is_same<ValueType, detail::json_ref<basic_json>>::value and not std::is_same<ValueType, typename string_t::value_type>::value and not detail::is_basic_json<ValueType>::value #ifndef _MSC_VER // fix for issue #167 operator<< ambiguity under VS2015 and not std::is_same<ValueType, std::initializer_list<typename string_t::value_type>>::value #if defined(JSON_HAS_CPP_17) && defined(_MSC_VER) and _MSC_VER <= 1914 and not std::is_same<ValueType, typename std::string_view>::value #endif #endif and detail::is_detected<detail::get_template_function, const basic_json_t&, ValueType>::value , int >::type = 0 > operator ValueType() const { // delegate the call to get<>() const return get<ValueType>(); } /// @} //////////////////// // element access // //////////////////// /// @name element access /// Access to the JSON value. /// @{ /*! @brief access specified array element with bounds checking Returns a reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__size_type} */ reference at(size_type idx) { // at only works for arrays if (JSON_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element with bounds checking Returns a const reference to the element at specified location @a idx, with bounds checking. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.304 if the JSON value is not an array; in this case, calling `at` with an index makes no sense. See example below. @throw out_of_range.401 if the index @a idx is out of range of the array; that is, `idx >= size()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 1.0.0 @liveexample{The example below shows how array elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__size_type_const} */ const_reference at(size_type idx) const { // at only works for arrays if (JSON_LIKELY(is_array())) { JSON_TRY { return m_value.array->at(idx); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read and written using `at()`. It also demonstrates the different exceptions that can be thrown.,at__object_t_key_type} */ reference at(const typename object_t::key_type& key) { // at only works for objects if (JSON_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified object element with bounds checking Returns a const reference to the element at with specified key @a key, with bounds checking. @param[in] key key of the element to access @return const reference to the element at key @a key @throw type_error.304 if the JSON value is not an object; in this case, calling `at` with a key makes no sense. See example below. @throw out_of_range.403 if the key @a key is is not stored in the object; that is, `find(key) == end()`. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Logarithmic in the size of the container. @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @sa @ref value() for access by value with a default value @since version 1.0.0 @liveexample{The example below shows how object elements can be read using `at()`. It also demonstrates the different exceptions that can be thrown., at__object_t_key_type_const} */ const_reference at(const typename object_t::key_type& key) const { // at only works for objects if (JSON_LIKELY(is_object())) { JSON_TRY { return m_value.object->at(key); } JSON_CATCH (std::out_of_range&) { // create better exception explanation JSON_THROW(out_of_range::create(403, "key '" + key + "' not found")); } } else { JSON_THROW(type_error::create(304, "cannot use at() with " + std::string(type_name()))); } } /*! @brief access specified array element Returns a reference to the element at specified location @a idx. @note If @a idx is beyond the range of the array (i.e., `idx >= size()`), then the array is silently filled up with `null` values to make `idx` a valid reference to the last stored element. @param[in] idx index of the element to access @return reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array or null; in that cases, using the [] operator with an index makes no sense. @complexity Constant if @a idx is in the range of the array. Otherwise linear in `idx - size()`. @liveexample{The example below shows how array elements can be read and written using `[]` operator. Note the addition of `null` values.,operatorarray__size_type} @since version 1.0.0 */ reference operator[](size_type idx) { // implicitly convert null value to an empty array if (is_null()) { m_type = value_t::array; m_value.array = create<array_t>(); assert_invariant(); } // operator[] only works for arrays if (JSON_LIKELY(is_array())) { // fill up array with null values if given idx is outside range if (idx >= m_value.array->size()) { m_value.array->insert(m_value.array->end(), idx - m_value.array->size() + 1, basic_json()); } return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()))); } /*! @brief access specified array element Returns a const reference to the element at specified location @a idx. @param[in] idx index of the element to access @return const reference to the element at index @a idx @throw type_error.305 if the JSON value is not an array; in that case, using the [] operator with an index makes no sense. @complexity Constant. @liveexample{The example below shows how array elements can be read using the `[]` operator.,operatorarray__size_type_const} @since version 1.0.0 */ const_reference operator[](size_type idx) const { // const operator[] only works for arrays if (JSON_LIKELY(is_array())) { return m_value.array->operator[](idx); } JSON_THROW(type_error::create(305, "cannot use operator[] with a numeric argument with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ reference operator[](const typename object_t::key_type& key) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } // operator[] only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that case, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.0.0 */ const_reference operator[](const typename object_t::key_type& key) const { // const operator[] only works for objects if (JSON_LIKELY(is_object())) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief access specified object element Returns a reference to the element at with specified key @a key. @note If @a key is not found in the object, then it is silently added to the object and filled with a `null` value to make `key` a valid reference. In case the value was `null` before, it is converted to an object. @param[in] key key of the element to access @return reference to the element at key @a key @throw type_error.305 if the JSON value is not an object or null; in that cases, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read and written using the `[]` operator.,operatorarray__key_type} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> reference operator[](T* key) { // implicitly convert null to object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // at only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->operator[](key); } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief read-only access specified object element Returns a const reference to the element at with specified key @a key. No bounds checking is performed. @warning If the element with key @a key does not exist, the behavior is undefined. @param[in] key key of the element to access @return const reference to the element at key @a key @pre The element with key @a key must exist. **This precondition is enforced with an assertion.** @throw type_error.305 if the JSON value is not an object; in that case, using the [] operator with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be read using the `[]` operator.,operatorarray__key_type_const} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref value() for access by value with a default value @since version 1.1.0 */ template<typename T> const_reference operator[](T* key) const { // at only works for objects if (JSON_LIKELY(is_object())) { assert(m_value.object->find(key) != m_value.object->end()); return m_value.object->find(key)->second; } JSON_THROW(type_error::create(305, "cannot use operator[] with a string argument with " + std::string(type_name()))); } /*! @brief access specified object element with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(key); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const typename object_t::key_type&), this function does not throw if the given key @a key was not found. @note Unlike @ref operator[](const typename object_t::key_type& key), this function does not implicitly add an element to the position defined by @a key. This function is furthermore also applicable to const objects. @param[in] key key of the element to access @param[in] default_value the value to return if @a key is not found @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.306 if the JSON value is not an object; in that case, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value} @sa @ref at(const typename object_t::key_type&) for access by reference with range checking @sa @ref operator[](const typename object_t::key_type&) for unchecked access by reference @since version 1.0.0 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const typename object_t::key_type& key, const ValueType& default_value) const { // at only works for objects if (JSON_LIKELY(is_object())) { // if key is found, return value and given default value otherwise const auto it = find(key); if (it != end()) { return *it; } return default_value; } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const typename object_t::key_type&, const ValueType&) const */ string_t value(const typename object_t::key_type& key, const char* default_value) const { return value(key, string_t(default_value)); } /*! @brief access specified object element via JSON Pointer with default value Returns either a copy of an object's element at the specified key @a key or a given default value if no element with key @a key exists. The function is basically equivalent to executing @code {.cpp} try { return at(ptr); } catch(out_of_range) { return default_value; } @endcode @note Unlike @ref at(const json_pointer&), this function does not throw if the given key @a key was not found. @param[in] ptr a JSON pointer to the element to access @param[in] default_value the value to return if @a ptr found no value @tparam ValueType type compatible to JSON values, for instance `int` for JSON integer numbers, `bool` for JSON booleans, or `std::vector` types for JSON arrays. Note the type of the expected value at @a key and the default value @a default_value must be compatible. @return copy of the element at key @a key or @a default_value if @a key is not found @throw type_error.306 if the JSON value is not an object; in that case, using `value()` with a key makes no sense. @complexity Logarithmic in the size of the container. @liveexample{The example below shows how object elements can be queried with a default value.,basic_json__value_ptr} @sa @ref operator[](const json_pointer&) for unchecked access by reference @since version 2.0.2 */ template<class ValueType, typename std::enable_if< std::is_convertible<basic_json_t, ValueType>::value, int>::type = 0> ValueType value(const json_pointer& ptr, const ValueType& default_value) const { // at only works for objects if (JSON_LIKELY(is_object())) { // if pointer resolves a value, return it or use default value JSON_TRY { return ptr.get_checked(this); } JSON_INTERNAL_CATCH (out_of_range&) { return default_value; } } JSON_THROW(type_error::create(306, "cannot use value() with " + std::string(type_name()))); } /*! @brief overload for a default value of type const char* @copydoc basic_json::value(const json_pointer&, ValueType) const */ string_t value(const json_pointer& ptr, const char* default_value) const { return value(ptr, string_t(default_value)); } /*! @brief access the first element Returns a reference to the first element in the container. For a JSON container `c`, the expression `c.front()` is equivalent to `*c.begin()`. @return In case of a structured type (array or object), a reference to the first element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on `null` value @liveexample{The following code shows an example for `front()`.,front} @sa @ref back() -- access the last element @since version 1.0.0 */ reference front() { return *begin(); } /*! @copydoc basic_json::front() */ const_reference front() const { return *cbegin(); } /*! @brief access the last element Returns a reference to the last element in the container. For a JSON container `c`, the expression `c.back()` is equivalent to @code {.cpp} auto tmp = c.end(); --tmp; return *tmp; @endcode @return In case of a structured type (array or object), a reference to the last element is returned. In case of number, string, or boolean values, a reference to the value is returned. @complexity Constant. @pre The JSON value must not be `null` (would throw `std::out_of_range`) or an empty array or object (undefined behavior, **guarded by assertions**). @post The JSON value remains unchanged. @throw invalid_iterator.214 when called on a `null` value. See example below. @liveexample{The following code shows an example for `back()`.,back} @sa @ref front() -- access the first element @since version 1.0.0 */ reference back() { auto tmp = end(); --tmp; return *tmp; } /*! @copydoc basic_json::back() */ const_reference back() const { auto tmp = cend(); --tmp; return *tmp; } /*! @brief remove element given an iterator Removes the element specified by iterator @a pos. The iterator @a pos must be valid and dereferenceable. Thus the `end()` iterator (which is valid, but is not dereferenceable) cannot be used as a value for @a pos. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] pos iterator to the element to remove @return Iterator following the last removed element. If the iterator @a pos refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.202 if called on an iterator which does not belong to the current JSON value; example: `"iterator does not fit current value"` @throw invalid_iterator.205 if called on a primitive type with invalid iterator (i.e., any iterator which is not `begin()`); example: `"iterator out of range"` @complexity The complexity depends on the type: - objects: amortized constant - arrays: linear in distance between @a pos and the end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType} @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType pos) { // make sure iterator fits the current value if (JSON_UNLIKELY(this != pos.m_object)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_UNLIKELY(not pos.m_it.primitive_iterator.is_begin())) { JSON_THROW(invalid_iterator::create(205, "iterator out of range")); } if (is_string()) { AllocatorType<string_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string); std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(pos.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(pos.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove elements given an iterator range Removes the element specified by the range `[first; last)`. The iterator @a first does not need to be dereferenceable if `first == last`: erasing an empty range is a no-op. If called on a primitive type other than `null`, the resulting JSON value will be `null`. @param[in] first iterator to the beginning of the range to remove @param[in] last iterator past the end of the range to remove @return Iterator following the last removed element. If the iterator @a second refers to the last element, the `end()` iterator is returned. @tparam IteratorType an @ref iterator or @ref const_iterator @post Invalidates iterators and references at or after the point of the erase, including the `end()` iterator. @throw type_error.307 if called on a `null` value; example: `"cannot use erase() with null"` @throw invalid_iterator.203 if called on iterators which does not belong to the current JSON value; example: `"iterators do not fit current value"` @throw invalid_iterator.204 if called on a primitive type with invalid iterators (i.e., if `first != begin()` and `last != end()`); example: `"iterators out of range"` @complexity The complexity depends on the type: - objects: `log(size()) + std::distance(first, last)` - arrays: linear in the distance between @a first and @a last, plus linear in the distance between @a last and end of the container - strings: linear in the length of the string - other types: constant @liveexample{The example shows the result of `erase()` for different JSON types.,erase__IteratorType_IteratorType} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ template<class IteratorType, typename std::enable_if< std::is_same<IteratorType, typename basic_json_t::iterator>::value or std::is_same<IteratorType, typename basic_json_t::const_iterator>::value, int>::type = 0> IteratorType erase(IteratorType first, IteratorType last) { // make sure iterator fits the current value if (JSON_UNLIKELY(this != first.m_object or this != last.m_object)) { JSON_THROW(invalid_iterator::create(203, "iterators do not fit current value")); } IteratorType result = end(); switch (m_type) { case value_t::boolean: case value_t::number_float: case value_t::number_integer: case value_t::number_unsigned: case value_t::string: { if (JSON_LIKELY(not first.m_it.primitive_iterator.is_begin() or not last.m_it.primitive_iterator.is_end())) { JSON_THROW(invalid_iterator::create(204, "iterators out of range")); } if (is_string()) { AllocatorType<string_t> alloc; std::allocator_traits<decltype(alloc)>::destroy(alloc, m_value.string); std::allocator_traits<decltype(alloc)>::deallocate(alloc, m_value.string, 1); m_value.string = nullptr; } m_type = value_t::null; assert_invariant(); break; } case value_t::object: { result.m_it.object_iterator = m_value.object->erase(first.m_it.object_iterator, last.m_it.object_iterator); break; } case value_t::array: { result.m_it.array_iterator = m_value.array->erase(first.m_it.array_iterator, last.m_it.array_iterator); break; } default: JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } return result; } /*! @brief remove element from a JSON object given a key Removes elements from a JSON object with the key value @a key. @param[in] key value of the elements to remove @return Number of elements removed. If @a ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @post References and iterators to the erased elements are invalidated. Other references and iterators are not affected. @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @complexity `log(size()) + count(key)` @liveexample{The example shows the effect of `erase()`.,erase__key_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const size_type) -- removes the element from an array at the given index @since version 1.0.0 */ size_type erase(const typename object_t::key_type& key) { // this erase only works for objects if (JSON_LIKELY(is_object())) { return m_value.object->erase(key); } JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } /*! @brief remove element from a JSON array given an index Removes element from a JSON array at the index @a idx. @param[in] idx index of the element to remove @throw type_error.307 when called on a type other than JSON object; example: `"cannot use erase() with null"` @throw out_of_range.401 when `idx >= size()`; example: `"array index 17 is out of range"` @complexity Linear in distance between @a idx and the end of the container. @liveexample{The example shows the effect of `erase()`.,erase__size_type} @sa @ref erase(IteratorType) -- removes the element at a given position @sa @ref erase(IteratorType, IteratorType) -- removes the elements in the given range @sa @ref erase(const typename object_t::key_type&) -- removes the element from an object at the given key @since version 1.0.0 */ void erase(const size_type idx) { // this erase only works for arrays if (JSON_LIKELY(is_array())) { if (JSON_UNLIKELY(idx >= size())) { JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } m_value.array->erase(m_value.array->begin() + static_cast<difference_type>(idx)); } else { JSON_THROW(type_error::create(307, "cannot use erase() with " + std::string(type_name()))); } } /// @} //////////// // lookup // //////////// /// @name lookup /// @{ /*! @brief find an element in a JSON object Finds an element in a JSON object with key equivalent to @a key. If the element is not found or the JSON value is not an object, end() is returned. @note This method always returns @ref end() when executed on a JSON type that is not an object. @param[in] key key value of the element to search for. @return Iterator to an element with key equivalent to @a key. If no such element is found or the JSON value is not an object, past-the-end (see @ref end()) iterator is returned. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `find()` is used.,find__key_type} @since version 1.0.0 */ template<typename KeyT> iterator find(KeyT&& key) { auto result = end(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key)); } return result; } /*! @brief find an element in a JSON object @copydoc find(KeyT&&) */ template<typename KeyT> const_iterator find(KeyT&& key) const { auto result = cend(); if (is_object()) { result.m_it.object_iterator = m_value.object->find(std::forward<KeyT>(key)); } return result; } /*! @brief returns the number of occurrences of a key in a JSON object Returns the number of elements with key @a key. If ObjectType is the default `std::map` type, the return value will always be `0` (@a key was not found) or `1` (@a key was found). @note This method always returns `0` when executed on a JSON type that is not an object. @param[in] key key value of the element to count @return Number of elements with key @a key. If the JSON value is not an object, the return value will be `0`. @complexity Logarithmic in the size of the JSON object. @liveexample{The example shows how `count()` is used.,count} @since version 1.0.0 */ template<typename KeyT> size_type count(KeyT&& key) const { // return 0 for all nonobject types return is_object() ? m_value.object->count(std::forward<KeyT>(key)) : 0; } /// @} /////////////// // iterators // /////////////// /// @name iterators /// @{ /*! @brief returns an iterator to the first element Returns an iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `begin()`.,begin} @sa @ref cbegin() -- returns a const iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ iterator begin() noexcept { iterator result(this); result.set_begin(); return result; } /*! @copydoc basic_json::cbegin() */ const_iterator begin() const noexcept { return cbegin(); } /*! @brief returns a const iterator to the first element Returns a const iterator to the first element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator to the first element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).begin()`. @liveexample{The following code shows an example for `cbegin()`.,cbegin} @sa @ref begin() -- returns an iterator to the beginning @sa @ref end() -- returns an iterator to the end @sa @ref cend() -- returns a const iterator to the end @since version 1.0.0 */ const_iterator cbegin() const noexcept { const_iterator result(this); result.set_begin(); return result; } /*! @brief returns an iterator to one past the last element Returns an iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. @liveexample{The following code shows an example for `end()`.,end} @sa @ref cend() -- returns a const iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ iterator end() noexcept { iterator result(this); result.set_end(); return result; } /*! @copydoc basic_json::cend() */ const_iterator end() const noexcept { return cend(); } /*! @brief returns a const iterator to one past the last element Returns a const iterator to one past the last element. @image html range-begin-end.svg "Illustration from cppreference.com" @return const iterator one past the last element @complexity Constant. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).end()`. @liveexample{The following code shows an example for `cend()`.,cend} @sa @ref end() -- returns an iterator to the end @sa @ref begin() -- returns an iterator to the beginning @sa @ref cbegin() -- returns a const iterator to the beginning @since version 1.0.0 */ const_iterator cend() const noexcept { const_iterator result(this); result.set_end(); return result; } /*! @brief returns an iterator to the reverse-beginning Returns an iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(end())`. @liveexample{The following code shows an example for `rbegin()`.,rbegin} @sa @ref crbegin() -- returns a const reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ reverse_iterator rbegin() noexcept { return reverse_iterator(end()); } /*! @copydoc basic_json::crbegin() */ const_reverse_iterator rbegin() const noexcept { return crbegin(); } /*! @brief returns an iterator to the reverse-end Returns an iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `reverse_iterator(begin())`. @liveexample{The following code shows an example for `rend()`.,rend} @sa @ref crend() -- returns a const reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ reverse_iterator rend() noexcept { return reverse_iterator(begin()); } /*! @copydoc basic_json::crend() */ const_reverse_iterator rend() const noexcept { return crend(); } /*! @brief returns a const reverse iterator to the last element Returns a const iterator to the reverse-beginning; that is, the last element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rbegin()`. @liveexample{The following code shows an example for `crbegin()`.,crbegin} @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref rend() -- returns a reverse iterator to the end @sa @ref crend() -- returns a const reverse iterator to the end @since version 1.0.0 */ const_reverse_iterator crbegin() const noexcept { return const_reverse_iterator(cend()); } /*! @brief returns a const reverse iterator to one before the first Returns a const reverse iterator to the reverse-end; that is, one before the first element. @image html range-rbegin-rend.svg "Illustration from cppreference.com" @complexity Constant. @requirement This function helps `basic_json` satisfying the [ReversibleContainer](https://en.cppreference.com/w/cpp/named_req/ReversibleContainer) requirements: - The complexity is constant. - Has the semantics of `const_cast<const basic_json&>(*this).rend()`. @liveexample{The following code shows an example for `crend()`.,crend} @sa @ref rend() -- returns a reverse iterator to the end @sa @ref rbegin() -- returns a reverse iterator to the beginning @sa @ref crbegin() -- returns a const reverse iterator to the beginning @since version 1.0.0 */ const_reverse_iterator crend() const noexcept { return const_reverse_iterator(cbegin()); } public: /*! @brief wrapper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. For loop without iterator_wrapper: @code{cpp} for (auto it = j_object.begin(); it != j_object.end(); ++it) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode Range-based for loop without iterator proxy: @code{cpp} for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } @endcode Range-based for loop with iterator proxy: @code{cpp} for (auto it : json::iterator_wrapper(j_object)) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode @note When iterating over an array, `key()` will return the index of the element as string (see example). @param[in] ref reference to a JSON value @return iteration proxy object wrapping @a ref with an interface to use in range-based for loops @liveexample{The following code shows how the wrapper is used,iterator_wrapper} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @note The name of this function is not yet final and may change in the future. @deprecated This stream operator is deprecated and will be removed in future 4.0.0 of the library. Please use @ref items() instead; that is, replace `json::iterator_wrapper(j)` with `j.items()`. */ JSON_DEPRECATED static iteration_proxy<iterator> iterator_wrapper(reference ref) noexcept { return ref.items(); } /*! @copydoc iterator_wrapper(reference) */ JSON_DEPRECATED static iteration_proxy<const_iterator> iterator_wrapper(const_reference ref) noexcept { return ref.items(); } /*! @brief helper to access iterator member functions in range-based for This function allows to access @ref iterator::key() and @ref iterator::value() during range-based for loops. In these loops, a reference to the JSON values is returned, so there is no access to the underlying iterator. For loop without `items()` function: @code{cpp} for (auto it = j_object.begin(); it != j_object.end(); ++it) { std::cout << "key: " << it.key() << ", value:" << it.value() << '\n'; } @endcode Range-based for loop without `items()` function: @code{cpp} for (auto it : j_object) { // "it" is of type json::reference and has no key() member std::cout << "value: " << it << '\n'; } @endcode Range-based for loop with `items()` function: @code{cpp} for (auto& el : j_object.items()) { std::cout << "key: " << el.key() << ", value:" << el.value() << '\n'; } @endcode The `items()` function also allows to use [structured bindings](https://en.cppreference.com/w/cpp/language/structured_binding) (C++17): @code{cpp} for (auto& [key, val] : j_object.items()) { std::cout << "key: " << key << ", value:" << val << '\n'; } @endcode @note When iterating over an array, `key()` will return the index of the element as string (see example). For primitive types (e.g., numbers), `key()` returns an empty string. @return iteration proxy object wrapping @a ref with an interface to use in range-based for loops @liveexample{The following code shows how the function is used.,items} @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 3.1.0, structured bindings support since 3.5.0. */ iteration_proxy<iterator> items() noexcept { return iteration_proxy<iterator>(*this); } /*! @copydoc items() */ iteration_proxy<const_iterator> items() const noexcept { return iteration_proxy<const_iterator>(*this); } /// @} ////////////// // capacity // ////////////// /// @name capacity /// @{ /*! @brief checks whether the container is empty. Checks if a JSON value has no elements (i.e. whether its @ref size is `0`). @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `true` boolean | `false` string | `false` number | `false` object | result of function `object_t::empty()` array | result of function `array_t::empty()` @liveexample{The following code uses `empty()` to check if a JSON object contains any elements.,empty} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `empty()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return whether a string stored as JSON value is empty - it returns whether the JSON container itself is empty which is false in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `begin() == end()`. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ bool empty() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return true; } case value_t::array: { // delegate call to array_t::empty() return m_value.array->empty(); } case value_t::object: { // delegate call to object_t::empty() return m_value.object->empty(); } default: { // all other types are nonempty return false; } } } /*! @brief returns the number of elements Returns the number of elements in a JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` boolean | `1` string | `1` number | `1` object | result of function object_t::size() array | result of function array_t::size() @liveexample{The following code calls `size()` on the different value types.,size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their size() functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @note This function does not return the length of a string stored as JSON value - it returns the number of elements in the JSON value which is 1 in the case of a string. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of `std::distance(begin(), end())`. @sa @ref empty() -- checks whether the container is empty @sa @ref max_size() -- returns the maximal number of elements @since version 1.0.0 */ size_type size() const noexcept { switch (m_type) { case value_t::null: { // null values are empty return 0; } case value_t::array: { // delegate call to array_t::size() return m_value.array->size(); } case value_t::object: { // delegate call to object_t::size() return m_value.object->size(); } default: { // all other types have size 1 return 1; } } } /*! @brief returns the maximum possible number of elements Returns the maximum number of elements a JSON value is able to hold due to system or library implementation limitations, i.e. `std::distance(begin(), end())` for the JSON value. @return The return value depends on the different types and is defined as follows: Value type | return value ----------- | ------------- null | `0` (same as `size()`) boolean | `1` (same as `size()`) string | `1` (same as `size()`) number | `1` (same as `size()`) object | result of function `object_t::max_size()` array | result of function `array_t::max_size()` @liveexample{The following code calls `max_size()` on the different value types. Note the output is implementation specific.,max_size} @complexity Constant, as long as @ref array_t and @ref object_t satisfy the Container concept; that is, their `max_size()` functions have constant complexity. @iterators No changes. @exceptionsafety No-throw guarantee: this function never throws exceptions. @requirement This function helps `basic_json` satisfying the [Container](https://en.cppreference.com/w/cpp/named_req/Container) requirements: - The complexity is constant. - Has the semantics of returning `b.size()` where `b` is the largest possible JSON value. @sa @ref size() -- returns the number of elements @since version 1.0.0 */ size_type max_size() const noexcept { switch (m_type) { case value_t::array: { // delegate call to array_t::max_size() return m_value.array->max_size(); } case value_t::object: { // delegate call to object_t::max_size() return m_value.object->max_size(); } default: { // all other types have max_size() == size() return size(); } } } /// @} /////////////// // modifiers // /////////////// /// @name modifiers /// @{ /*! @brief clears the contents Clears the content of a JSON value and resets it to the default value as if @ref basic_json(value_t) would have been called with the current value type from @ref type(): Value type | initial value ----------- | ------------- null | `null` boolean | `false` string | `""` number | `0` object | `{}` array | `[]` @post Has the same effect as calling @code {.cpp} *this = basic_json(type()); @endcode @liveexample{The example below shows the effect of `clear()` to different JSON types.,clear} @complexity Linear in the size of the JSON value. @iterators All iterators, pointers and references related to this container are invalidated. @exceptionsafety No-throw guarantee: this function never throws exceptions. @sa @ref basic_json(value_t) -- constructor that creates an object with the same value than calling `clear()` @since version 1.0.0 */ void clear() noexcept { switch (m_type) { case value_t::number_integer: { m_value.number_integer = 0; break; } case value_t::number_unsigned: { m_value.number_unsigned = 0; break; } case value_t::number_float: { m_value.number_float = 0.0; break; } case value_t::boolean: { m_value.boolean = false; break; } case value_t::string: { m_value.string->clear(); break; } case value_t::array: { m_value.array->clear(); break; } case value_t::object: { m_value.object->clear(); break; } default: break; } } /*! @brief add an object to an array Appends the given element @a val to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending @a val. @param[in] val the value to add to the JSON array @throw type_error.308 when called on a type other than JSON array or null; example: `"cannot use push_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,push_back} @since version 1.0.0 */ void push_back(basic_json&& val) { // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (move semantics) m_value.array->push_back(std::move(val)); // invalidate object val.m_type = value_t::null; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(basic_json&& val) { push_back(std::move(val)); return *this; } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ void push_back(const basic_json& val) { // push_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array m_value.array->push_back(val); } /*! @brief add an object to an array @copydoc push_back(basic_json&&) */ reference operator+=(const basic_json& val) { push_back(val); return *this; } /*! @brief add an object to an object Inserts the given element @a val to the JSON object. If the function is called on a JSON null value, an empty object is created before inserting @a val. @param[in] val the value to add to the JSON object @throw type_error.308 when called on a type other than JSON object or null; example: `"cannot use push_back() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `push_back()` and `+=` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object.,push_back__object_t__value} @since version 1.0.0 */ void push_back(const typename object_t::value_type& val) { // push_back only works for null objects or objects if (JSON_UNLIKELY(not(is_null() or is_object()))) { JSON_THROW(type_error::create(308, "cannot use push_back() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array m_value.object->insert(val); } /*! @brief add an object to an object @copydoc push_back(const typename object_t::value_type&) */ reference operator+=(const typename object_t::value_type& val) { push_back(val); return *this; } /*! @brief add an object to an object This function allows to use `push_back` with an initializer list. In case 1. the current value is an object, 2. the initializer list @a init contains only two elements, and 3. the first element of @a init is a string, @a init is converted into an object element and added using @ref push_back(const typename object_t::value_type&). Otherwise, @a init is converted to a JSON value and added using @ref push_back(basic_json&&). @param[in] init an initializer list @complexity Linear in the size of the initializer list @a init. @note This function is required to resolve an ambiguous overload error, because pairs like `{"key", "value"}` can be both interpreted as `object_t::value_type` or `std::initializer_list<basic_json>`, see https://github.com/nlohmann/json/issues/235 for more information. @liveexample{The example shows how initializer lists are treated as objects when possible.,push_back__initializer_list} */ void push_back(initializer_list_t init) { if (is_object() and init.size() == 2 and (*init.begin())->is_string()) { basic_json&& key = init.begin()->moved_or_copied(); push_back(typename object_t::value_type( std::move(key.get_ref<string_t&>()), (init.begin() + 1)->moved_or_copied())); } else { push_back(basic_json(init)); } } /*! @brief add an object to an object @copydoc push_back(initializer_list_t) */ reference operator+=(initializer_list_t init) { push_back(init); return *this; } /*! @brief add an object to an array Creates a JSON value from the passed parameters @a args to the end of the JSON value. If the function is called on a JSON null value, an empty array is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @throw type_error.311 when called on a type other than JSON array or null; example: `"cannot use emplace_back() with number"` @complexity Amortized constant. @liveexample{The example shows how `push_back()` can be used to add elements to a JSON array. Note how the `null` value was silently converted to a JSON array.,emplace_back} @since version 2.0.8 */ template<class... Args> void emplace_back(Args&& ... args) { // emplace_back only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_array()))) { JSON_THROW(type_error::create(311, "cannot use emplace_back() with " + std::string(type_name()))); } // transform null object into an array if (is_null()) { m_type = value_t::array; m_value = value_t::array; assert_invariant(); } // add element to array (perfect forwarding) m_value.array->emplace_back(std::forward<Args>(args)...); } /*! @brief add an object to an object if key does not exist Inserts a new element into a JSON object constructed in-place with the given @a args if there is no element with the key in the container. If the function is called on a JSON null value, an empty object is created before appending the value created from @a args. @param[in] args arguments to forward to a constructor of @ref basic_json @tparam Args compatible types to create a @ref basic_json object @return a pair consisting of an iterator to the inserted element, or the already-existing element if no insertion happened, and a bool denoting whether the insertion took place. @throw type_error.311 when called on a type other than JSON object or null; example: `"cannot use emplace() with number"` @complexity Logarithmic in the size of the container, O(log(`size()`)). @liveexample{The example shows how `emplace()` can be used to add elements to a JSON object. Note how the `null` value was silently converted to a JSON object. Further note how no value is added if there was already one value stored with the same key.,emplace} @since version 2.0.8 */ template<class... Args> std::pair<iterator, bool> emplace(Args&& ... args) { // emplace only works for null objects or arrays if (JSON_UNLIKELY(not(is_null() or is_object()))) { JSON_THROW(type_error::create(311, "cannot use emplace() with " + std::string(type_name()))); } // transform null object into an object if (is_null()) { m_type = value_t::object; m_value = value_t::object; assert_invariant(); } // add element to array (perfect forwarding) auto res = m_value.object->emplace(std::forward<Args>(args)...); // create result iterator and set iterator to the result of emplace auto it = begin(); it.m_it.object_iterator = res.first; // return pair of iterator and boolean return {it, res.second}; } /// Helper for insertion of an iterator /// @note: This uses std::distance to support GCC 4.8, /// see https://github.com/nlohmann/json/pull/1257 template<typename... Args> iterator insert_iterator(const_iterator pos, Args&& ... args) { iterator result(this); assert(m_value.array != nullptr); auto insert_pos = std::distance(m_value.array->begin(), pos.m_it.array_iterator); m_value.array->insert(pos.m_it.array_iterator, std::forward<Args>(args)...); result.m_it.array_iterator = m_value.array->begin() + insert_pos; // This could have been written as: // result.m_it.array_iterator = m_value.array->insert(pos.m_it.array_iterator, cnt, val); // but the return value of insert is missing in GCC 4.8, so it is written this way instead. return result; } /*! @brief inserts element Inserts element @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] val element to insert @return iterator pointing to the inserted @a val. @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Constant plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert} @since version 1.0.0 */ iterator insert(const_iterator pos, const basic_json& val) { // insert only works for arrays if (JSON_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator return insert_iterator(pos, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts element @copydoc insert(const_iterator, const basic_json&) */ iterator insert(const_iterator pos, basic_json&& val) { return insert(pos, val); } /*! @brief inserts elements Inserts @a cnt copies of @a val before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] cnt number of copies of @a val to insert @param[in] val element to insert @return iterator pointing to the first element inserted, or @a pos if `cnt==0` @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @complexity Linear in @a cnt plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__count} @since version 1.0.0 */ iterator insert(const_iterator pos, size_type cnt, const basic_json& val) { // insert only works for arrays if (JSON_LIKELY(is_array())) { // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator return insert_iterator(pos, cnt, val); } JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } /*! @brief inserts elements Inserts elements from range `[first, last)` before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @throw invalid_iterator.211 if @a first or @a last are iterators into container for which insert is called; example: `"passed iterators may not belong to container"` @return iterator pointing to the first element inserted, or @a pos if `first==last` @complexity Linear in `std::distance(first, last)` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__range} @since version 1.0.0 */ iterator insert(const_iterator pos, const_iterator first, const_iterator last) { // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } if (JSON_UNLIKELY(first.m_object == this)) { JSON_THROW(invalid_iterator::create(211, "passed iterators may not belong to container")); } // insert to array and return iterator return insert_iterator(pos, first.m_it.array_iterator, last.m_it.array_iterator); } /*! @brief inserts elements Inserts elements from initializer list @a ilist before iterator @a pos. @param[in] pos iterator before which the content will be inserted; may be the end() iterator @param[in] ilist initializer list to insert the values from @throw type_error.309 if called on JSON values other than arrays; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if @a pos is not an iterator of *this; example: `"iterator does not fit current value"` @return iterator pointing to the first element inserted, or @a pos if `ilist` is empty @complexity Linear in `ilist.size()` plus linear in the distance between @a pos and end of the container. @liveexample{The example shows how `insert()` is used.,insert__ilist} @since version 1.0.0 */ iterator insert(const_iterator pos, initializer_list_t ilist) { // insert only works for arrays if (JSON_UNLIKELY(not is_array())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if iterator pos fits to this JSON value if (JSON_UNLIKELY(pos.m_object != this)) { JSON_THROW(invalid_iterator::create(202, "iterator does not fit current value")); } // insert to array and return iterator return insert_iterator(pos, ilist.begin(), ilist.end()); } /*! @brief inserts elements Inserts elements from range `[first, last)`. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.309 if called on JSON values other than objects; example: `"cannot use insert() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity Logarithmic: `O(N*log(size() + N))`, where `N` is the number of elements to insert. @liveexample{The example shows how `insert()` is used.,insert__range_object} @since version 3.0.0 */ void insert(const_iterator first, const_iterator last) { // insert only works for objects if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(309, "cannot use insert() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_UNLIKELY(not first.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } m_value.object->insert(first.m_it.object_iterator, last.m_it.object_iterator); } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from JSON object @a j and overwrites existing keys. @param[in] j JSON object to read values from @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_reference j) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } if (JSON_UNLIKELY(not j.is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(j.type_name()))); } for (auto it = j.cbegin(); it != j.cend(); ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief updates a JSON object from another object, overwriting existing keys Inserts all values from from range `[first, last)` and overwrites existing keys. @param[in] first begin of the range of elements to insert @param[in] last end of the range of elements to insert @throw type_error.312 if called on JSON values other than objects; example: `"cannot use update() with string"` @throw invalid_iterator.202 if iterator @a first or @a last does does not point to an object; example: `"iterators first and last must point to objects"` @throw invalid_iterator.210 if @a first and @a last do not belong to the same JSON value; example: `"iterators do not fit"` @complexity O(N*log(size() + N)), where N is the number of elements to insert. @liveexample{The example shows how `update()` is used__range.,update} @sa https://docs.python.org/3.6/library/stdtypes.html#dict.update @since version 3.0.0 */ void update(const_iterator first, const_iterator last) { // implicitly convert null value to an empty object if (is_null()) { m_type = value_t::object; m_value.object = create<object_t>(); assert_invariant(); } if (JSON_UNLIKELY(not is_object())) { JSON_THROW(type_error::create(312, "cannot use update() with " + std::string(type_name()))); } // check if range iterators belong to the same JSON object if (JSON_UNLIKELY(first.m_object != last.m_object)) { JSON_THROW(invalid_iterator::create(210, "iterators do not fit")); } // passed iterators must belong to objects if (JSON_UNLIKELY(not first.m_object->is_object() or not last.m_object->is_object())) { JSON_THROW(invalid_iterator::create(202, "iterators first and last must point to objects")); } for (auto it = first; it != last; ++it) { m_value.object->operator[](it.key()) = it.value(); } } /*! @brief exchanges the values Exchanges the contents of the JSON value with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other JSON value to exchange the contents with @complexity Constant. @liveexample{The example below shows how JSON values can be swapped with `swap()`.,swap__reference} @since version 1.0.0 */ void swap(reference other) noexcept ( std::is_nothrow_move_constructible<value_t>::value and std::is_nothrow_move_assignable<value_t>::value and std::is_nothrow_move_constructible<json_value>::value and std::is_nothrow_move_assignable<json_value>::value ) { std::swap(m_type, other.m_type); std::swap(m_value, other.m_value); assert_invariant(); } /*! @brief exchanges the values Exchanges the contents of a JSON array with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other array to exchange the contents with @throw type_error.310 when JSON value is not an array; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how arrays can be swapped with `swap()`.,swap__array_t} @since version 1.0.0 */ void swap(array_t& other) { // swap only works for arrays if (JSON_LIKELY(is_array())) { std::swap(*(m_value.array), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON object with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other object to exchange the contents with @throw type_error.310 when JSON value is not an object; example: `"cannot use swap() with string"` @complexity Constant. @liveexample{The example below shows how objects can be swapped with `swap()`.,swap__object_t} @since version 1.0.0 */ void swap(object_t& other) { // swap only works for objects if (JSON_LIKELY(is_object())) { std::swap(*(m_value.object), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /*! @brief exchanges the values Exchanges the contents of a JSON string with those of @a other. Does not invoke any move, copy, or swap operations on individual elements. All iterators and references remain valid. The past-the-end iterator is invalidated. @param[in,out] other string to exchange the contents with @throw type_error.310 when JSON value is not a string; example: `"cannot use swap() with boolean"` @complexity Constant. @liveexample{The example below shows how strings can be swapped with `swap()`.,swap__string_t} @since version 1.0.0 */ void swap(string_t& other) { // swap only works for strings if (JSON_LIKELY(is_string())) { std::swap(*(m_value.string), other); } else { JSON_THROW(type_error::create(310, "cannot use swap() with " + std::string(type_name()))); } } /// @} public: ////////////////////////////////////////// // lexicographical comparison operators // ////////////////////////////////////////// /// @name lexicographical comparison operators /// @{ /*! @brief comparison: equal Compares two JSON values for equality according to the following rules: - Two JSON values are equal if (1) they are from the same type and (2) their stored values are the same according to their respective `operator==`. - Integer and floating-point numbers are automatically converted before comparison. Note than two NaN values are always treated as unequal. - Two JSON null values are equal. @note Floating-point inside JSON values numbers are compared with `json::number_float_t::operator==` which is `double::operator==` by default. To compare floating-point while respecting an epsilon, an alternative [comparison function](https://github.com/mariokonrad/marnav/blob/master/src/marnav/math/floatingpoint.hpp#L34-#L39) could be used, for instance @code {.cpp} template<typename T, typename = typename std::enable_if<std::is_floating_point<T>::value, T>::type> inline bool is_same(T a, T b, T epsilon = std::numeric_limits<T>::epsilon()) noexcept { return std::abs(a - b) <= epsilon; } @endcode @note NaN values never compare equal to themselves or to other NaN values. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are equal @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Linear. @liveexample{The example demonstrates comparing several JSON types.,operator__equal} @since version 1.0.0 */ friend bool operator==(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return (*lhs.m_value.array == *rhs.m_value.array); case value_t::object: return (*lhs.m_value.object == *rhs.m_value.object); case value_t::null: return true; case value_t::string: return (*lhs.m_value.string == *rhs.m_value.string); case value_t::boolean: return (lhs.m_value.boolean == rhs.m_value.boolean); case value_t::number_integer: return (lhs.m_value.number_integer == rhs.m_value.number_integer); case value_t::number_unsigned: return (lhs.m_value.number_unsigned == rhs.m_value.number_unsigned); case value_t::number_float: return (lhs.m_value.number_float == rhs.m_value.number_float); default: return false; } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return (static_cast<number_float_t>(lhs.m_value.number_integer) == rhs.m_value.number_float); } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_integer)); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return (static_cast<number_float_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_float); } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return (lhs.m_value.number_float == static_cast<number_float_t>(rhs.m_value.number_unsigned)); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return (static_cast<number_integer_t>(lhs.m_value.number_unsigned) == rhs.m_value.number_integer); } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return (lhs.m_value.number_integer == static_cast<number_integer_t>(rhs.m_value.number_unsigned)); } return false; } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const_reference lhs, const ScalarType rhs) noexcept { return (lhs == basic_json(rhs)); } /*! @brief comparison: equal @copydoc operator==(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator==(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) == rhs); } /*! @brief comparison: not equal Compares two JSON values for inequality by calculating `not (lhs == rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether the values @a lhs and @a rhs are not equal @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__notequal} @since version 1.0.0 */ friend bool operator!=(const_reference lhs, const_reference rhs) noexcept { return not (lhs == rhs); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs != basic_json(rhs)); } /*! @brief comparison: not equal @copydoc operator!=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator!=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) != rhs); } /*! @brief comparison: less than Compares whether one JSON value @a lhs is less than another JSON value @a rhs according to the following rules: - If @a lhs and @a rhs have the same type, the values are compared using the default `<` operator. - Integer and floating-point numbers are automatically converted before comparison - In case @a lhs and @a rhs have different types, the values are ignored and the order of the types is considered, see @ref operator<(const value_t, const value_t). @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__less} @since version 1.0.0 */ friend bool operator<(const_reference lhs, const_reference rhs) noexcept { const auto lhs_type = lhs.type(); const auto rhs_type = rhs.type(); if (lhs_type == rhs_type) { switch (lhs_type) { case value_t::array: return (*lhs.m_value.array) < (*rhs.m_value.array); case value_t::object: return *lhs.m_value.object < *rhs.m_value.object; case value_t::null: return false; case value_t::string: return *lhs.m_value.string < *rhs.m_value.string; case value_t::boolean: return lhs.m_value.boolean < rhs.m_value.boolean; case value_t::number_integer: return lhs.m_value.number_integer < rhs.m_value.number_integer; case value_t::number_unsigned: return lhs.m_value.number_unsigned < rhs.m_value.number_unsigned; case value_t::number_float: return lhs.m_value.number_float < rhs.m_value.number_float; default: return false; } } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_integer) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_integer) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_integer); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_float) { return static_cast<number_float_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_float; } else if (lhs_type == value_t::number_float and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_float < static_cast<number_float_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_integer and rhs_type == value_t::number_unsigned) { return lhs.m_value.number_integer < static_cast<number_integer_t>(rhs.m_value.number_unsigned); } else if (lhs_type == value_t::number_unsigned and rhs_type == value_t::number_integer) { return static_cast<number_integer_t>(lhs.m_value.number_unsigned) < rhs.m_value.number_integer; } // We only reach this line if we cannot compare values. In that case, // we compare types. Note we have to call the operator explicitly, // because MSVC has problems otherwise. return operator<(lhs_type, rhs_type); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(const_reference lhs, const ScalarType rhs) noexcept { return (lhs < basic_json(rhs)); } /*! @brief comparison: less than @copydoc operator<(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) < rhs); } /*! @brief comparison: less than or equal Compares whether one JSON value @a lhs is less than or equal to another JSON value by calculating `not (rhs < lhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is less than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greater} @since version 1.0.0 */ friend bool operator<=(const_reference lhs, const_reference rhs) noexcept { return not (rhs < lhs); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs <= basic_json(rhs)); } /*! @brief comparison: less than or equal @copydoc operator<=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator<=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) <= rhs); } /*! @brief comparison: greater than Compares whether one JSON value @a lhs is greater than another JSON value by calculating `not (lhs <= rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__lessequal} @since version 1.0.0 */ friend bool operator>(const_reference lhs, const_reference rhs) noexcept { return not (lhs <= rhs); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(const_reference lhs, const ScalarType rhs) noexcept { return (lhs > basic_json(rhs)); } /*! @brief comparison: greater than @copydoc operator>(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) > rhs); } /*! @brief comparison: greater than or equal Compares whether one JSON value @a lhs is greater than or equal to another JSON value by calculating `not (lhs < rhs)`. @param[in] lhs first JSON value to consider @param[in] rhs second JSON value to consider @return whether @a lhs is greater than or equal to @a rhs @complexity Linear. @exceptionsafety No-throw guarantee: this function never throws exceptions. @liveexample{The example demonstrates comparing several JSON types.,operator__greaterequal} @since version 1.0.0 */ friend bool operator>=(const_reference lhs, const_reference rhs) noexcept { return not (lhs < rhs); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(const_reference lhs, const ScalarType rhs) noexcept { return (lhs >= basic_json(rhs)); } /*! @brief comparison: greater than or equal @copydoc operator>=(const_reference, const_reference) */ template<typename ScalarType, typename std::enable_if< std::is_scalar<ScalarType>::value, int>::type = 0> friend bool operator>=(const ScalarType lhs, const_reference rhs) noexcept { return (basic_json(lhs) >= rhs); } /// @} /////////////////// // serialization // /////////////////// /// @name serialization /// @{ /*! @brief serialize to stream Serialize the given JSON value @a j to the output stream @a o. The JSON value will be serialized using the @ref dump member function. - The indentation of the output can be controlled with the member variable `width` of the output stream @a o. For instance, using the manipulator `std::setw(4)` on @a o sets the indentation level to `4` and the serialization result is the same as calling `dump(4)`. - The indentation character can be controlled with the member variable `fill` of the output stream @a o. For instance, the manipulator `std::setfill('\\t')` sets indentation to use a tab character rather than the default space character. @param[in,out] o stream to serialize to @param[in] j JSON value to serialize @return the stream @a o @throw type_error.316 if a string stored inside the JSON value is not UTF-8 encoded @complexity Linear. @liveexample{The example below shows the serialization with different parameters to `width` to adjust the indentation level.,operator_serialize} @since version 1.0.0; indentation character added in version 3.0.0 */ friend std::ostream& operator<<(std::ostream& o, const basic_json& j) { // read width member and use it as indentation parameter if nonzero const bool pretty_print = (o.width() > 0); const auto indentation = (pretty_print ? o.width() : 0); // reset width to 0 for subsequent calls to this stream o.width(0); // do the actual serialization serializer s(detail::output_adapter<char>(o), o.fill()); s.dump(j, pretty_print, false, static_cast<unsigned int>(indentation)); return o; } /*! @brief serialize to stream @deprecated This stream operator is deprecated and will be removed in future 4.0.0 of the library. Please use @ref operator<<(std::ostream&, const basic_json&) instead; that is, replace calls like `j >> o;` with `o << j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_DEPRECATED friend std::ostream& operator>>(const basic_json& j, std::ostream& o) { return o << j; } /// @} ///////////////////// // deserialization // ///////////////////// /// @name deserialization /// @{ /*! @brief deserialize from a compatible input This function reads from a compatible input. Examples are: - an array of 1-byte values - strings with character/literal type with size of 1 byte - input streams - container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @pre The container storage is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with a noncompliant container and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @param[in] i input to read from @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an array.,parse__array__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__string__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function with and without callback function.,parse__istream__parser_callback_t} @liveexample{The example below demonstrates the `parse()` function reading from a contiguous container.,parse__contiguouscontainer__parser_callback_t} @since version 2.0.3 (contiguous containers) */ static basic_json parse(detail::input_adapter&& i, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(i, cb, allow_exceptions).parse(true, result); return result; } static bool accept(detail::input_adapter&& i) { return parser(i).accept(true); } /*! @brief generate SAX events The SAX event lister must follow the interface of @ref json_sax. This function reads from a compatible input. Examples are: - an array of 1-byte values - strings with character/literal type with size of 1 byte - input streams - container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @pre The container storage is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element of the container has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with a noncompliant container and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @param[in] i input to read from @param[in,out] sax SAX event listener @param[in] format the format to parse (JSON, CBOR, MessagePack, or UBJSON) @param[in] strict whether the input has to be consumed completely @return return value of the last processed SAX event @throw parse_error.101 if a parse error occurs; example: `""unexpected end of input; expected string literal""` @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the SAX consumer @a sax has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `sax_parse()` function reading from string and processing the events with a user-defined SAX event consumer.,sax_parse} @since version 3.2.0 */ template <typename SAX> static bool sax_parse(detail::input_adapter&& i, SAX* sax, input_format_t format = input_format_t::json, const bool strict = true) { assert(sax); switch (format) { case input_format_t::json: return parser(std::move(i)).sax_parse(sax, strict); default: return detail::binary_reader<basic_json, SAX>(std::move(i)).sax_parse(format, sax, strict); } } /*! @brief deserialize from an iterator range with contiguous storage This function reads from an iterator range of a container with contiguous storage of 1-byte values. Compatible container types include `std::vector`, `std::string`, `std::array`, `std::valarray`, and `std::initializer_list`. Furthermore, C-style arrays can be used with `std::begin()`/`std::end()`. User-defined containers can be used as long as they implement random-access iterators and a contiguous storage. @pre The iterator range is contiguous. Violating this precondition yields undefined behavior. **This precondition is enforced with an assertion.** @pre Each element in the range has a size of 1 byte. Violating this precondition yields undefined behavior. **This precondition is enforced with a static assertion.** @warning There is no way to enforce all preconditions at compile-time. If the function is called with noncompliant iterators and with assertions switched off, the behavior is undefined and will most likely yield segmentation violation. @tparam IteratorType iterator of container with contiguous storage @param[in] first begin of the range to parse (included) @param[in] last end of the range to parse (excluded) @param[in] cb a parser callback function of type @ref parser_callback_t which is used to control the deserialization by filtering unwanted values (optional) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. The complexity can be higher if the parser callback function @a cb has a super-linear complexity. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below demonstrates the `parse()` function reading from an iterator range.,parse__iteratortype__parser_callback_t} @since version 2.0.3 */ template<class IteratorType, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static basic_json parse(IteratorType first, IteratorType last, const parser_callback_t cb = nullptr, const bool allow_exceptions = true) { basic_json result; parser(detail::input_adapter(first, last), cb, allow_exceptions).parse(true, result); return result; } template<class IteratorType, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static bool accept(IteratorType first, IteratorType last) { return parser(detail::input_adapter(first, last)).accept(true); } template<class IteratorType, class SAX, typename std::enable_if< std::is_base_of< std::random_access_iterator_tag, typename std::iterator_traits<IteratorType>::iterator_category>::value, int>::type = 0> static bool sax_parse(IteratorType first, IteratorType last, SAX* sax) { return parser(detail::input_adapter(first, last)).sax_parse(sax); } /*! @brief deserialize from stream @deprecated This stream operator is deprecated and will be removed in version 4.0.0 of the library. Please use @ref operator>>(std::istream&, basic_json&) instead; that is, replace calls like `j << i;` with `i >> j;`. @since version 1.0.0; deprecated since version 3.0.0 */ JSON_DEPRECATED friend std::istream& operator<<(basic_json& j, std::istream& i) { return operator>>(i, j); } /*! @brief deserialize from stream Deserializes an input stream to a JSON value. @param[in,out] i input stream to read a serialized JSON value from @param[in,out] j JSON value to write the deserialized input to @throw parse_error.101 in case of an unexpected token @throw parse_error.102 if to_unicode fails or surrogate error @throw parse_error.103 if to_unicode fails @complexity Linear in the length of the input. The parser is a predictive LL(1) parser. @note A UTF-8 byte order mark is silently ignored. @liveexample{The example below shows how a JSON value is constructed by reading a serialization from a stream.,operator_deserialize} @sa parse(std::istream&, const parser_callback_t) for a variant with a parser callback function to filter values while parsing @since version 1.0.0 */ friend std::istream& operator>>(std::istream& i, basic_json& j) { parser(detail::input_adapter(i)).parse(false, j); return i; } /// @} /////////////////////////// // convenience functions // /////////////////////////// /*! @brief return the type as string Returns the type name as string to be used in error messages - usually to indicate that a function was called on a wrong JSON type. @return a string representation of a the @a m_type member: Value type | return value ----------- | ------------- null | `"null"` boolean | `"boolean"` string | `"string"` number | `"number"` (for all number types) object | `"object"` array | `"array"` discarded | `"discarded"` @exceptionsafety No-throw guarantee: this function never throws exceptions. @complexity Constant. @liveexample{The following code exemplifies `type_name()` for all JSON types.,type_name} @sa @ref type() -- return the type of the JSON value @sa @ref operator value_t() -- return the type of the JSON value (implicit) @since version 1.0.0, public since 2.1.0, `const char*` and `noexcept` since 3.0.0 */ const char* type_name() const noexcept { { switch (m_type) { case value_t::null: return "null"; case value_t::object: return "object"; case value_t::array: return "array"; case value_t::string: return "string"; case value_t::boolean: return "boolean"; case value_t::discarded: return "discarded"; default: return "number"; } } } private: ////////////////////// // member variables // ////////////////////// /// the type of the current element value_t m_type = value_t::null; /// the value of the current element json_value m_value = {}; ////////////////////////////////////////// // binary serialization/deserialization // ////////////////////////////////////////// /// @name binary serialization/deserialization support /// @{ public: /*! @brief create a CBOR serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the CBOR (Concise Binary Object Representation) serialization format. CBOR is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to CBOR types according to the CBOR specification (RFC 7049): JSON value type | value/range | CBOR type | first byte --------------- | ------------------------------------------ | ---------------------------------- | --------------- null | `null` | Null | 0xF6 boolean | `true` | True | 0xF5 boolean | `false` | False | 0xF4 number_integer | -9223372036854775808..-2147483649 | Negative integer (8 bytes follow) | 0x3B number_integer | -2147483648..-32769 | Negative integer (4 bytes follow) | 0x3A number_integer | -32768..-129 | Negative integer (2 bytes follow) | 0x39 number_integer | -128..-25 | Negative integer (1 byte follow) | 0x38 number_integer | -24..-1 | Negative integer | 0x20..0x37 number_integer | 0..23 | Integer | 0x00..0x17 number_integer | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_integer | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_integer | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A number_integer | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B number_unsigned | 0..23 | Integer | 0x00..0x17 number_unsigned | 24..255 | Unsigned integer (1 byte follow) | 0x18 number_unsigned | 256..65535 | Unsigned integer (2 bytes follow) | 0x19 number_unsigned | 65536..4294967295 | Unsigned integer (4 bytes follow) | 0x1A number_unsigned | 4294967296..18446744073709551615 | Unsigned integer (8 bytes follow) | 0x1B number_float | *any value* | Double-Precision Float | 0xFB string | *length*: 0..23 | UTF-8 string | 0x60..0x77 string | *length*: 23..255 | UTF-8 string (1 byte follow) | 0x78 string | *length*: 256..65535 | UTF-8 string (2 bytes follow) | 0x79 string | *length*: 65536..4294967295 | UTF-8 string (4 bytes follow) | 0x7A string | *length*: 4294967296..18446744073709551615 | UTF-8 string (8 bytes follow) | 0x7B array | *size*: 0..23 | array | 0x80..0x97 array | *size*: 23..255 | array (1 byte follow) | 0x98 array | *size*: 256..65535 | array (2 bytes follow) | 0x99 array | *size*: 65536..4294967295 | array (4 bytes follow) | 0x9A array | *size*: 4294967296..18446744073709551615 | array (8 bytes follow) | 0x9B object | *size*: 0..23 | map | 0xA0..0xB7 object | *size*: 23..255 | map (1 byte follow) | 0xB8 object | *size*: 256..65535 | map (2 bytes follow) | 0xB9 object | *size*: 65536..4294967295 | map (4 bytes follow) | 0xBA object | *size*: 4294967296..18446744073709551615 | map (8 bytes follow) | 0xBB @note The mapping is **complete** in the sense that any JSON value type can be converted to a CBOR value. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The following CBOR types are not used in the conversion: - byte strings (0x40..0x5F) - UTF-8 strings terminated by "break" (0x7F) - arrays terminated by "break" (0x9F) - maps terminated by "break" (0xBF) - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - tagged items (0xC6..0xD4, 0xD8..0xDB) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) - half and single-precision floats (0xF9-0xFA) - break (0xFF) @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in CBOR format.,to_cbor} @sa http://cbor.io @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the analogous deserialization @sa @ref to_msgpack(const basic_json&) for the related MessagePack format @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @since version 2.0.9 */ static std::vector<uint8_t> to_cbor(const basic_json& j) { std::vector<uint8_t> result; to_cbor(j, result); return result; } static void to_cbor(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_cbor(j); } static void to_cbor(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_cbor(j); } /*! @brief create a MessagePack serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the MessagePack serialization format. MessagePack is a binary serialization format which aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to MessagePack types according to the MessagePack specification: JSON value type | value/range | MessagePack type | first byte --------------- | --------------------------------- | ---------------- | ---------- null | `null` | nil | 0xC0 boolean | `true` | true | 0xC3 boolean | `false` | false | 0xC2 number_integer | -9223372036854775808..-2147483649 | int64 | 0xD3 number_integer | -2147483648..-32769 | int32 | 0xD2 number_integer | -32768..-129 | int16 | 0xD1 number_integer | -128..-33 | int8 | 0xD0 number_integer | -32..-1 | negative fixint | 0xE0..0xFF number_integer | 0..127 | positive fixint | 0x00..0x7F number_integer | 128..255 | uint 8 | 0xCC number_integer | 256..65535 | uint 16 | 0xCD number_integer | 65536..4294967295 | uint 32 | 0xCE number_integer | 4294967296..18446744073709551615 | uint 64 | 0xCF number_unsigned | 0..127 | positive fixint | 0x00..0x7F number_unsigned | 128..255 | uint 8 | 0xCC number_unsigned | 256..65535 | uint 16 | 0xCD number_unsigned | 65536..4294967295 | uint 32 | 0xCE number_unsigned | 4294967296..18446744073709551615 | uint 64 | 0xCF number_float | *any value* | float 64 | 0xCB string | *length*: 0..31 | fixstr | 0xA0..0xBF string | *length*: 32..255 | str 8 | 0xD9 string | *length*: 256..65535 | str 16 | 0xDA string | *length*: 65536..4294967295 | str 32 | 0xDB array | *size*: 0..15 | fixarray | 0x90..0x9F array | *size*: 16..65535 | array 16 | 0xDC array | *size*: 65536..4294967295 | array 32 | 0xDD object | *size*: 0..15 | fix map | 0x80..0x8F object | *size*: 16..65535 | map 16 | 0xDE object | *size*: 65536..4294967295 | map 32 | 0xDF @note The mapping is **complete** in the sense that any JSON value type can be converted to a MessagePack value. @note The following values can **not** be converted to a MessagePack value: - strings with more than 4294967295 bytes - arrays with more than 4294967295 elements - objects with more than 4294967295 elements @note The following MessagePack types are not used in the conversion: - bin 8 - bin 32 (0xC4..0xC6) - ext 8 - ext 32 (0xC7..0xC9) - float 32 (0xCA) - fixext 1 - fixext 16 (0xD4..0xD8) @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @param[in] j JSON value to serialize @return MessagePack serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in MessagePack format.,to_msgpack} @sa http://msgpack.org @sa @ref from_msgpack for the analogous deserialization @sa @ref to_cbor(const basic_json& for the related CBOR format @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @since version 2.0.9 */ static std::vector<uint8_t> to_msgpack(const basic_json& j) { std::vector<uint8_t> result; to_msgpack(j, result); return result; } static void to_msgpack(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_msgpack(j); } static void to_msgpack(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_msgpack(j); } /*! @brief create a UBJSON serialization of a given JSON value Serializes a given JSON value @a j to a byte vector using the UBJSON (Universal Binary JSON) serialization format. UBJSON aims to be more compact than JSON itself, yet more efficient to parse. The library uses the following mapping from JSON values types to UBJSON types according to the UBJSON specification: JSON value type | value/range | UBJSON type | marker --------------- | --------------------------------- | ----------- | ------ null | `null` | null | `Z` boolean | `true` | true | `T` boolean | `false` | false | `F` number_integer | -9223372036854775808..-2147483649 | int64 | `L` number_integer | -2147483648..-32769 | int32 | `l` number_integer | -32768..-129 | int16 | `I` number_integer | -128..127 | int8 | `i` number_integer | 128..255 | uint8 | `U` number_integer | 256..32767 | int16 | `I` number_integer | 32768..2147483647 | int32 | `l` number_integer | 2147483648..9223372036854775807 | int64 | `L` number_unsigned | 0..127 | int8 | `i` number_unsigned | 128..255 | uint8 | `U` number_unsigned | 256..32767 | int16 | `I` number_unsigned | 32768..2147483647 | int32 | `l` number_unsigned | 2147483648..9223372036854775807 | int64 | `L` number_float | *any value* | float64 | `D` string | *with shortest length indicator* | string | `S` array | *see notes on optimized format* | array | `[` object | *see notes on optimized format* | map | `{` @note The mapping is **complete** in the sense that any JSON value type can be converted to a UBJSON value. @note The following values can **not** be converted to a UBJSON value: - strings with more than 9223372036854775807 bytes (theoretical) - unsigned integer numbers above 9223372036854775807 @note The following markers are not used in the conversion: - `Z`: no-op values are not created. - `C`: single-byte strings are serialized with `S` markers. @note Any UBJSON output created @ref to_ubjson can be successfully parsed by @ref from_ubjson. @note If NaN or Infinity are stored inside a JSON number, they are serialized properly. This behavior differs from the @ref dump() function which serializes NaN or Infinity to `null`. @note The optimized formats for containers are supported: Parameter @a use_size adds size information to the beginning of a container and removes the closing marker. Parameter @a use_type further checks whether all elements of a container have the same type and adds the type marker to the beginning of the container. The @a use_type parameter must only be used together with @a use_size = true. Note that @a use_size = true alone may result in larger representations - the benefit of this parameter is that the receiving side is immediately informed on the number of elements of the container. @param[in] j JSON value to serialize @param[in] use_size whether to add size annotations to container types @param[in] use_type whether to add type annotations to container types (must be combined with @a use_size = true) @return UBJSON serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in UBJSON format.,to_ubjson} @sa http://ubjson.org @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the analogous deserialization @sa @ref to_cbor(const basic_json& for the related CBOR format @sa @ref to_msgpack(const basic_json&) for the related MessagePack format @since version 3.1.0 */ static std::vector<uint8_t> to_ubjson(const basic_json& j, const bool use_size = false, const bool use_type = false) { std::vector<uint8_t> result; to_ubjson(j, result, use_size, use_type); return result; } static void to_ubjson(const basic_json& j, detail::output_adapter<uint8_t> o, const bool use_size = false, const bool use_type = false) { binary_writer<uint8_t>(o).write_ubjson(j, use_size, use_type); } static void to_ubjson(const basic_json& j, detail::output_adapter<char> o, const bool use_size = false, const bool use_type = false) { binary_writer<char>(o).write_ubjson(j, use_size, use_type); } /*! @brief Serializes the given JSON object `j` to BSON and returns a vector containing the corresponding BSON-representation. BSON (Binary JSON) is a binary format in which zero or more ordered key/value pairs are stored as a single entity (a so-called document). The library uses the following mapping from JSON values types to BSON types: JSON value type | value/range | BSON type | marker --------------- | --------------------------------- | ----------- | ------ null | `null` | null | 0x0A boolean | `true`, `false` | boolean | 0x08 number_integer | -9223372036854775808..-2147483649 | int64 | 0x12 number_integer | -2147483648..2147483647 | int32 | 0x10 number_integer | 2147483648..9223372036854775807 | int64 | 0x12 number_unsigned | 0..2147483647 | int32 | 0x10 number_unsigned | 2147483648..9223372036854775807 | int64 | 0x12 number_unsigned | 9223372036854775808..18446744073709551615| -- | -- number_float | *any value* | double | 0x01 string | *any value* | string | 0x02 array | *any value* | document | 0x04 object | *any value* | document | 0x03 @warning The mapping is **incomplete**, since only JSON-objects (and things contained therein) can be serialized to BSON. Also, integers larger than 9223372036854775807 cannot be serialized to BSON, and the keys may not contain U+0000, since they are serialized a zero-terminated c-strings. @throw out_of_range.407 if `j.is_number_unsigned() && j.get<std::uint64_t>() > 9223372036854775807` @throw out_of_range.409 if a key in `j` contains a NULL (U+0000) @throw type_error.317 if `!j.is_object()` @pre The input `j` is required to be an object: `j.is_object() == true`. @note Any BSON output created via @ref to_bson can be successfully parsed by @ref from_bson. @param[in] j JSON value to serialize @return BSON serialization as byte vector @complexity Linear in the size of the JSON value @a j. @liveexample{The example shows the serialization of a JSON value to a byte vector in BSON format.,to_bson} @sa http://bsonspec.org/spec.html @sa @ref from_bson(detail::input_adapter&&, const bool strict) for the analogous deserialization @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the related UBJSON format @sa @ref to_cbor(const basic_json&) for the related CBOR format @sa @ref to_msgpack(const basic_json&) for the related MessagePack format */ static std::vector<uint8_t> to_bson(const basic_json& j) { std::vector<uint8_t> result; to_bson(j, result); return result; } /*! @brief Serializes the given JSON object `j` to BSON and forwards the corresponding BSON-representation to the given output_adapter `o`. @param j The JSON object to convert to BSON. @param o The output adapter that receives the binary BSON representation. @pre The input `j` shall be an object: `j.is_object() == true` @sa @ref to_bson(const basic_json&) */ static void to_bson(const basic_json& j, detail::output_adapter<uint8_t> o) { binary_writer<uint8_t>(o).write_bson(j); } /*! @copydoc to_bson(const basic_json&, detail::output_adapter<uint8_t>) */ static void to_bson(const basic_json& j, detail::output_adapter<char> o) { binary_writer<char>(o).write_bson(j); } /*! @brief create a JSON value from an input in CBOR format Deserializes a given input @a i to a JSON value using the CBOR (Concise Binary Object Representation) serialization format. The library maps CBOR types to JSON value types as follows: CBOR type | JSON value type | first byte ---------------------- | --------------- | ---------- Integer | number_unsigned | 0x00..0x17 Unsigned integer | number_unsigned | 0x18 Unsigned integer | number_unsigned | 0x19 Unsigned integer | number_unsigned | 0x1A Unsigned integer | number_unsigned | 0x1B Negative integer | number_integer | 0x20..0x37 Negative integer | number_integer | 0x38 Negative integer | number_integer | 0x39 Negative integer | number_integer | 0x3A Negative integer | number_integer | 0x3B Negative integer | number_integer | 0x40..0x57 UTF-8 string | string | 0x60..0x77 UTF-8 string | string | 0x78 UTF-8 string | string | 0x79 UTF-8 string | string | 0x7A UTF-8 string | string | 0x7B UTF-8 string | string | 0x7F array | array | 0x80..0x97 array | array | 0x98 array | array | 0x99 array | array | 0x9A array | array | 0x9B array | array | 0x9F map | object | 0xA0..0xB7 map | object | 0xB8 map | object | 0xB9 map | object | 0xBA map | object | 0xBB map | object | 0xBF False | `false` | 0xF4 True | `true` | 0xF5 Null | `null` | 0xF6 Half-Precision Float | number_float | 0xF9 Single-Precision Float | number_float | 0xFA Double-Precision Float | number_float | 0xFB @warning The mapping is **incomplete** in the sense that not all CBOR types can be converted to a JSON value. The following CBOR types are not supported and will yield parse errors (parse_error.112): - byte strings (0x40..0x5F) - date/time (0xC0..0xC1) - bignum (0xC2..0xC3) - decimal fraction (0xC4) - bigfloat (0xC5) - tagged items (0xC6..0xD4, 0xD8..0xDB) - expected conversions (0xD5..0xD7) - simple values (0xE0..0xF3, 0xF8) - undefined (0xF7) @warning CBOR allows map keys of any type, whereas JSON only allows strings as keys in object values. Therefore, CBOR maps with keys other than UTF-8 strings are rejected (parse_error.113). @note Any CBOR output created @ref to_cbor can be successfully parsed by @ref from_cbor. @param[in] i an input in CBOR format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from CBOR were used in the given input @a v or if the input is not valid CBOR @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in CBOR format to a JSON value.,from_cbor} @sa http://cbor.io @sa @ref to_cbor(const basic_json&) for the analogous serialization @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the related MessagePack format @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the related UBJSON format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0; added @a allow_exceptions parameter since 3.2.0 */ static basic_json from_cbor(detail::input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::cbor, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_cbor(detail::input_adapter&&, const bool, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_cbor(A1 && a1, A2 && a2, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::cbor, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @brief create a JSON value from an input in MessagePack format Deserializes a given input @a i to a JSON value using the MessagePack serialization format. The library maps MessagePack types to JSON value types as follows: MessagePack type | JSON value type | first byte ---------------- | --------------- | ---------- positive fixint | number_unsigned | 0x00..0x7F fixmap | object | 0x80..0x8F fixarray | array | 0x90..0x9F fixstr | string | 0xA0..0xBF nil | `null` | 0xC0 false | `false` | 0xC2 true | `true` | 0xC3 float 32 | number_float | 0xCA float 64 | number_float | 0xCB uint 8 | number_unsigned | 0xCC uint 16 | number_unsigned | 0xCD uint 32 | number_unsigned | 0xCE uint 64 | number_unsigned | 0xCF int 8 | number_integer | 0xD0 int 16 | number_integer | 0xD1 int 32 | number_integer | 0xD2 int 64 | number_integer | 0xD3 str 8 | string | 0xD9 str 16 | string | 0xDA str 32 | string | 0xDB array 16 | array | 0xDC array 32 | array | 0xDD map 16 | object | 0xDE map 32 | object | 0xDF negative fixint | number_integer | 0xE0-0xFF @warning The mapping is **incomplete** in the sense that not all MessagePack types can be converted to a JSON value. The following MessagePack types are not supported and will yield parse errors: - bin 8 - bin 32 (0xC4..0xC6) - ext 8 - ext 32 (0xC7..0xC9) - fixext 1 - fixext 16 (0xD4..0xD8) @note Any MessagePack output created @ref to_msgpack can be successfully parsed by @ref from_msgpack. @param[in] i an input in MessagePack format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if unsupported features from MessagePack were used in the given input @a i or if the input is not valid MessagePack @throw parse_error.113 if a string was expected as map key, but not found @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in MessagePack format to a JSON value.,from_msgpack} @sa http://msgpack.org @sa @ref to_msgpack(const basic_json&) for the analogous serialization @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the related CBOR format @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the related UBJSON format @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for the related BSON format @since version 2.0.9; parameter @a start_index since 2.1.1; changed to consume input adapters, removed start_index parameter, and added @a strict parameter since 3.0.0; added @a allow_exceptions parameter since 3.2.0 */ static basic_json from_msgpack(detail::input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_msgpack(detail::input_adapter&&, const bool, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_msgpack(A1 && a1, A2 && a2, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::msgpack, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @brief create a JSON value from an input in UBJSON format Deserializes a given input @a i to a JSON value using the UBJSON (Universal Binary JSON) serialization format. The library maps UBJSON types to JSON value types as follows: UBJSON type | JSON value type | marker ----------- | --------------------------------------- | ------ no-op | *no value, next value is read* | `N` null | `null` | `Z` false | `false` | `F` true | `true` | `T` float32 | number_float | `d` float64 | number_float | `D` uint8 | number_unsigned | `U` int8 | number_integer | `i` int16 | number_integer | `I` int32 | number_integer | `l` int64 | number_integer | `L` string | string | `S` char | string | `C` array | array (optimized values are supported) | `[` object | object (optimized values are supported) | `{` @note The mapping is **complete** in the sense that any UBJSON value can be converted to a JSON value. @param[in] i an input in UBJSON format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.110 if the given input ends prematurely or the end of file was not reached when @a strict was set to true @throw parse_error.112 if a parse error occurs @throw parse_error.113 if a string could not be parsed successfully @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in UBJSON format to a JSON value.,from_ubjson} @sa http://ubjson.org @sa @ref to_ubjson(const basic_json&, const bool, const bool) for the analogous serialization @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the related CBOR format @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the related MessagePack format @sa @ref from_bson(detail::input_adapter&&, const bool, const bool) for the related BSON format @since version 3.1.0; added @a allow_exceptions parameter since 3.2.0 */ static basic_json from_ubjson(detail::input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_ubjson(detail::input_adapter&&, const bool, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_ubjson(A1 && a1, A2 && a2, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::ubjson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @brief Create a JSON value from an input in BSON format Deserializes a given input @a i to a JSON value using the BSON (Binary JSON) serialization format. The library maps BSON record types to JSON value types as follows: BSON type | BSON marker byte | JSON value type --------------- | ---------------- | --------------------------- double | 0x01 | number_float string | 0x02 | string document | 0x03 | object array | 0x04 | array binary | 0x05 | still unsupported undefined | 0x06 | still unsupported ObjectId | 0x07 | still unsupported boolean | 0x08 | boolean UTC Date-Time | 0x09 | still unsupported null | 0x0A | null Regular Expr. | 0x0B | still unsupported DB Pointer | 0x0C | still unsupported JavaScript Code | 0x0D | still unsupported Symbol | 0x0E | still unsupported JavaScript Code | 0x0F | still unsupported int32 | 0x10 | number_integer Timestamp | 0x11 | still unsupported 128-bit decimal float | 0x13 | still unsupported Max Key | 0x7F | still unsupported Min Key | 0xFF | still unsupported @warning The mapping is **incomplete**. The unsupported mappings are indicated in the table above. @param[in] i an input in BSON format convertible to an input adapter @param[in] strict whether to expect the input to be consumed until EOF (true by default) @param[in] allow_exceptions whether to throw exceptions in case of a parse error (optional, true by default) @return deserialized JSON value; in case of a parse error and @a allow_exceptions set to `false`, the return value will be value_t::discarded. @throw parse_error.114 if an unsupported BSON record type is encountered @complexity Linear in the size of the input @a i. @liveexample{The example shows the deserialization of a byte vector in BSON format to a JSON value.,from_bson} @sa http://bsonspec.org/spec.html @sa @ref to_bson(const basic_json&) for the analogous serialization @sa @ref from_cbor(detail::input_adapter&&, const bool, const bool) for the related CBOR format @sa @ref from_msgpack(detail::input_adapter&&, const bool, const bool) for the related MessagePack format @sa @ref from_ubjson(detail::input_adapter&&, const bool, const bool) for the related UBJSON format */ static basic_json from_bson(detail::input_adapter&& i, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(i)).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /*! @copydoc from_bson(detail::input_adapter&&, const bool, const bool) */ template<typename A1, typename A2, detail::enable_if_t<std::is_constructible<detail::input_adapter, A1, A2>::value, int> = 0> static basic_json from_bson(A1 && a1, A2 && a2, const bool strict = true, const bool allow_exceptions = true) { basic_json result; detail::json_sax_dom_parser<basic_json> sdp(result, allow_exceptions); const bool res = binary_reader(detail::input_adapter(std::forward<A1>(a1), std::forward<A2>(a2))).sax_parse(input_format_t::bson, &sdp, strict); return res ? result : basic_json(value_t::discarded); } /// @} ////////////////////////// // JSON Pointer support // ////////////////////////// /// @name JSON Pointer functions /// @{ /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. Similar to @ref operator[](const typename object_t::key_type&), `null` values are created in arrays and objects if necessary. In particular: - If the JSON pointer points to an object key that does not exist, it is created an filled with a `null` value before a reference to it is returned. - If the JSON pointer points to an array index that does not exist, it is created an filled with a `null` value before a reference to it is returned. All indices between the current maximum and the given index are also filled with `null`. - The special value `-` is treated as a synonym for the index past the end. @param[in] ptr a JSON pointer @return reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer} @since version 2.0.0 */ reference operator[](const json_pointer& ptr) { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Uses a JSON pointer to retrieve a reference to the respective JSON value. No bound checking is performed. The function does not change the JSON value; no `null` values are created. In particular, the the special value `-` yields an exception. @param[in] ptr JSON pointer to the desired element @return const reference to the element pointed to by @a ptr @complexity Constant. @throw parse_error.106 if an array index begins with '0' @throw parse_error.109 if an array index was not a number @throw out_of_range.402 if the array index '-' is used @throw out_of_range.404 if the JSON pointer can not be resolved @liveexample{The behavior is shown in the example.,operatorjson_pointer_const} @since version 2.0.0 */ const_reference operator[](const json_pointer& ptr) const { return ptr.get_unchecked(this); } /*! @brief access specified element via JSON Pointer Returns a reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer} */ reference at(const json_pointer& ptr) { return ptr.get_checked(this); } /*! @brief access specified element via JSON Pointer Returns a const reference to the element at with specified JSON pointer @a ptr, with bounds checking. @param[in] ptr JSON pointer to the desired element @return reference to the element pointed to by @a ptr @throw parse_error.106 if an array index in the passed JSON pointer @a ptr begins with '0'. See example below. @throw parse_error.109 if an array index in the passed JSON pointer @a ptr is not a number. See example below. @throw out_of_range.401 if an array index in the passed JSON pointer @a ptr is out of range. See example below. @throw out_of_range.402 if the array index '-' is used in the passed JSON pointer @a ptr. As `at` provides checked access (and no elements are implicitly inserted), the index '-' is always invalid. See example below. @throw out_of_range.403 if the JSON pointer describes a key of an object which cannot be found. See example below. @throw out_of_range.404 if the JSON pointer @a ptr can not be resolved. See example below. @exceptionsafety Strong guarantee: if an exception is thrown, there are no changes in the JSON value. @complexity Constant. @since version 2.0.0 @liveexample{The behavior is shown in the example.,at_json_pointer_const} */ const_reference at(const json_pointer& ptr) const { return ptr.get_checked(this); } /*! @brief return flattened JSON value The function creates a JSON object whose keys are JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) and whose values are all primitive. The original JSON value can be restored using the @ref unflatten() function. @return an object that maps JSON pointers to primitive values @note Empty objects and arrays are flattened to `null` and will not be reconstructed correctly by the @ref unflatten() function. @complexity Linear in the size the JSON value. @liveexample{The following code shows how a JSON object is flattened to an object whose keys consist of JSON pointers.,flatten} @sa @ref unflatten() for the reverse function @since version 2.0.0 */ basic_json flatten() const { basic_json result(value_t::object); json_pointer::flatten("", *this, result); return result; } /*! @brief unflatten a previously flattened JSON value The function restores the arbitrary nesting of a JSON value that has been flattened before using the @ref flatten() function. The JSON value must meet certain constraints: 1. The value must be an object. 2. The keys must be JSON pointers (see [RFC 6901](https://tools.ietf.org/html/rfc6901)) 3. The mapped values must be primitive JSON types. @return the original JSON from a flattened version @note Empty objects and arrays are flattened by @ref flatten() to `null` values and can not unflattened to their original type. Apart from this example, for a JSON value `j`, the following is always true: `j == j.flatten().unflatten()`. @complexity Linear in the size the JSON value. @throw type_error.314 if value is not an object @throw type_error.315 if object values are not primitive @liveexample{The following code shows how a flattened JSON object is unflattened into the original nested JSON object.,unflatten} @sa @ref flatten() for the reverse function @since version 2.0.0 */ basic_json unflatten() const { return json_pointer::unflatten(*this); } /// @} ////////////////////////// // JSON Patch functions // ////////////////////////// /// @name JSON Patch functions /// @{ /*! @brief applies a JSON patch [JSON Patch](http://jsonpatch.com) defines a JSON document structure for expressing a sequence of operations to apply to a JSON) document. With this function, a JSON Patch is applied to the current JSON value by executing all operations from the patch. @param[in] json_patch JSON patch document @return patched document @note The application of a patch is atomic: Either all operations succeed and the patched document is returned or an exception is thrown. In any case, the original value is not changed: the patch is applied to a copy of the value. @throw parse_error.104 if the JSON patch does not consist of an array of objects @throw parse_error.105 if the JSON patch is malformed (e.g., mandatory attributes are missing); example: `"operation add must have member path"` @throw out_of_range.401 if an array index is out of range. @throw out_of_range.403 if a JSON pointer inside the patch could not be resolved successfully in the current JSON value; example: `"key baz not found"` @throw out_of_range.405 if JSON pointer has no parent ("add", "remove", "move") @throw other_error.501 if "test" operation was unsuccessful @complexity Linear in the size of the JSON value and the length of the JSON patch. As usually only a fraction of the JSON value is affected by the patch, the complexity can usually be neglected. @liveexample{The following code shows how a JSON patch is applied to a value.,patch} @sa @ref diff -- create a JSON patch by comparing two JSON values @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @sa [RFC 6901 (JSON Pointer)](https://tools.ietf.org/html/rfc6901) @since version 2.0.0 */ basic_json patch(const basic_json& json_patch) const { // make a working copy to apply the patch to basic_json result = *this; // the valid JSON Patch operations enum class patch_operations {add, remove, replace, move, copy, test, invalid}; const auto get_op = [](const std::string & op) { if (op == "add") { return patch_operations::add; } if (op == "remove") { return patch_operations::remove; } if (op == "replace") { return patch_operations::replace; } if (op == "move") { return patch_operations::move; } if (op == "copy") { return patch_operations::copy; } if (op == "test") { return patch_operations::test; } return patch_operations::invalid; }; // wrapper for "add" operation; add value at ptr const auto operation_add = [&result](json_pointer & ptr, basic_json val) { // adding to the root of the target document means replacing it if (ptr.is_root()) { result = val; } else { // make sure the top element of the pointer exists json_pointer top_pointer = ptr.top(); if (top_pointer != ptr) { result.at(top_pointer); } // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result[ptr]; switch (parent.m_type) { case value_t::null: case value_t::object: { // use operator[] to add value parent[last_path] = val; break; } case value_t::array: { if (last_path == "-") { // special case: append to back parent.push_back(val); } else { const auto idx = json_pointer::array_index(last_path); if (JSON_UNLIKELY(static_cast<size_type>(idx) > parent.size())) { // avoid undefined behavior JSON_THROW(out_of_range::create(401, "array index " + std::to_string(idx) + " is out of range")); } // default case: insert add offset parent.insert(parent.begin() + static_cast<difference_type>(idx), val); } break; } // LCOV_EXCL_START default: { // if there exists a parent it cannot be primitive assert(false); } // LCOV_EXCL_STOP } } }; // wrapper for "remove" operation; remove value at ptr const auto operation_remove = [&result](json_pointer & ptr) { // get reference to parent of JSON pointer ptr const auto last_path = ptr.pop_back(); basic_json& parent = result.at(ptr); // remove child if (parent.is_object()) { // perform range check auto it = parent.find(last_path); if (JSON_LIKELY(it != parent.end())) { parent.erase(it); } else { JSON_THROW(out_of_range::create(403, "key '" + last_path + "' not found")); } } else if (parent.is_array()) { // note erase performs range check parent.erase(static_cast<size_type>(json_pointer::array_index(last_path))); } }; // type check: top level value must be an array if (JSON_UNLIKELY(not json_patch.is_array())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // iterate and apply the operations for (const auto& val : json_patch) { // wrapper to get a value for an operation const auto get_value = [&val](const std::string & op, const std::string & member, bool string_type) -> basic_json & { // find value auto it = val.m_value.object->find(member); // context-sensitive error message const auto error_msg = (op == "op") ? "operation" : "operation '" + op + "'"; // check if desired value is present if (JSON_UNLIKELY(it == val.m_value.object->end())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have member '" + member + "'")); } // check if result is of type string if (JSON_UNLIKELY(string_type and not it->second.is_string())) { JSON_THROW(parse_error::create(105, 0, error_msg + " must have string member '" + member + "'")); } // no error: return value return it->second; }; // type check: every element of the array must be an object if (JSON_UNLIKELY(not val.is_object())) { JSON_THROW(parse_error::create(104, 0, "JSON patch must be an array of objects")); } // collect mandatory members const std::string op = get_value("op", "op", true); const std::string path = get_value(op, "path", true); json_pointer ptr(path); switch (get_op(op)) { case patch_operations::add: { operation_add(ptr, get_value("add", "value", false)); break; } case patch_operations::remove: { operation_remove(ptr); break; } case patch_operations::replace: { // the "path" location must exist - use at() result.at(ptr) = get_value("replace", "value", false); break; } case patch_operations::move: { const std::string from_path = get_value("move", "from", true); json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The move operation is functionally identical to a // "remove" operation on the "from" location, followed // immediately by an "add" operation at the target // location with the value that was just removed. operation_remove(from_ptr); operation_add(ptr, v); break; } case patch_operations::copy: { const std::string from_path = get_value("copy", "from", true); const json_pointer from_ptr(from_path); // the "from" location must exist - use at() basic_json v = result.at(from_ptr); // The copy is functionally identical to an "add" // operation at the target location using the value // specified in the "from" member. operation_add(ptr, v); break; } case patch_operations::test: { bool success = false; JSON_TRY { // check if "value" matches the one at "path" // the "path" location must exist - use at() success = (result.at(ptr) == get_value("test", "value", false)); } JSON_INTERNAL_CATCH (out_of_range&) { // ignore out of range errors: success remains false } // throw an exception if test fails if (JSON_UNLIKELY(not success)) { JSON_THROW(other_error::create(501, "unsuccessful: " + val.dump())); } break; } case patch_operations::invalid: { // op must be "add", "remove", "replace", "move", "copy", or // "test" JSON_THROW(parse_error::create(105, 0, "operation value '" + op + "' is invalid")); } } } return result; } /*! @brief creates a diff as a JSON patch Creates a [JSON Patch](http://jsonpatch.com) so that value @a source can be changed into the value @a target by calling @ref patch function. @invariant For two JSON values @a source and @a target, the following code yields always `true`: @code {.cpp} source.patch(diff(source, target)) == target; @endcode @note Currently, only `remove`, `add`, and `replace` operations are generated. @param[in] source JSON value to compare from @param[in] target JSON value to compare against @param[in] path helper value to create JSON pointers @return a JSON patch to convert the @a source to @a target @complexity Linear in the lengths of @a source and @a target. @liveexample{The following code shows how a JSON patch is created as a diff for two JSON values.,diff} @sa @ref patch -- apply a JSON patch @sa @ref merge_patch -- apply a JSON Merge Patch @sa [RFC 6902 (JSON Patch)](https://tools.ietf.org/html/rfc6902) @since version 2.0.0 */ static basic_json diff(const basic_json& source, const basic_json& target, const std::string& path = "") { // the patch basic_json result(value_t::array); // if the values are the same, return empty patch if (source == target) { return result; } if (source.type() != target.type()) { // different types: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); } else { switch (source.type()) { case value_t::array: { // first pass: traverse common elements std::size_t i = 0; while (i < source.size() and i < target.size()) { // recursive call to compare array values at index i auto temp_diff = diff(source[i], target[i], path + "/" + std::to_string(i)); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); ++i; } // i now reached the end of at least one array // in a second pass, traverse the remaining elements // remove my remaining elements const auto end_index = static_cast<difference_type>(result.size()); while (i < source.size()) { // add operations in reverse order to avoid invalid // indices result.insert(result.begin() + end_index, object( { {"op", "remove"}, {"path", path + "/" + std::to_string(i)} })); ++i; } // add other remaining elements while (i < target.size()) { result.push_back( { {"op", "add"}, {"path", path + "/" + std::to_string(i)}, {"value", target[i]} }); ++i; } break; } case value_t::object: { // first pass: traverse this object's elements for (auto it = source.cbegin(); it != source.cend(); ++it) { // escape the key name to be used in a JSON patch const auto key = json_pointer::escape(it.key()); if (target.find(it.key()) != target.end()) { // recursive call to compare object values at key it auto temp_diff = diff(it.value(), target[it.key()], path + "/" + key); result.insert(result.end(), temp_diff.begin(), temp_diff.end()); } else { // found a key that is not in o -> remove it result.push_back(object( { {"op", "remove"}, {"path", path + "/" + key} })); } } // second pass: traverse other object's elements for (auto it = target.cbegin(); it != target.cend(); ++it) { if (source.find(it.key()) == source.end()) { // found a key that is not in this -> add it const auto key = json_pointer::escape(it.key()); result.push_back( { {"op", "add"}, {"path", path + "/" + key}, {"value", it.value()} }); } } break; } default: { // both primitive type: replace value result.push_back( { {"op", "replace"}, {"path", path}, {"value", target} }); break; } } } return result; } /// @} //////////////////////////////// // JSON Merge Patch functions // //////////////////////////////// /// @name JSON Merge Patch functions /// @{ /*! @brief applies a JSON Merge Patch The merge patch format is primarily intended for use with the HTTP PATCH method as a means of describing a set of modifications to a target resource's content. This function applies a merge patch to the current JSON value. The function implements the following algorithm from Section 2 of [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396): ``` define MergePatch(Target, Patch): if Patch is an Object: if Target is not an Object: Target = {} // Ignore the contents and set it to an empty Object for each Name/Value pair in Patch: if Value is null: if Name exists in Target: remove the Name/Value pair from Target else: Target[Name] = MergePatch(Target[Name], Value) return Target else: return Patch ``` Thereby, `Target` is the current object; that is, the patch is applied to the current value. @param[in] apply_patch the patch to apply @complexity Linear in the lengths of @a patch. @liveexample{The following code shows how a JSON Merge Patch is applied to a JSON document.,merge_patch} @sa @ref patch -- apply a JSON patch @sa [RFC 7396 (JSON Merge Patch)](https://tools.ietf.org/html/rfc7396) @since version 3.0.0 */ void merge_patch(const basic_json& apply_patch) { if (apply_patch.is_object()) { if (not is_object()) { *this = object(); } for (auto it = apply_patch.begin(); it != apply_patch.end(); ++it) { if (it.value().is_null()) { erase(it.key()); } else { operator[](it.key()).merge_patch(it.value()); } } } else { *this = apply_patch; } } /// @} }; } // namespace nlohmann /////////////////////// // nonmember support // /////////////////////// // specialization of std::swap, and std::hash namespace std { /// hash value for JSON objects template<> struct hash<nlohmann::json> { /*! @brief return a hash value for a JSON object @since version 1.0.0 */ std::size_t operator()(const nlohmann::json& j) const { // a naive hashing via the string representation const auto& h = hash<nlohmann::json::string_t>(); return h(j.dump()); } }; /// specialization for std::less<value_t> /// @note: do not remove the space after '<', /// see https://github.com/nlohmann/json/pull/679 template<> struct less< ::nlohmann::detail::value_t> { /*! @brief compare two value_t enum values @since version 3.0.0 */ bool operator()(nlohmann::detail::value_t lhs, nlohmann::detail::value_t rhs) const noexcept { return nlohmann::detail::operator<(lhs, rhs); } }; /*! @brief exchanges the values of two JSON objects @since version 1.0.0 */ template<> inline void swap<nlohmann::json>(nlohmann::json& j1, nlohmann::json& j2) noexcept( is_nothrow_move_constructible<nlohmann::json>::value and is_nothrow_move_assignable<nlohmann::json>::value ) { j1.swap(j2); } } // namespace std /*! @brief user-defined string literal for JSON values This operator implements a user-defined string literal for JSON objects. It can be used by adding `"_json"` to a string literal and returns a JSON object if no parse error occurred. @param[in] s a string representation of a JSON object @param[in] n the length of string @a s @return a JSON object @since version 1.0.0 */ inline nlohmann::json operator "" _json(const char* s, std::size_t n) { return nlohmann::json::parse(s, s + n); } /*! @brief user-defined string literal for JSON pointer This operator implements a user-defined string literal for JSON Pointers. It can be used by adding `"_json_pointer"` to a string literal and returns a JSON pointer object if no parse error occurred. @param[in] s a string representation of a JSON Pointer @param[in] n the length of string @a s @return a JSON pointer object @since version 2.0.0 */ inline nlohmann::json::json_pointer operator "" _json_pointer(const char* s, std::size_t n) { return nlohmann::json::json_pointer(std::string(s, n)); } // #include <nlohmann/detail/macro_unscope.hpp> // restore GCC/clang diagnostic settings #if defined(__clang__) || defined(__GNUC__) || defined(__GNUG__) #pragma GCC diagnostic pop #endif #if defined(__clang__) #pragma GCC diagnostic pop #endif // clean up #undef JSON_INTERNAL_CATCH #undef JSON_CATCH #undef JSON_THROW #undef JSON_TRY #undef JSON_LIKELY #undef JSON_UNLIKELY #undef JSON_DEPRECATED #undef JSON_HAS_CPP_14 #undef JSON_HAS_CPP_17 #undef NLOHMANN_BASIC_JSON_TPL_DECLARATION #undef NLOHMANN_BASIC_JSON_TPL #endif using json = nlohmann::json;
[ "itsarabbit@gmail.com" ]
itsarabbit@gmail.com
3643064c2083113827057ff602c1a977958212b3
2a3ddf6a2db5bce9fd401b2f97f919da4b2cc026
/SFEngine/Source/Headers/Actor/Player.h
13a9e81a34d8cd0d311901532be9b3c10b435fdd
[ "Zlib", "LicenseRef-scancode-unknown-license-reference" ]
permissive
croemer/EECS581Project
87e05a975d8ab003f236aae1185bbaabffc84f1a
2209050e1fc3e614928018950faf1da44605c842
refs/heads/master
2021-01-19T20:23:18.682056
2017-02-26T16:59:39
2017-02-26T16:59:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,304
h
#ifndef SFENGINE_PLAYER_H #define SFENGINE_PLAYER_H #include "Actor.h" namespace Engine { class Player : public GenericActor { public: TYPEDEF_PARENT_CLASS(Engine::GenericActor); Player(); Player(const std::string &texfile, const std::string &texID); Player(const Player &p); virtual ~Player(); virtual void TickUpdate(const double &delta) override; virtual void Render(std::shared_ptr<sf::RenderTarget> Target) override; virtual void OnShutDown() override; virtual void SerializeOut(std::ofstream &out) override; virtual void SerializeIn(std::ifstream &in) override; virtual void KeyRightPressed(); virtual void KeyUpPressed(); virtual void KeyDownPressed(); virtual void KeyLeftPressed(); virtual void ForcePosition(float x, float y); virtual float GetPositionX() { return Sprite.getPosition().x; } virtual float GetPositionY() { return Sprite.getPosition().y; } virtual bool WantsInputEvent(const Events &evnt) const override; virtual void MoveTo(const sf::Vector2f &pos); protected: void KeyWasPressed(const sf::Keyboard::Key &k); void KeyWasReleased(const sf::Keyboard::Key &k); void TryToMove(const sf::Vector2f &amount); sf::RectangleShape TestShape; }; } #endif
[ "kurt_slagle@yahoo.com" ]
kurt_slagle@yahoo.com
ae5372a03d8e613e0724fcf4022260304c177928
7fa30033e7338ae66464a9862d5375121619e62f
/pointerpractice.cpp
b5aac73a31697b5fbaf84714daba9e77de58c020
[]
no_license
nick82632/Practice_Code
984c23ce5e46fb598b64a7d83f6ce0313b794515
eb7e6e447ff45b4aed5bea852cbb92a6c247d000
refs/heads/master
2022-12-19T13:45:56.320660
2020-09-26T08:08:04
2020-09-26T08:08:04
209,308,874
0
0
null
null
null
null
UTF-8
C++
false
false
1,122
cpp
#include <iostream> #include <typeinfo> int main() { const int i = 42; auto j = i; const auto &k = i; auto *p = &i; const auto j2 = i, &k2 = i; std::cout << "i is " << typeid(i).name() << "\n"; std::cout << "j is " << typeid(j).name() << "\n"; std::cout << "k is " << typeid(k).name() << "\n"; std::cout << "p is " << typeid(p).name() << "\n"; std::cout << "j2 is " << typeid(j2).name() << "\n"; std::cout << "k2 is " << typeid(k2).name() << "\n"; std::cout << std::endl; std::cout << std::boolalpha; std::cout << "i and j have same type? " << std::is_same<decltype(i), decltype(j)>::value << "\n"; std::cout << "i and k have same type? " << std::is_same<decltype(i), decltype(k)>::value << "\n"; std::cout << "i and j2 have same type? " << std::is_same<decltype(i), decltype(j2)>::value << "\n"; std::cout << "j and j2 have same type? " << std::is_same<decltype(j), decltype(j2)>::value << "\n"; std::cout << "k and k2 have same type? " << std::is_same<decltype(k), decltype(k2)>::value << "\n"; return 0; }
[ "noreply@github.com" ]
nick82632.noreply@github.com
d589ad51b809577eafea781ab7fbc37c46cb1096
f1bdc307a5f545efa3097ca62d7c5b8d84722f3a
/clase pila.cpp
a7937d89f66f73f60ce53ee09fbac211510ed6c1
[]
no_license
camilo11/AutoPila
1fb5e045a4154597b999c164ebd726b5dbd11e68
769288b34a21b8faddd6fac004056383e5e74190
refs/heads/master
2021-07-10T10:08:20.776244
2017-10-11T23:07:10
2017-10-11T23:07:10
105,074,545
0
0
null
null
null
null
UTF-8
C++
false
false
995
cpp
using namespace std; struct nodo{ char a;//campo donde se almacenara el caracter struct nodo *sgte; }; typedef struct nodo *Puntero; class Pila{ public: Pila(void); void Apilar(char ); int Desapilar(void ); bool PilaVacia(void); void MostrarPila(void); private: Puntero cima; }; Pila::Pila(void){ cima=""; } void Pila::Apilar(char x){ Puntero aux; aux=new(struct nodo); aux->a=x; aux->sgte=cima; cima=aux; } int Pila::Desapilar(void){ char x; Puntero aux; if(cima=="") cout<<"\n\n\tPila Vacia...!!"; else{ aux=cima; x=aux->a; cima=cima->sgte; delete(aux); } return x; } bool Pila::PilaVacia(void){ if(cima=="") return true; else return false; } void Pila::MostrarPila(void){ Puntero aux; aux=cima; while(aux!=""){ cout<<"\t "<<aux->a<<endl; aux=aux->sgte; } }
[ "noreply@github.com" ]
camilo11.noreply@github.com
1f8a5599a13b636f004b9d2e7c5bf0b7be268cf7
0688ed4fbbbd19613cc453c568af75ba59ae5144
/libraries/mojingsdk/src/main/cpp/Base/MojingAllocator.h
d075b1d3e9e072744316e6a8b3e9fbae4dd23835
[]
no_license
playbar/testplayer
49c068e53a5b93768b4d46f4f9b8d2bb739ff7fe
b4869ed9193739ab48c067cd51b4f5084943e924
refs/heads/master
2021-05-07T03:37:09.438661
2017-11-20T03:38:59
2017-11-20T03:38:59
110,958,488
3
0
null
null
null
null
UTF-8
C++
false
false
12,059
h
#ifndef MJ_Allocator_h #define MJ_Allocator_h #include "MojingTypes.h" #include <pthread.h>// pthread_mutex_ XXXX #include <map> using namespace std; //----------------------------------------------------------------------------------- // ***** Disable template-unfriendly MS VC++ warnings #if defined(MJ_CC_MSVC) // Pragma to prevent long name warnings in in VC++ #pragma warning(disable : 4503) #pragma warning(disable : 4786) // In MSVC 7.1, warning about placement new POD default initializer #pragma warning(disable : 4345) #endif // Un-define new so that placement constructors work #undef new //----------------------------------------------------------------------------------- // ***** Placement new overrides // Calls constructor on own memory created with "new(ptr) type" #ifndef __PLACEMENT_NEW_INLINE #define __PLACEMENT_NEW_INLINE # if defined(MJ_CC_MWERKS) || defined(MJ_CC_BORLAND) || defined(MJ_CC_GNU) # include <new> # else // Useful on MSVC MJ_FORCE_INLINE void* operator new (UPInt n, void *ptr) { MJ_UNUSED(n); return ptr; } MJ_FORCE_INLINE void operator delete (void *, void *) { } # endif #endif // __PLACEMENT_NEW_INLINE //------------------------------------------------------------------------ // ***** Macros to redefine class new/delete operators // Types specifically declared to allow disambiguation of address in // class member operator new. #define MJ_MEMORY_REDEFINE_NEW_IMPL(class_name, check_delete) \ void* operator new(UPInt sz) \ { void *p = MJ_ALLOC_DEBUG(sz, __FILE__, __LINE__); return p; } \ void* operator new(UPInt sz, const char* file, int line) \ { void* p = MJ_ALLOC_DEBUG(sz, file, line); MJ_UNUSED2(file, line); return p; } \ void operator delete(void *p) \ { check_delete(class_name, p); MJ_FREE(p); } \ void operator delete(void *p, const char*, int) \ { check_delete(class_name, p); MJ_FREE(p); } #define MJ_MEMORY_DEFINE_PLACEMENT_NEW \ void* operator new (UPInt n, void *ptr){ MJ_UNUSED(n); return ptr; } \ void operator delete (void *ptr, void *ptr2) { MJ_UNUSED2(ptr, ptr2); } #define MJ_MEMORY_CHECK_DELETE_NONE(class_name, p) // Redefined all delete/new operators in a class without custom memory initialization #define MJ_MEMORY_REDEFINE_NEW(class_name) \ MJ_MEMORY_REDEFINE_NEW_IMPL(class_name, MJ_MEMORY_CHECK_DELETE_NONE) namespace Baofeng { //----------------------------------------------------------------------------------- // ***** Construct / Destruct // Construct/Destruct functions are useful when new is redefined, as they can // be called instead of placement new constructors. template <class T> MJ_FORCE_INLINE T* Construct(void *p) { return ::new(p)T; } template <class T> MJ_FORCE_INLINE T* Construct(void *p, const T& source) { return ::new(p)T(source); } // Same as above, but allows for a different type of constructor. template <class T, class S> MJ_FORCE_INLINE T* ConstructAlt(void *p, const S& source) { return ::new(p)T(source); } template <class T, class S1, class S2> MJ_FORCE_INLINE T* ConstructAlt(void *p, const S1& src1, const S2& src2) { return ::new(p)T(src1, src2); } template <class T> MJ_FORCE_INLINE void ConstructArray(void *p, UPInt count) { UByte *pdata = (UByte*)p; for (UPInt i = 0; i < count; ++i, pdata += sizeof(T)) { Construct<T>(pdata); } } template <class T> MJ_FORCE_INLINE void ConstructArray(void *p, UPInt count, const T& source) { UByte *pdata = (UByte*)p; for (UPInt i = 0; i < count; ++i, pdata += sizeof(T)) { Construct<T>(pdata, source); } } template <class T> MJ_FORCE_INLINE void Destruct(T *pobj) { pobj->~T(); MJ_UNUSED1(pobj); // Fix incorrect 'unused variable' MSVC warning. } template <class T> MJ_FORCE_INLINE void DestructArray(T *pobj, UPInt count) { for (UPInt i = 0; i < count; ++i, ++pobj) pobj->~T(); } namespace Mojing { //----------------------------------------------------------------------------------- // ***** Allocator // Allocator defines a memory allocation interface that developers can override // to to provide memory for OVR; an instance of this class is typically created on // application startup and passed into System or OVR::System constructor. // // // Users implementing this interface must provide three functions: Alloc, Free, // and Realloc. Implementations of these functions must honor the requested alignment. // Although arbitrary alignment requests are possible, requested alignment will // typically be small, such as 16 bytes or less. class Allocator { friend class System; public: // *** Standard Alignment Alloc/Free // Allocate memory of specified size with default alignment. // Alloc of size==0 will allocate a tiny block & return a valid pointer; // this makes it suitable for new operator. virtual void* Alloc(UPInt size) = 0; // Same as Alloc, but provides an option of passing debug data. virtual void* AllocDebug(UPInt size, const char* file, unsigned line) { MJ_UNUSED2(file, line); return Alloc(size); } // Reallocate memory block to a new size, copying data if necessary. Returns the pointer to // new memory block, which may be the same as original pointer. Will return 0 if reallocation // failed, in which case previous memory is still valid. // Realloc to decrease size will never fail. // Realloc of pointer == 0 is equivalent to Alloc // Realloc to size == 0, shrinks to the minimal size, pointer remains valid and requires Free(). virtual void* Realloc(void* p, UPInt newSize) = 0; virtual void* ReallocDebug(void* p, UPInt newSize) = 0; // Frees memory allocated by Alloc/Realloc. // Free of null pointer is valid and will do nothing. virtual void Free(void *p) = 0; virtual void FreeDebug(void *p) = 0; // *** Standard Alignment Alloc/Free // Allocate memory of specified alignment. // Memory allocated with AllocAligned MUST be freed with FreeAligned. // Default implementation will delegate to Alloc/Free after doing rounding. virtual void* AllocAligned(UPInt size, UPInt align); // Frees memory allocated with AllocAligned. virtual void FreeAligned(void* p); // Returns the pointer to the current globally installed Allocator instance. // This pointer is used for most of the memory allocations. static Allocator* GetInstance() { return pInstance; } protected: // onSystemShutdown is called on the allocator during System::Shutdown. // At this point, all allocations should've been freed. virtual void onSystemShutdown() { } public: static void setInstance(Allocator* palloc) { MJ_ASSERT((pInstance == 0) || (palloc == 0)); pInstance = palloc; } private: static Allocator* pInstance; }; //------------------------------------------------------------------------ // ***** Allocator_SingletonSupport // Allocator_SingletonSupport is a Allocator wrapper class that implements // the InitSystemSingleton static function, used to create a global singleton // used for the OVR::System default argument initialization. // // End users implementing custom Allocator interface don't need to make use of this base // class; they can just create an instance of their own class on stack and pass it to System. template<class D> class Allocator_SingletonSupport : public Allocator { struct AllocContainer { UPInt Data[(sizeof(D)+sizeof(UPInt)-1) / sizeof(UPInt)]; bool Initialized; AllocContainer() : Initialized(0) { } }; AllocContainer* pContainer; public: Allocator_SingletonSupport() : pContainer(0) { } // Creates a singleton instance of this Allocator class used // on MJ_DEFAULT_ALLOCATOR during System initialization. static D* InitSystemSingleton() { static AllocContainer Container; MJ_ASSERT(Container.Initialized == false); Allocator_SingletonSupport<D> *presult = Construct<D>((void*)Container.Data); presult->pContainer = &Container; Container.Initialized = true; return (D*)presult; } protected: virtual void onSystemShutdown() { Allocator::onSystemShutdown(); if (pContainer) { pContainer->Initialized = false; Destruct((D*)this); pContainer = 0; } } }; //------------------------------------------------------------------------ // ***** Default Allocator // This allocator is created and used if no other allocator is installed. // Default allocator delegates to system malloc. struct MemMutex { MemMutex() { pthread_mutex_init(&mtx, NULL); } ~MemMutex() { pthread_mutex_destroy(&mtx); } inline void lock() { pthread_mutex_lock(&mtx); } inline void unlock() { pthread_mutex_unlock(&mtx); } pthread_mutex_t mtx; }; struct __tagAllocatorInfo { char * m_pszFile; int m_iLine; int m_iSize; int m_iAllocSize; unsigned char *m_pPosition; }; class DefaultAllocator : public Allocator_SingletonSupport<DefaultAllocator> { MemMutex m_AllocTableLock; map<void *, __tagAllocatorInfo> m_AllocTable; void BeforeMapOP(){ m_AllocTableLock.lock(); }; void AfterMapOP(){ m_AllocTableLock.unlock(); }; public: virtual ~DefaultAllocator(); virtual void* Alloc(UPInt size); virtual void* AllocDebug(UPInt size, const char* file, unsigned line); virtual void* Realloc(void* p, UPInt newSize); virtual void* ReallocDebug(void* p, UPInt newSize); virtual void FreeDebug(void *p); virtual void Free(void *p); }; //------------------------------------------------------------------------ // ***** Memory Allocation Macros // These macros should be used for global allocation. In the future, these // macros will allows allocation to be extended with debug file/line information // if necessary. #define MJ_ALLOC_ALIGNED(s,a) Baofeng::Mojing::Allocator::GetInstance()->AllocAligned((s),(a)) #define MJ_FREE_ALIGNED(p) Baofeng::Mojing::Allocator::GetInstance()->FreeAligned((p)) //#if defined( MJ_BUILD_DEBUG) || defined(_DEBUG) //#define MJ_ALLOC(s) Baofeng::Mojing::Allocator::GetInstance()->AllocDebug((s), __FILE__, __LINE__) //#define MJ_ALLOC_DEBUG(s,f,l) Baofeng::Mojing::Allocator::GetInstance()->AllocDebug((s), f, l) //#define MJ_FREE(p) Baofeng::Mojing::Allocator::GetInstance()->FreeDebug((p)) //#define MJ_REALLOC(p,s) Baofeng::Mojing::Allocator::GetInstance()->ReallocDebug((p),(s)) //#else #define MJ_ALLOC(s) Baofeng::Mojing::Allocator::GetInstance()->Alloc((s)) #define MJ_ALLOC_DEBUG(s,f,l) Baofeng::Mojing::Allocator::GetInstance()->Alloc((s)) #define MJ_FREE(p) Baofeng::Mojing::Allocator::GetInstance()->Free((p)) #define MJ_REALLOC(p,s) Baofeng::Mojing::Allocator::GetInstance()->Realloc((p),(s)) //#endif //------------------------------------------------------------------------ // Base class that overrides the new and delete operators. // Deriving from this class, even as a multiple base, incurs no space overhead. class NewOverrideBase { public: // Redefine all new & delete operators. MJ_MEMORY_REDEFINE_NEW(NewOverrideBase) }; } } // Redefine operator 'new' if necessary. #if defined(MJ_DEFINE_NEW) #define new MJ_DEFINE_NEW #endif #endif // MJ_Memory
[ "hgl868@126.com" ]
hgl868@126.com
867e3b8ba71cf71016ca8669fa7d29c7dea353d0
31adbc5f508fd9585931022fd46d65f29533a851
/DynamicPointPaths.cpp
18a06a6bc694d3a22d800a4808e05161640badb3
[]
no_license
Tape09/aimasa2
b51314121b4de02bc7b8d71c0c5ed74d5d275c49
db30bf60e6dbb7b2f1678e7ea2d7e371b425595f
refs/heads/master
2021-01-20T15:19:19.629180
2017-03-25T01:46:08
2017-03-25T01:46:08
82,805,435
0
0
null
null
null
null
UTF-8
C++
false
false
17,167
cpp
// Fill out your copyright notice in the Description page of Project Settings. #include "aimasa2.h" #include "DynamicPointPaths.h" DynamicPointPaths::DynamicPointPaths(FVector pos0_, FVector vel0_, FVector pos1_, FVector vel1_, float v_max_, float phi_max_, float L_car_, float a_max_) { pos0 = pos0_; pos1 = pos1_; vel0 = vel0_; vel1 = vel1_; v_max = v_max_; phi_max = phi_max_; L_car = L_car_; a_max = a_max_; turn_radius = L_car / tan(phi_max); //turn_radius = 2; //print_log(FString::SanitizeFloat(turn_radius)); //print_log(FString::SanitizeFloat(phi_max)); RSState goal_state((pos1 - pos0) / turn_radius, wrapAngle(vecAngle(vel1) - vecAngle(vel0))); rotateVector(goal_state.pos, -vecAngle(vel0)); //goal_state.pos = goal_state.pos.RotateAngleAxis(rad2deg(-vecAngle(vel0)),FVector(0,0,1)); //print_log(goal_state.pos.ToString()); //print_log(FString::SanitizeFloat(goal_state.theta)); addTransforms(std::bind(&DynamicPointPaths::get_path_LSL, this, std::placeholders::_1), goal_state); addTransforms(std::bind(&DynamicPointPaths::get_path_LSR, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LGRGL, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LGRL, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LRGL, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LRGLR, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LGRLGR, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LGR90SL, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LSR90GL, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LGR90SR, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LSL90GR, this, std::placeholders::_1), goal_state); //addTransforms(std::bind(&DynamicPointPaths::get_path_LGR90SL90GR, this, std::placeholders::_1), goal_state); std::sort(all_paths.begin(), all_paths.end()); if (all_paths.size() == 0) exists = false; path_index = 0; } DynamicPointPaths::~DynamicPointPaths() {} float DynamicPointPaths::time_taken(int idx) { return turn_radius * all_paths[idx].calc_dist() / v_max; } float DynamicPointPaths::time_taken() { return turn_radius * all_paths[0].calc_dist() / v_max; } State DynamicPointPaths::state_at(RSPath rsp, float time) const { //print_log("time: " + FString::SanitizeFloat(time)); float d = rsp.dist_at(time); //int idx = rsp.get_rsc_idx(time); //print_log("dist: " + FString::SanitizeFloat(d)); //print_log("time: " + FString::SanitizeFloat(time)); //print_log("dist: " + FString::SanitizeFloat(rsp.ais.back().p3)); //print_log("tim: " + FString::SanitizeFloat(rsp.time)); State istate; istate.pos = pos0; istate.vel = vel0; //print_log(istate); //print_log(FString::SanitizeFloat(rsp.dist)); //print_log(FString::SanitizeFloat(rsp.dist*turn_radius)); //print_log(rsp.word()); for (int i = 1; i<rsp.dists.size(); ++i) { //print_log(FString::SanitizeFloat(rsp.dists[i])); if (d <= rsp.dists[i] * turn_radius) { return state_at(istate, rsp.components[i - 1], (d - rsp.dists[i - 1] * turn_radius)); } else { istate = state_at(istate, rsp.components[i - 1], rsp.components[i - 1].dist*turn_radius); } //print_log(istate); } return istate; } State DynamicPointPaths::state_at(State istate, RSComponent rsc, float dist) const { State s; if (rsc.turn == L) { s = drive_L(istate, rsc, dist); } else if (rsc.turn == R) { s = drive_R(istate, rsc, dist); } else { s = drive_S(istate, rsc, dist); } return s; } State DynamicPointPaths::drive_R(State istate, RSComponent rsc, float dist) const { State s; float theta0 = vecAngle(istate.vel); float theta = rsc.gear * dist / turn_radius; float LL = 2 * sin(theta / 2) * turn_radius; s.pos.X = LL * cos(theta / 2); s.pos.Y = -LL * sin(theta / 2); s.vel = istate.vel; rotateVector(s.vel, -theta); s.acc = FVector(0, turn_radius, 0) - s.pos; rotateVector(s.pos, theta0); rotateVector(s.acc, theta0); s.vel.Normalize(); s.vel = s.vel * v_max; s.pos = s.pos + istate.pos; return s; } State DynamicPointPaths::drive_L(State istate, RSComponent rsc, float dist) const { State s; float theta0 = vecAngle(istate.vel); float theta = rsc.gear * dist / turn_radius; float LL = 2 * sin(theta / 2) * turn_radius; s.pos.X = LL * cos(theta / 2); s.pos.Y = LL * sin(theta / 2); s.vel = istate.vel; rotateVector(s.vel, theta); s.acc = FVector(0, turn_radius, 0) - s.pos; rotateVector(s.pos, theta0); rotateVector(s.acc, theta0); s.vel.Normalize(); s.vel = s.vel * v_max; s.pos = s.pos + istate.pos; return s; } State DynamicPointPaths::drive_S(State istate, RSComponent rsc, float dist) const { State s; float theta0 = vecAngle(istate.vel); dist = rsc.gear * dist; s.pos.X = dist*cos(theta0) + istate.pos.X; s.pos.Y = dist*sin(theta0) + istate.pos.Y; s.vel = istate.vel; s.acc = FVector(0, 0, 0); return s; } State DynamicPointPaths::state_at(int idx, float time) const { return state_at(all_paths[idx], time); } int DynamicPointPaths::n_paths() const { return all_paths.size(); } float DynamicPointPaths::theta(float t) const { return v_max*t / turn_radius; } State DynamicPointPaths::step(float delta_time) { t_now += delta_time; return state_at(t_now); } State DynamicPointPaths::state_at(float t) { return state_at(path_index, t); } //1: 8.1 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LSL(const RSState & goal) { float t = 0; float u = 0; float v = 0; float x = goal.pos.X - sin(goal.theta); float y = goal.pos.Y - 1 + cos(goal.theta); t = atan2(y, x); u = sqrt(x * x + y * y); v = wrapAngle(goal.theta - t); RSPath out_path; out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(S, 1, u)); out_path.components.push_back(RSComponent(L, 1, v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //2: 8.2 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LSR(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float x = goal.pos.X + sin(goal.theta); float y = goal.pos.Y - 1 - cos(goal.theta); float u1_2 = x * x + y * y; float t1 = atan2(y, x); if (u1_2 < 4) { out_path.is_valid = false; return out_path; } u = sqrt(u1_2 - 4); t = wrapAngle(t1 + atan2(2, u)); v = wrapAngle(t - goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(S, 1, u)); out_path.components.push_back(RSComponent(R, 1, v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //3: 8.3 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LGRGL(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X - sin(goal.theta); float eta = goal.pos.Y - 1 + cos(goal.theta); float u1 = sqrt(xi * xi + eta * eta); //print_log(FString::SanitizeFloat(u1)); if (u1 > 4) { out_path.is_valid = false; return out_path; } float alpha = acos(u1 / 4); t = mod2pi(pii / 2 + alpha + atan2(eta, xi)); u = mod2pi(pii - 2 * alpha); v = mod2pi(goal.theta - t - u); // if (isInvalidAngle(t) || isInvalidAngle(u) || isInvalidAngle(v)) // return float.PositiveInfinity; // return t + u + v; out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, -1, -u)); out_path.components.push_back(RSComponent(L, 1, v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //4: 8.4 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LGRL(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X - sin(goal.theta); float eta = goal.pos.Y - 1 + cos(goal.theta); float u1 = sqrt(xi * xi + eta * eta); if (u1 > 4) { out_path.is_valid = false; return out_path; } float alpha = acos(u1 / 4); t = mod2pi(pii / 2 + alpha + atan2(eta, xi)); u = mod2pi(pii - 2 * alpha); v = mod2pi(t + u - goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, -1, -u)); out_path.components.push_back(RSComponent(L, -1, -v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //5: 8.4 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LRGL(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X - sin(goal.theta); float eta = goal.pos.Y - 1 + cos(goal.theta); float u1 = sqrt(xi * xi + eta * eta); if (u1 > 4) { out_path.is_valid = false; return out_path; } u = acos((8 - u1 * u1) / 8); float va = sin(u); float vb = 2 * va / u1; if (abs(vb) > 1) { out_path.is_valid = false; return out_path; } float alpha = asin(vb); t = mod2pi(pii / 2 - alpha + atan2(eta, xi)); v = mod2pi(t - u - goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, 1, u)); out_path.components.push_back(RSComponent(L, -1, -v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //6: 8.7 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LRGLR(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X + sin(goal.theta); float eta = goal.pos.Y - 1 - cos(goal.theta); float u1 = sqrt(xi * xi + eta * eta); if (u1 > 4) { out_path.is_valid = false; return out_path; } float phii = atan2(eta, xi); if (u1 > 2) { float alpha = acos(u1 / 4 - 0.5); t = mod2pi(pii / 2 + phii - alpha); u = mod2pi(pii - alpha); v = mod2pi(goal.theta - t + 2 * u); } else { float alpha = acos(u1 / 4 + 0.5); t = mod2pi(pii / 2 + phii + alpha); u = mod2pi(alpha); v = mod2pi(goal.theta - t + 2 * u); } out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, 1, u)); out_path.components.push_back(RSComponent(L, -1, -u)); out_path.components.push_back(RSComponent(R, -1, -v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //7: 8.8 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LGRLGR(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X + sin(goal.theta); float eta = goal.pos.Y - 1 - cos(goal.theta); float u1 = sqrt(xi * xi + eta * eta); if (u1 > 6) { out_path.is_valid = false; return out_path; } float va1 = 1.25f - u1 * u1 / 16; if (va1 < 0 || va1 > 1) { out_path.is_valid = false; return out_path; } u = acos(va1); float va2 = sin(u); float va3 = 2 * va2 / u1; if (abs(va3) > 1) { out_path.is_valid = false; return out_path; } float alpha = asin(va3); t = mod2pi(pii / 2 + atan2(eta, xi) + alpha); v = mod2pi(t - goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, -1, -u)); out_path.components.push_back(RSComponent(L, -1, -u)); out_path.components.push_back(RSComponent(R, 1, v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //8: 8.9 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LGR90SL(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X - sin(goal.theta); float eta = goal.pos.Y - 1 + cos(goal.theta); float u1_s = xi * xi + eta * eta; if (u1_s < 4) { out_path.is_valid = false; return out_path; } u = sqrt(u1_s - 4) - 2; if (u < 0) { out_path.is_valid = false; return out_path; } float alpha = atan2(2, u + 2); t = mod2pi(pii / 2 + atan2(eta, xi) + alpha); v = mod2pi(t + pii / 2 - goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, -1, -pii / 2)); out_path.components.push_back(RSComponent(S, -1, -u)); out_path.components.push_back(RSComponent(L, -1, -v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //9: 8.9 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LSR90GL(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X - sin(goal.theta); float eta = goal.pos.Y - 1 + cos(goal.theta); float u1_s = xi * xi + eta * eta; if (u1_s < 4) { out_path.is_valid = false; return out_path; } u = sqrt(u1_s - 4) - 2; if (u < 0) { out_path.is_valid = false; return out_path; } float alpha = atan2(u + 2, 2); t = mod2pi(pii / 2 + atan2(eta, xi) - alpha); v = mod2pi(t - pii / 2 - goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(S, 1, u)); out_path.components.push_back(RSComponent(R, 1, pii / 2)); out_path.components.push_back(RSComponent(L, -1, -v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //10: 8.10 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LGR90SR(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X + sin(goal.theta); float eta = goal.pos.Y - 1 - cos(goal.theta); float u1 = sqrt(xi * xi + eta * eta); if (u1 < 2) { out_path.is_valid = false; return out_path; } t = mod2pi(pii / 2 + atan2(eta, xi)); u = u1 - 2; v = mod2pi(goal.theta - t - pii / 2); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, -1, -pii / 2)); out_path.components.push_back(RSComponent(S, -1, -u)); out_path.components.push_back(RSComponent(R, -1, -v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //11: 8.10 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LSL90GR(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X + sin(goal.theta); float eta = goal.pos.Y - 1 - cos(goal.theta); float u1 = sqrt(xi * xi + eta * eta); if (u1 < 2) { out_path.is_valid = false; return out_path; } t = mod2pi(atan2(eta, xi)); u = u1 - 2; v = mod2pi(-t - pii / 2 + goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(S, 1, u)); out_path.components.push_back(RSComponent(L, 1, pii / 2)); out_path.components.push_back(RSComponent(R, -1, -v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } //12: 8.11 DynamicPointPaths::RSPath DynamicPointPaths::get_path_LGR90SL90GR(const RSState & goal) { RSPath out_path; float t = 0; float u = 0; float v = 0; float xi = goal.pos.X + sin(goal.theta); float eta = goal.pos.Y - 1 - cos(goal.theta); float u1_s = xi * xi + eta * eta; if (u1_s < 4) { // <16 out_path.is_valid = false; return out_path; } u = sqrt(u1_s - 4) - 4; if (u < 0) { out_path.is_valid = false; return out_path; } float alpha = atan2(2, u + 4); t = mod2pi(pii / 2 + atan2(eta, xi) + alpha); v = mod2pi(t - goal.theta); out_path.components.push_back(RSComponent(L, 1, t)); out_path.components.push_back(RSComponent(R, -1, -pii / 2)); out_path.components.push_back(RSComponent(S, -1, -u)); out_path.components.push_back(RSComponent(L, -1, -pii / 2)); out_path.components.push_back(RSComponent(R, 1, v)); out_path.is_valid = true; out_path.calc_dist(); out_path.calc_time(vel0.Size(), vel1.Size(), turn_radius, v_max, a_max); return out_path; } void DynamicPointPaths::addTransforms(pathFcn fptr, const RSState & goal) { RSPath rsp; RSState rs; rs = goal; rsp = fptr(rs); if (rsp.is_valid) { all_paths.push_back(rsp); } //rs = goal; //rs.reverse(); //rsp = fptr(rs); //rsp.reverse(); //if (rsp.is_valid) { // all_paths.push_back(rsp); //} rs = goal; rs.reflect(); rsp = fptr(rs); rsp.reflect(); if (rsp.is_valid) { all_paths.push_back(rsp); } //rs = goal; //rs.reverse(); //rs.reflect(); //rsp = fptr(rs); //rsp.reverse(); //rsp.reflect(); //if (rsp.is_valid) { // all_paths.push_back(rsp); //} } float DynamicPointPaths::path_time(int idx) const { return all_paths[idx].time; } float DynamicPointPaths::path_time() const { return all_paths[path_index].time; }
[ "tapeworm09@hotmail.com" ]
tapeworm09@hotmail.com
d7d40693971e4d5efdfcbaa532c2ad932df32aa7
2f89b19631984f8fe47f8e1468668865583bfb85
/ABC/■100/71-80/ABC_077/ABC077_B.cpp
e4aa96ff92a8a5a02469484feb8683f02f1b47e8
[]
no_license
masakinihirota/2019pg
29e6ded7a043d0e061c714feeebf9439d171bbc3
0d7e3fda329bf610de19e6e019ca0ea2954b3155
refs/heads/master
2020-09-22T11:30:05.244365
2020-01-13T01:46:17
2020-01-13T01:46:17
225,169,649
0
0
null
null
null
null
UTF-8
C++
false
false
1,101
cpp
#include <bits/stdc++.h> using namespace std; using ll = long long; #define ld long double #define ull unsigned long long int #define rep(i, n) for (int i = 0; i < (int)(n); i++) // (i, 10) i=0~i=9まで #define repr(i, n) for (int i = n; i >= 0; i--) // (i, 10) i=10~i=0まで #define FOR(i, m, n) for (int i = m; i < n; i++) // (i, 3, 10) i=3~i=9まで #define SORT(v, n) sort(v, v + n); #define VSORT(v) sort(v.begin(), v.end()); #define all(x) (x).begin(), (x).end() #define rall(x) (x).rbegin(), (x).rend() #define sz(x) ((int)(x).size()) #define pb push_back #define ret return typedef pair<int, int> pii; typedef vector<int> vi; typedef vector<vi> vii; typedef vector<long long> vl; // 総数を1000000007で割った余り const long long mod = 1e9 + 7; #define EPS (1e-7) #define INF (1e9) #define PI (acos(-1)) int main() { // cin.tie(0); // ios::sync_with_stdio(false); // cout << fixed << setprecision(5); // 入力 int n; cin >> n; int num = sqrt(n); // 処理 // 出力 cout << num * num << endl; return 0; }
[ "masakinihirota@gmail.com" ]
masakinihirota@gmail.com
caf4df208c7fcb92cca1f97d2d2f5608d39d1196
1a45d284d29ee041f5dae9693a318264bebe3513
/idastarsolver.h
80914c0912c3c87092d84dd04152eee7dc79fc1f
[]
no_license
KsaneK/QtPuzzleGame
ad99c961d99a208fb25ad4431d46bc3eaa07f7dd
d5dc1fe61a7f9676a80209bc66212231f28acee3
refs/heads/master
2023-04-04T04:33:44.372526
2021-04-16T14:33:23
2021-04-16T14:33:23
339,517,379
0
0
null
null
null
null
UTF-8
C++
false
false
1,040
h
#ifndef IDASTARSOLVER_H #define IDASTARSOLVER_H #include "solver.h" #include <vector> #include <chrono> struct TimeoutException : public std::exception { const char * what () const throw () { return "Nie udało się znaleźć rozwiązanie w przeciągu 10 sekund"; } }; class IDAStarSolver : public Solver { public: IDAStarSolver(); std::vector<int> solve(std::vector<int> vals); private: std::chrono::time_point<std::chrono::high_resolution_clock> solve_start_timestamp; std::unordered_map<long long int, int> WDTABLE; int bits; int directions[4][2] = {{-1,0}, {1,0}, {0,-1}, {0,1}}; int size; int manhattan_dist(const char* vals) const; static void swap(char *arr, int p1, int p2); int dfs(char *state, std::vector<int> *path, int cost, int bound, int hole); bool isGoal(const char *state) const; void genWDTable(int size); unsigned long long encode(const char *state, int boardSize); int walking_dist(const char *state) const; }; #endif // IDASTARSOLVER_H
[ "xaneqtv@gmail.com" ]
xaneqtv@gmail.com
9003f3363285818e28b192e75baa6730f78ebb98
4cf6f78ee72ac34eb0ba79f27a6b2a530881f435
/Core/Input.cpp
04a054497302e6fc6b63cba71c84c825c93a6f9d
[]
no_license
TVChatten/SavePrybist
33dedaf64f2fd85edc20bf583073d91bdf740370
f17478f801c7e4aa44f0be5429f5b7d480d8fd4a
refs/heads/master
2020-04-22T02:10:18.445591
2019-02-10T23:34:16
2019-02-10T23:34:16
170,035,405
0
0
null
null
null
null
UTF-8
C++
false
false
1,962
cpp
#include "Input.h" void Input::init() { Uint8* keyboard = SDL_GetKeyState(&numKeys); keys = new bool[numKeys]; prevKeys = new bool[numKeys]; for(int i = 0; i < numKeys; i++) { keys[i] = keyboard[i]; prevKeys[i] = false; } SDL_GetMouseState(&mouseX, &mouseY); for(int i = 1; i <= 3; i++) { mouseKeys[i] = SDL_GetMouseState(NULL,NULL) & SDL_BUTTON(i); prevMouseKeys[i] = false; } } void Input::kill() { delete[] keys; delete[] prevKeys; } void Input::update() { Uint8* keyboard = SDL_GetKeyState(&numKeys); for(int i = 0; i < numKeys; i++) { prevKeys[i] = keys[i]; keys[i] = keyboard[i]; } SDL_GetMouseState(&mouseX, &mouseY); for(int i = 1; i <= 3; i++) { prevMouseKeys[i] = mouseKeys[i]; mouseKeys[i] = SDL_GetMouseState(NULL,NULL) & SDL_BUTTON(i); } } bool Input::keyDown(int key) { if(key < 0 || key > numKeys) return false; return keys[key]; } bool Input::keyHit(int key) { if(key < 0 || key > numKeys) return false; return (keys[key] && !prevKeys[key]); } bool Input::keyUp(int key) { if(key < 0 || key > numKeys) return false; return (prevKeys[key] && !keys[key]); } bool Input::mouseDown(int key) { if(key < 0 || key > 3) return false; return mouseKeys[key]; } bool Input::mouseHit(int key) { if(key < 0 || key > 3) return false; return (mouseKeys[key] && !prevMouseKeys[key]); } bool Input::mouseUp(int key) { if(key < 0 || key > 3) return false; return (prevMouseKeys[key] && !mouseKeys[key]); } int Input::getMouseX() { return mouseX; } int Input::getMouseY() { return mouseY; } void Input::setMousePos(int x, int y) { SDL_WarpMouse(x,y); } void Input::hideCursor(bool hide) { if(hide) SDL_ShowCursor(SDL_DISABLE); else SDL_ShowCursor(SDL_ENABLE); }
[ "nessa071390@gmail.com" ]
nessa071390@gmail.com
11bfeb48acd17d7179c1174b8e7feb0c42d31601
33b567f6828bbb06c22a6fdf903448bbe3b78a4f
/opencascade/OpenGl_GraphicDriverFactory.hxx
aede5bd28991ff9fc5554d98b4116d1a9fbe2553
[ "Apache-2.0" ]
permissive
CadQuery/OCP
fbee9663df7ae2c948af66a650808079575112b5
b5cb181491c9900a40de86368006c73f169c0340
refs/heads/master
2023-07-10T18:35:44.225848
2023-06-12T18:09:07
2023-06-12T18:09:07
228,692,262
64
28
Apache-2.0
2023-09-11T12:40:09
2019-12-17T20:02:11
C++
UTF-8
C++
false
false
1,628
hxx
// Copyright (c) 2021 OPEN CASCADE SAS // // This file is part of Open CASCADE Technology software library. // // This library is free software; you can redistribute it and/or modify it under // the terms of the GNU Lesser General Public License version 2.1 as published // by the Free Software Foundation, with special exception defined in the file // OCCT_LGPL_EXCEPTION.txt. Consult the file LICENSE_LGPL_21.txt included in OCCT // distribution for complete text of the license and disclaimer of any warranty. // // Alternatively, this file may be used under the terms of Open CASCADE // commercial license or contractual agreement. #ifndef _OpenGl_GraphicDriverFactory_Header #define _OpenGl_GraphicDriverFactory_Header #include <Graphic3d_GraphicDriverFactory.hxx> #include <OpenGl_Caps.hxx> //! This class for creation of OpenGl_GraphicDriver. class OpenGl_GraphicDriverFactory : public Graphic3d_GraphicDriverFactory { DEFINE_STANDARD_RTTIEXT(OpenGl_GraphicDriverFactory, Graphic3d_GraphicDriverFactory) public: //! Empty constructor. Standard_EXPORT OpenGl_GraphicDriverFactory(); //! Creates new empty graphic driver. Standard_EXPORT virtual Handle(Graphic3d_GraphicDriver) CreateDriver (const Handle(Aspect_DisplayConnection)& theDisp) Standard_OVERRIDE; //! Return default driver options. const Handle(OpenGl_Caps)& DefaultOptions() const { return myDefaultCaps; } //! Set default driver options. void SetDefaultOptions (const Handle(OpenGl_Caps)& theOptions) { myDefaultCaps = theOptions; } protected: Handle(OpenGl_Caps) myDefaultCaps; }; #endif //_OpenGl_GraphicDriverFactory_Header
[ "noreply@github.com" ]
CadQuery.noreply@github.com
31650fbac130fd3595eeafe557216d878cd4de36
75bd815c782d58c808b0257855bc1e8c7655035b
/Arrays/Form_biggest_number.cpp
f81bc099dc9ae0094bae8aa1d79dc1b810cd0f42
[]
no_license
divyanshudob/CodingBlocks-HackerBlocks_Solutions
6fbb77c5d7181b52927a9e30da38043e3c9d74f1
dab9e0058d18c8e0ca337a4537bdabb4d5d6bc4c
refs/heads/main
2023-07-17T22:44:39.668693
2021-08-12T03:02:43
2021-08-12T03:02:43
380,254,907
0
0
null
null
null
null
UTF-8
C++
false
false
480
cpp
#include<bits/stdc++.h> using namespace std; bool comparator(string s1,string s2) { string xy= s1.append(s2); string yx= s2.append(s1); return xy>yx; } int main() { int t; cin>>t; while(t--) { int n; cin>>n; string a[n]; for(int i=0;i<n;i++) { cin>>a[i]; } sort(a,a+n,comparator); for(int i=0;i<n;i++) cout<<a[i]; cout<<endl; } return 0; }
[ "noreply@github.com" ]
divyanshudob.noreply@github.com
cf68bc3f9ac09aa1b68dfaad23a0cba20bcbcbb1
f2d58acf31902d1b8d6e9643e63551adb62140a3
/elbow/63/uniform/functionObjects/functionObjectProperties
972ee6b10b7c6111fa643c71632f5b872b4e1fa9
[]
no_license
maruthiprasanna/OpenFOAMLearning
9858326cc93068cce96702e18d7dc6b5e1972429
13ddba113e66ef21beec155222511f3f7b80e365
refs/heads/main
2023-09-04T13:01:10.180676
2021-10-17T17:10:59
2021-10-17T17:10:59
null
0
0
null
null
null
null
UTF-8
C++
false
false
938
/*--------------------------------*- C++ -*----------------------------------*\ | ========= | | | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox | | \\ / O peration | Version: 2106 | | \\ / A nd | Website: www.openfoam.com | | \\/ M anipulation | | \*---------------------------------------------------------------------------*/ FoamFile { version 2.0; format ascii; arch "LSB;label=32;scalar=64"; class dictionary; location "63/uniform/functionObjects"; object functionObjectProperties; } // * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * // // ************************************************************************* //
[ "maruthi.prasanna3222@gmail.com" ]
maruthi.prasanna3222@gmail.com
d331ff2b4787cc6e4d2895857200af02b0efcc65
afa53fe23d84296c3202ac1329f4ce55020f9e0d
/Source/GameTaskEditor/Private/Node/GameTaskGraphNode_Event.cpp
251245d258d739461c43f63e7520637305de25e0
[]
no_license
977908569/GameTask
70d40f4bc1677be66c20ad0301332e8f8b896741
0cb7a5f97ee1eb0b28596f906c49117f56dcb7c7
refs/heads/main
2023-01-31T23:56:45.499708
2020-12-11T09:52:02
2020-12-11T09:52:02
309,542,809
1
0
null
null
null
null
UTF-8
C++
false
false
1,430
cpp
#include "GameTaskGraphNode_Event.h" #include "GameTaskEvent.h" #define LOCTEXT_NAMESPACE "GameTask" UGameTaskGraphNode_Event::UGameTaskGraphNode_Event(const FObjectInitializer& ObjectInitializer) : Super(ObjectInitializer) { bIsSubNode = true; } FText UGameTaskGraphNode_Event::GetNodeTitle(ENodeTitleType::Type TitleType) const { const UGameTaskEvent* Event = Cast<UGameTaskEvent>(NodeInstance); if (Event) { return FText::FromString(Event->GetNodeName()); } else if (!ClassData.GetClassName().IsEmpty()) { FString StoredClassName = ClassData.GetClassName(); StoredClassName.RemoveFromEnd(TEXT("_C")); return FText::Format(NSLOCTEXT("GameTaskGraph", "NodeClassError", "Class {0} not found, make sure it's saved!"), FText::FromString(StoredClassName)); } return Super::GetNodeTitle(TitleType); } void UGameTaskGraphNode_Event::AllocateDefaultPins() { //No Pins for events } void UGameTaskGraphNode_Event::CollectEventData(TArray<UGameTaskEvent*>& NodeInstances) const { if (NodeInstance) { UGameTaskEvent* EventNode = Cast<UGameTaskEvent>(NodeInstance); check(EventNode); NodeInstances.Add(EventNode); } } FName UGameTaskGraphNode_Event::GetNameIcon() const { if (UGameTaskEvent* EventNode = Cast<UGameTaskEvent>(NodeInstance)) { if (bEnterEvent) return EventNode->GetEnterIconName(); else return EventNode->GetExitIconName(); } return Super::GetNameIcon(); } #undef LOCTEXT_NAMESPACE
[ "977908569@qq.com" ]
977908569@qq.com
38e6e1e5ecfece1a34c6bad67392b36f605dfb0d
022fc9ba04da929835cdab0ae6bfca45cb1da1f8
/UnitTestHcMgr/ConstantEntryTest.cpp
189178dd2f05fd35bf533c085145a74380a68478
[]
no_license
JoaoFelipe/hcmgr
075330989caa0e3eb56c857569057d3a337c3ccb
8e9bf83942a001fcd405cb871d5dae4b93f172e0
refs/heads/master
2021-01-01T18:11:46.137415
2012-12-10T00:59:50
2012-12-10T00:59:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,637
cpp
#include "stdafx.h" #include "CppUnitTest.h" #include <string> #include "..\hcmgr\UnboundEntry.h" #include "..\hcmgr\BoundEntry.h" #include "..\hcmgr\ConstantEntry.h" #include "..\hcmgr\SymbolValueEntry.h" #include "..\hcmgr\PredicateEntry.h" #include "..\hcmgr\SymbolTable.h" #include "..\hcmgr\SubstitutionList.h" #include <iostream> #include <sstream> #include <vector> using namespace std; using namespace Microsoft::VisualStudio::CppUnitTestFramework; namespace UnitTestHcMgr { TEST_CLASS(ConstantEntrylTest) { public: TEST_METHOD(CreateConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(1, entry.value()); } TEST_METHOD(CopyConstantEntry) { ConstantEntry entry(1); ConstantEntry centry(entry); Assert::AreEqual(1, centry.value()); } TEST_METHOD(CloneConstantEntry) { ConstantEntry entry(1); shared_ptr<ConstantEntry> centry = dynamic_pointer_cast<ConstantEntry>(entry.clone()); Assert::AreEqual(1, centry->value()); } TEST_METHOD(GetConstantValueConstantEntry) { ConstantEntry entry(1); shared_ptr<ConstantEntry> centry = dynamic_pointer_cast<ConstantEntry>(entry.get_constant_value()); Assert::AreEqual(1, centry->value()); } TEST_METHOD(EqualOperatorConstantEntry) { ConstantEntry entry1(1); ConstantEntry entry2(1); ConstantEntry entry3(2); BoundEntry entry4(string("a")); SymbolTableEntry & e1 = entry1; SymbolTableEntry & e4 = entry4; Assert::AreEqual(true, entry1 == entry2); Assert::AreEqual(false, entry1 == entry3); Assert::AreEqual(false, e1 == e4); } TEST_METHOD(TypeConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(string("Constant"), entry.type()); } TEST_METHOD(TextConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(string("1"), entry.text()); } TEST_METHOD(IsConstantConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(true, entry.is_constant()); } //SymbolValueEntry TEST_METHOD(IsEvaluableConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(true, entry.is_evaluable()); } //SymbolEntry TEST_METHOD(EqualConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(true, entry.equals("Constant:1")); Assert::AreEqual(false, entry.equals("1")); Assert::AreEqual(false, entry.equals("Bound:1")); } TEST_METHOD(UnificationConstantEntry) { ConstantEntry entry(1); SubstitutionList subst; Assert::AreEqual(string("1"), entry.unification(subst)); } TEST_METHOD(MatchesConstantEntry_Predicate) { shared_ptr<ConstantEntry> entry(new ConstantEntry(1)); SubstitutionList subst; shared_ptr<PredicateEntry> other(new PredicateEntry(string("abs"), vector<shared_ptr<SymbolTableEntry>>())); Assert::AreEqual(false, entry->matches(other, subst)); } TEST_METHOD(MatchesConstantEntry_Unbounds) { shared_ptr<ConstantEntry> entry(new ConstantEntry(1)); shared_ptr<UnboundEntry> other(new UnboundEntry(string("B"))); SubstitutionList subst; Assert::AreEqual(true, entry->matches(other, subst)); } TEST_METHOD(MatchesConstantEntry_Constant) { shared_ptr<ConstantEntry> entry(new ConstantEntry(1)); shared_ptr<ConstantEntry> other(new ConstantEntry(1)); SubstitutionList subst; Assert::AreEqual(true, entry->matches(other, subst)); } TEST_METHOD(MatchesConstantEntry_Bound) { shared_ptr<ConstantEntry> entry(new ConstantEntry(0)); shared_ptr<BoundEntry> other(new BoundEntry(string("a"))); SubstitutionList subst; Assert::AreEqual(true, entry->matches(other, subst)); } TEST_METHOD(MatchesConstantEntry_Constant_Fail) { shared_ptr<ConstantEntry> entry(new ConstantEntry(1)); shared_ptr<ConstantEntry> other(new ConstantEntry(2)); SubstitutionList subst; Assert::AreEqual(false, entry->matches(other, subst)); } TEST_METHOD(MatchesConstantEntry_Bound_Fail) { shared_ptr<ConstantEntry> entry(new ConstantEntry(1)); shared_ptr<BoundEntry> other(new BoundEntry(string("a"))); SubstitutionList subst; Assert::AreEqual(false, entry->matches(other, subst)); } //SymbolTableEntry TEST_METHOD(IsPredicateConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(false, entry.is_predicate()); } TEST_METHOD(IsUnboundConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(false, entry.is_unbound()); } TEST_METHOD(IsBoundConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(false, entry.is_bound()); } TEST_METHOD(IsFunctionConstantEntry) { ConstantEntry entry(1); Assert::AreEqual(false, entry.is_function()); } }; }
[ "joaofelipenp@gmail.com" ]
joaofelipenp@gmail.com
8142ae3504e269f7bf6390cff06bd2d0aecd861c
24004e1c3b8005af26d5890091d3c207427a799e
/Win32/NXOPEN/NXOpen/BlockStyler_CurveCollector.hxx
dd3c1e440a01f8794932982d2a5f823eb33a3cc3
[]
no_license
15831944/PHStart
068ca6f86b736a9cc857d7db391b2f20d2f52ba9
f79280bca2ec7e5f344067ead05f98b7d592ae39
refs/heads/master
2022-02-20T04:07:46.994182
2019-09-29T06:15:37
2019-09-29T06:15:37
null
0
0
null
null
null
null
UTF-8
C++
false
false
16,074
hxx
#ifndef NXOpen_BLOCKSTYLER_CURVECOLLECTOR_HXX_INCLUDED #define NXOpen_BLOCKSTYLER_CURVECOLLECTOR_HXX_INCLUDED //-------------------------------------------------------------------------- // Header for C++ interface to JA API //-------------------------------------------------------------------------- // // Source File: // BlockStyler_CurveCollector.ja // // Generated by: // apiwrap // // WARNING: // This file is automatically generated - do not edit by hand // #ifdef _MSC_VER #pragma once #endif #include <NXOpen/NXDeprecation.hxx> #include <vector> #include <NXOpen/NXString.hxx> #include <NXOpen/Callback.hxx> #include <NXOpen/BlockStyler_UIBlock.hxx> #include <NXOpen/BlockStyler_CurveCollector.hxx> #include <NXOpen/libnxopenuicpp_exports.hxx> #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4996) #endif #ifdef __GNUC__ #pragma GCC diagnostic ignored "-Wdeprecated-declarations" #endif namespace NXOpen { namespace BlockStyler { class CurveCollector; } namespace BlockStyler { class UIBlock; } class TaggedObject; namespace BlockStyler { class _CurveCollectorBuilder; class CurveCollectorImpl; /** Represents a Curve Collector <br> Created in NX8.5.0. <br> */ class NXOPENUICPPEXPORT CurveCollector : public BlockStyler::UIBlock { private: CurveCollectorImpl * m_curvecollector_impl; private: friend class _CurveCollectorBuilder; protected: CurveCollector(); public: ~CurveCollector(); /**Returns the AutomaticProgression <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: bool AutomaticProgression ( ); /**Sets the AutomaticProgression <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetAutomaticProgression ( bool automaticProgression /** automaticprogression */ ); /**Returns the BalloonTooltipImage <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString BalloonTooltipImage ( ); /**Sets the BalloonTooltipImage <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetBalloonTooltipImage ( const NXString & imageString /** image string */ ); /**Sets the BalloonTooltipImage <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetBalloonTooltipImage ( const char * imageString /** image string */ ); /**Returns the BalloonTooltipLayout as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString BalloonTooltipLayoutAsString ( ); /**Sets the BalloonTooltipLayout as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetBalloonTooltipLayoutAsString ( const NXString & enumString /** enumstring */ ); /**Sets the BalloonTooltipLayout as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetBalloonTooltipLayoutAsString ( const char * enumString /** enumstring */ ); /** Gets the BalloonTooltipLayout members @return Value to get from the property. <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: std::vector<NXString> GetBalloonTooltipLayoutMembers ( ); /**Returns the BalloonTooltipText <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString BalloonTooltipText ( ); /**Sets the BalloonTooltipText <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetBalloonTooltipText ( const NXString & balloonTooltipText /** balloon tooltip text */ ); /**Sets the BalloonTooltipText <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetBalloonTooltipText ( const char * balloonTooltipText /** balloon tooltip text */ ); /**Returns the Bitmap <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString Bitmap ( ); /**Sets the Bitmap <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetBitmap ( const NXString & bitmapString /** bitmap string */ ); /**Sets the Bitmap <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetBitmap ( const char * bitmapString /** bitmap string */ ); /**Returns the BlendVirtualCurveOverlay <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: bool BlendVirtualCurveOverlay ( ); /**Sets the BlendVirtualCurveOverlay <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetBlendVirtualCurveOverlay ( bool blendCurve /** blendcurve */ ); /**Returns the CurveRules <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: int CurveRules ( ); /**Sets the CurveRules <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetCurveRules ( int curveRules /** curverules */ ); /**Returns the CreateInterpartLink <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: bool CreateInterpartLink ( ); /**Sets the CreateInterpartLink <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetCreateInterpartLink ( bool createLink /** createlink */ ); /**Returns the Cue <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString Cue ( ); /**Sets the Cue <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetCue ( const NXString & cue /** cue */ ); /**Sets the Cue <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetCue ( const char * cue /** cue */ ); /**Returns the InterpartSelection as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString InterpartSelectionAsString ( ); /**Sets the InterpartSelection as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetInterpartSelectionAsString ( const NXString & enumString /** enumstring */ ); /**Sets the InterpartSelection as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetInterpartSelectionAsString ( const char * enumString /** enumstring */ ); /** Gets the InterpartSelection members @return Value to get from the property <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: std::vector<NXString> GetInterpartSelectionMembers ( ); /** Gets the SelectedObjects @return Value to get from the property <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: std::vector<NXOpen::TaggedObject *> GetSelectedObjects ( ); /** Sets the SelectedObjects <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetSelectedObjects ( const std::vector<NXOpen::TaggedObject *> & objectVector /**Value to set for the property*/ ); /**Returns the SelectMode as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString SelectModeAsString ( ); /**Sets the SelectMode as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetSelectModeAsString ( const NXString & enumString /** enumstring */ ); /**Sets the SelectMode as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetSelectModeAsString ( const char * enumString /** enumstring */ ); /** Gets the SelectMode members @return Value to get from the property <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: std::vector<NXString> GetSelectModeMembers ( ); /**Returns the StepStatus as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString StepStatusAsString ( ); /**Sets the StepStatus as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetStepStatusAsString ( const NXString & enumString /** enumstring */ ); /**Sets the StepStatus as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetStepStatusAsString ( const char * enumString /** enumstring */ ); /** Gets the StepStatus members @return Value to get from the property <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: std::vector<NXString> GetStepStatusMembers ( ); /**Returns the ToolTip <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString ToolTip ( ); /**Sets the ToolTip <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetToolTip ( const NXString & toolTip /** tooltip */ ); /**Sets the ToolTip <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetToolTip ( const char * toolTip /** tooltip */ ); /**Returns the DefaultCurveRules as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString DefaultCurveRulesAsString ( ); /**Sets the DefaultCurveRules as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetDefaultCurveRulesAsString ( const NXString & enumString /** enumstring */ ); /**Sets the DefaultCurveRules as string <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetDefaultCurveRulesAsString ( const char * enumString /** enumstring */ ); /** Gets the DefaultCurveRules members @return Value to get from the property <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: std::vector<NXString> GetDefaultCurveRulesMembers ( ); /**Returns the EntityType <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: int EntityType ( ); /**Sets the EntityType <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetEntityType ( int entityType /** entitytype */ ); /**Returns the PopupMenuEnabled <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: bool PopupMenuEnabled ( ); /**Sets the PopupMenuEnabled <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetPopupMenuEnabled ( bool enabled /** enabled */ ); /**Returns the AllowInferredCurveSelection <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: bool AllowInferredCurveSelection ( ); /**Sets the AllowInferredCurveSelection <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetAllowInferredCurveSelection ( bool allow /** allow */ ); /**Returns the InferredCurveSelection <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: bool InferredCurveSelection ( ); /**Sets the InferredCurveSelection <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetInferredCurveSelection ( bool selectInferredCurve /** selectinferredcurve */ ); /**Returns the LabelString <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: NXString LabelString ( ); /**Sets the LabelString <br> Created in NX8.5.0. <br> <br> License requirements : None */ public: void SetLabelString ( const NXString & labelString /** labelstring */ ); /**Sets the LabelString <br> Created in NX8.5.0. <br> <br> License requirements : None */ void SetLabelString ( const char * labelString /** labelstring */ ); }; } } #ifdef _MSC_VER #pragma warning(pop) #endif #ifdef __GNUC__ #ifndef NX_NO_GCC_DEPRECATION_WARNINGS #pragma GCC diagnostic warning "-Wdeprecated-declarations" #endif #endif #undef EXPORTLIBRARY #endif
[ "1075087594@qq.com" ]
1075087594@qq.com
56f98865d9f285703919573ecfef6c3827e870f3
0cb85cd0c88a9b9f0cca4472742c2bf9febef2d8
/external/edk/src/IFind.cpp
35e761671f1662ccf019049542b18b45a93ad903
[]
no_license
seth1002/antivirus-1
9dfbadc68e16e51f141ac8b3bb283c1d25792572
3752a3b20e1a8390f0889f6192ee6b851e99e8a4
refs/heads/master
2020-07-15T00:30:19.131934
2016-07-21T13:59:11
2016-07-21T13:59:11
null
0
0
null
null
null
null
UTF-8
C++
false
false
13,299
cpp
// --ifind.c------------------------------------------------------------------ // // Module containing FIND functions for various folders. // // Copyright (C) Microsoft Corp. 1986 - 2000. All Rights Reserved. // ----------------------------------------------------------------------------- #include "stdafx.h" #include "edk.h" #include "MAPIedkDef.h" #include "ifind.chk" //$--HrMAPIFindInbox---------------------------------------------------------- // Find IPM inbox folder. // ----------------------------------------------------------------------------- HRESULT HrMAPIFindInbox( // RETURNS: return code IN LPMDB lpMdb, // pointer to message store OUT ULONG *lpcbeid, // count of bytes in entry ID OUT LPENTRYID *lppeid) // Entry ID of IPM inbox { HRESULT hr = NOERROR; HRESULT hrT = NOERROR; SCODE sc = 0; DEBUGPUBLIC("HrMAPIFindInbox()"); hr = CHK_HrMAPIFindInbox( lpMdb, lpcbeid, lppeid); if(FAILED(hr)) RETURN(hr); *lpcbeid = 0; *lppeid = NULL; // Get the entry ID of the Inbox from the message store hrT = MAPICALL(lpMdb)->GetReceiveFolder( /*lpMdb,*/ TEXT("IPM"), fMapiUnicode, lpcbeid, lppeid, NULL); if(FAILED(hrT)) { if(hrT == MAPI_E_NOT_FOUND) { hr = HR_LOG(MAPI_E_NOT_FOUND); } else { hr = HR_LOG(E_FAIL); } } ASSERTERROR(*lpcbeid != 0, "ZERO length entry ID"); ASSERTERROR(*lppeid != NULL, "NULL entry ID"); RETURN(hr); } //$--HrMAPIFindOutbox--------------------------------------------------------- // Find IPM outbox folder. // ----------------------------------------------------------------------------- HRESULT HrMAPIFindOutbox( // RETURNS: return code IN LPMDB lpMdb, // pointer to message store OUT ULONG *lpcbeid, // count of bytes in entry ID OUT LPENTRYID *lppeid) // Entry ID of IPM outbox { HRESULT hr = NOERROR; HRESULT hrT = NOERROR; SCODE sc = 0; ULONG cValues = 0; LPSPropValue lpPropValue = NULL; ULONG cbeid = 0; SPropTagArray rgPropTag = { 1, { PR_IPM_OUTBOX_ENTRYID } }; DEBUGPUBLIC("HrMAPIFindOutbox()"); hr = CHK_HrMAPIFindOutbox( lpMdb, lpcbeid, lppeid); if(FAILED(hr)) RETURN(hr); *lpcbeid = 0; *lppeid = NULL; // Get the outbox entry ID property. hrT = MAPICALL(lpMdb)->GetProps( /*lpMdb,*/ &rgPropTag, fMapiUnicode, &cValues, &lpPropValue); if(hrT == MAPI_W_ERRORS_RETURNED) { if((lpPropValue != NULL) && (lpPropValue->Value.ul == MAPI_E_NOT_FOUND)) { hr = HR_LOG(MAPI_E_NOT_FOUND); } else { hr = HR_LOG(E_FAIL); } goto cleanup; } if(FAILED(hrT)) { lpPropValue = NULL; hr = HR_LOG(E_FAIL); goto cleanup; } ASSERTERROR(cValues != 0, "ZERO cValues variable"); ASSERTERROR(lpPropValue != NULL, "NULL lpPropValue variable"); // Check to make sure we got the right property. if (lpPropValue->ulPropTag != PR_IPM_OUTBOX_ENTRYID) { hr = HR_LOG(E_FAIL); goto cleanup; } cbeid = lpPropValue->Value.bin.cb; sc = MAPIAllocateBuffer(cbeid, (void **)lppeid); if(FAILED(sc)) { hr = HR_LOG(E_OUTOFMEMORY); goto cleanup; } // Copy outbox Entry ID CopyMemory( *lppeid, lpPropValue->Value.bin.lpb, cbeid); *lpcbeid = cbeid; cleanup: MAPIFREEBUFFER(lpPropValue); RETURN(hr); } //$--HrMAPIFindIPMSubtree-------------------------------------------------------- // Find IPM subtree folder. // ----------------------------------------------------------------------------- HRESULT HrMAPIFindIPMSubtree( // RETURNS: return code IN LPMDB lpMdb, // pointer to message store OUT ULONG *lpcbeid, // count of bytes in entry ID OUT LPENTRYID *lppeid) // entry ID of IPM subtree { HRESULT hr = NOERROR; HRESULT hrT = NOERROR; SCODE sc = 0; ULONG cValues = 0; LPSPropValue lpPropValue = NULL; ULONG cbeid = 0; SPropTagArray rgPropTag = { 1, { PR_IPM_SUBTREE_ENTRYID } }; DEBUGPUBLIC("HrMAPIFindIPMSubtree()"); hr = CHK_HrMAPIFindIPMSubtree( lpMdb, lpcbeid, lppeid); if(FAILED(hr)) RETURN(hr); *lpcbeid = 0; *lppeid = NULL; // Get the subtree entry ID property. hrT = MAPICALL(lpMdb)->GetProps( /*lpMdb,*/ &rgPropTag, fMapiUnicode, &cValues, &lpPropValue); if(hrT == MAPI_W_ERRORS_RETURNED) { if((lpPropValue != NULL) && (lpPropValue->Value.ul == MAPI_E_NOT_FOUND)) { hr = HR_LOG(MAPI_E_NOT_FOUND); } else { hr = HR_LOG(E_FAIL); } goto cleanup; } if(FAILED(hrT)) { lpPropValue = NULL; hr = HR_LOG(E_FAIL); goto cleanup; } ASSERTERROR(cValues != 0, "ZERO cValues variable"); ASSERTERROR(lpPropValue != NULL, "NULL lpPropValue variable"); // Check to make sure we got the right property. if (lpPropValue->ulPropTag != PR_IPM_SUBTREE_ENTRYID) { hr = HR_LOG(E_FAIL); goto cleanup; } cbeid = lpPropValue->Value.bin.cb; sc = MAPIAllocateBuffer(cbeid, (void **)lppeid); if(FAILED(sc)) { hr = HR_LOG(E_OUTOFMEMORY); goto cleanup; } // Copy subtree entry ID CopyMemory( *lppeid, lpPropValue->Value.bin.lpb, cbeid); *lpcbeid = cbeid; cleanup: MAPIFREEBUFFER(lpPropValue); RETURN(hr); } //$--HrGWFindMtsOutFolder------------------------------------------------------------ // Find MTS-OUT folder. // ----------------------------------------------------------------------------- HRESULT HrGWFindMtsOutFolder( // RETURNS: return code IN LPMDB lpMdb, // pointer to message store OUT ULONG *lpcbeid, // count of bytes in entry ID OUT LPENTRYID *lppeid) // entry ID of MTS-OUT { HRESULT hr = NOERROR; HRESULT hrT = NOERROR; SCODE sc = 0; ULONG cValues = 0; LPSPropValue lpPropValue = NULL; ULONG cbeid = 0; SPropTagArray rgPropTag = { 1, { PR_GW_MTSOUT_ENTRYID } }; DEBUGPUBLIC("HrGWFindMtsOutFolder()"); hr = CHK_HrGWFindMtsOutFolder( lpMdb, lpcbeid, lppeid); if(FAILED(hr)) RETURN(hr); *lpcbeid = 0; *lppeid = NULL; // Get the entry ID property. hrT = MAPICALL(lpMdb)->GetProps( /*lpMdb,*/ &rgPropTag, fMapiUnicode, &cValues, &lpPropValue); if(hrT == MAPI_W_ERRORS_RETURNED) { if((lpPropValue != NULL) && (lpPropValue->Value.ul == MAPI_E_NOT_FOUND)) { hr = HR_LOG(MAPI_E_NOT_FOUND); } else { hr = HR_LOG(E_FAIL); } goto cleanup; } if(FAILED(hrT)) { lpPropValue = NULL; hr = HR_LOG(E_FAIL); goto cleanup; } ASSERTERROR(cValues != 0, "ZERO cValues variable"); ASSERTERROR(lpPropValue != NULL, "NULL lpPropValue variable"); // Check to make sure we got the right property. if (lpPropValue->ulPropTag != PR_GW_MTSOUT_ENTRYID) { hr = HR_LOG(E_FAIL); goto cleanup; } cbeid = lpPropValue->Value.bin.cb; sc = MAPIAllocateBuffer(cbeid, (void **)lppeid); if(FAILED(sc)) { hr = HR_LOG(E_OUTOFMEMORY); goto cleanup; } // Copy entry ID CopyMemory( *lppeid, lpPropValue->Value.bin.lpb, cbeid); *lpcbeid = cbeid; cleanup: MAPIFREEBUFFER(lpPropValue); RETURN(hr); } //$--HrGWFindMtsInFolder------------------------------------------------------------- // Find MTS-IN folder. // ----------------------------------------------------------------------------- HRESULT HrGWFindMtsInFolder( // RETURNS: return code IN LPMDB lpMdb, // pointer to message store OUT ULONG *lpcbeid, // count of bytes in entry ID OUT LPENTRYID *lppeid) // entry ID of MTS-IN { HRESULT hr = NOERROR; HRESULT hrT = NOERROR; SCODE sc = 0; ULONG cValues = 0; LPSPropValue lpPropValue = NULL; ULONG cbeid = 0; SPropTagArray rgPropTag = { 1, { PR_GW_MTSIN_ENTRYID } }; DEBUGPUBLIC("HrGWFindMtsInFolder()"); hr = CHK_HrGWFindMtsInFolder( lpMdb, lpcbeid, lppeid); if(FAILED(hr)) RETURN(hr); *lpcbeid = 0; *lppeid = NULL; // Get the entry ID property. hrT = MAPICALL(lpMdb)->GetProps( /*lpMdb,*/ &rgPropTag, fMapiUnicode, &cValues, &lpPropValue); if(hrT == MAPI_W_ERRORS_RETURNED) { if((lpPropValue != NULL) && (lpPropValue->Value.ul == MAPI_E_NOT_FOUND)) { hr = HR_LOG(MAPI_E_NOT_FOUND); } else { hr = HR_LOG(E_FAIL); } goto cleanup; } if(FAILED(hrT)) { lpPropValue = NULL; hr = HR_LOG(E_FAIL); goto cleanup; } ASSERTERROR(cValues != 0, "ZERO cValues variable"); ASSERTERROR(lpPropValue != NULL, "NULL lpPropValue variable"); // Check to make sure we got the right property. if (lpPropValue->ulPropTag != PR_GW_MTSIN_ENTRYID) { hr = HR_LOG(E_FAIL); goto cleanup; } cbeid = lpPropValue->Value.bin.cb; sc = MAPIAllocateBuffer(cbeid, (void **)lppeid); if(FAILED(sc)) { hr = HR_LOG(E_OUTOFMEMORY); goto cleanup; } // Copy entry ID CopyMemory( *lppeid, lpPropValue->Value.bin.lpb, cbeid); *lpcbeid = cbeid; cleanup: MAPIFREEBUFFER(lpPropValue); RETURN(hr); } //$--HrFindExchangePublicStore------------------------------------------------------- // Find public store root folder. // ----------------------------------------------------------------------------- HRESULT HrFindExchangePublicStore( // RETURNS: return code IN LPMDB lpMdb, // pointer to message store OUT ULONG *lpcbeid, // count of bytes in entry ID OUT LPENTRYID *lppeid) // entry ID of public store { HRESULT hr = NOERROR; HRESULT hrT = NOERROR; SCODE sc = 0; ULONG cValues = 0; LPSPropValue lpPropValue = NULL; ULONG cbeid = 0; SPropTagArray rgPropTag = { 1, { PR_NON_IPM_SUBTREE_ENTRYID } }; DEBUGPUBLIC("HrFindExchangePublicStore()"); hr = CHK_HrFindExchangePublicStore( lpMdb, lpcbeid, lppeid); if(FAILED(hr)) RETURN(hr); *lpcbeid = 0; *lppeid = NULL; // Get the entry ID property. hrT = MAPICALL(lpMdb)->GetProps( /*lpMdb,*/ &rgPropTag, fMapiUnicode, &cValues, &lpPropValue); if(hrT == MAPI_W_ERRORS_RETURNED) { if((lpPropValue != NULL) && (lpPropValue->Value.ul == MAPI_E_NOT_FOUND)) { hr = HR_LOG(MAPI_E_NOT_FOUND); } else { hr = HR_LOG(E_FAIL); } goto cleanup; } if(FAILED(hrT)) { lpPropValue = NULL; hr = HR_LOG(E_FAIL); goto cleanup; } ASSERTERROR(cValues != 0, "ZERO cValues variable"); ASSERTERROR(lpPropValue != NULL, "NULL lpPropValue variable"); // Check to make sure we got the right property. if (lpPropValue->ulPropTag != PR_NON_IPM_SUBTREE_ENTRYID) { hr = HR_LOG(E_FAIL); goto cleanup; } cbeid = lpPropValue->Value.bin.cb; sc = MAPIAllocateBuffer(cbeid, (void **)lppeid); if(FAILED(sc)) { hr = HR_LOG(E_OUTOFMEMORY); goto cleanup; } // Copy entry ID CopyMemory( *lppeid, lpPropValue->Value.bin.lpb, cbeid); *lpcbeid = cbeid; cleanup: MAPIFREEBUFFER(lpPropValue); RETURN(hr); }
[ "idrez.mochamad@gmail.com" ]
idrez.mochamad@gmail.com
1cd966daca930c5db4b24216a8785cdbe7dff685
f34b8a5215a2192e1f39589ecee9383aa0698736
/sort.cpp
97fd82cdb5f1e7172a6123b8c0535ce4b5559fd3
[]
no_license
adammorton11/3sorts
9899ce4ad2095be22a8e91e2c8149833ae180a74
1986dcc25b5537e41fa7e5bf1e1c7ec0b30bc9b5
refs/heads/master
2021-01-02T09:07:41.746487
2015-03-06T00:25:05
2015-03-06T00:25:05
null
0
0
null
null
null
null
UTF-8
C++
false
false
4,768
cpp
#include <iostream> #include <string> // The string class: pg 131 #include <vector> // The vector class: pg 1012 #include "sort.hpp" using std::string; using std::vector; template <typename T> void sort(T *a, T *aux, int lo, int hi); template <typename T> void sort(vector<T> &a, T *aux, int lo, int hi); template <typename T> void merge(T *a, T *aux, int lo, int mid, int hi); template <typename T> void merge(vector<T> &a, T* aux, int lo, int mid, int hi); //Recursive Mergesort //Pointer template <typename T> void recursive_mergesort(T *a, long int n) { T *aux = (T*) std::malloc(n*sizeof(T)); if(aux == NULL){ //UH OH MALLOC FAILED } else{ if (n<=42){ insertion_sort(a,n); } else{ sort(a, aux, 0, n-1); } } } //Vector template <typename T> void recursive_mergesort(vector<T> &a) { T *aux = (T*) std::malloc(a.size()*sizeof(T)); if(aux == NULL){ //UH OH MALLOC FAILED } else{ if (a.size()<=42){ insertion_sort(a); } else{ sort(a, aux, 0, a.size()-1); } } } //Sort helper function for Recursive Mergesort //Pointer version template <typename T> // template, typename: pg 419 void sort(T *a, T *aux, int lo, int hi) { if (hi<= lo){ return; } int mid = lo + (hi-lo) / 2; sort(a, aux, lo, mid); sort(a, aux, mid+1, hi); merge(a, aux, lo, mid, hi); } //Vector Version template <typename T> // template, typename: pg 419 void sort(vector<T> &a, T *aux, int lo, int hi) { if (hi<= lo){ return; } int mid = lo + (hi-lo) / 2; sort(a, aux, lo, mid); sort(a, aux, mid+1, hi); merge(a, aux, lo, mid, hi); } //Iterative Mergesort - pointer version template <typename T> void iterative_mergesort(T *a, long int n) { if (n<=0){ return; } T *aux = (T*) std::malloc(n*sizeof(T)); if (n<=0){ return; } if(aux == NULL){ //UH OH MALLOC FAILED } else{ for (int sz = 1; sz <n; sz = sz+sz){ for (int lo = 0; lo < n-sz; lo+=(sz+sz)){ if ((lo+sz+sz-1)<=(n-1)){ int hi = (lo+sz+sz-1); merge(a, aux, lo, lo+sz-1, hi); } else{ int hi = n-1; merge(a, aux, lo, lo+sz-1, hi); } } } } } //Vector Version template <typename T> void iterative_mergesort(vector<T> &a) { T *aux = (T*) std::malloc(a.size()*sizeof(T)); if(aux == NULL){ //UH OH MALLOC FAILED } else{ for (int sz = 1; sz <a.size(); sz = sz+sz){ for (int lo = 0; lo < a.size()-sz; lo+=(sz+sz)){ if ((lo+sz+sz-1)<=(a.size()-1)){ int hi = (lo+sz+sz-1); merge(a, aux, lo, lo+sz-1, hi); } else{ int hi = a.size()-1; merge(a, aux, lo, lo+sz-1, hi); } } } } } //Merge Helper function //Pointer version template <typename T> void merge(T *a, T *aux, int lo, int mid, int hi){ int i = lo, j = mid+1; for (int k = lo; k <= hi; k++){ aux[k] = a[k]; } for (int k = lo; k <= hi; k++){ if (i > mid){ a[k] = aux[j++]; } else if(j>hi){ a[k] = aux[i++]; } else if(aux[j] < aux[i]){ a[k] = aux[j++]; } else{ a[k] = aux[i++]; } } } //Vector Version template <typename T> void merge(vector<T> &a, T *aux, int lo, int mid, int hi){ int i = lo, j = mid+1; for (int k = lo; k <= hi; k++){ aux[k] = a[k]; } for (int k = lo; k <= hi; k++){ if (i > mid){ a[k] = aux[j++]; } else if(j>hi){ a[k] = aux[i++]; } else if(aux[j] < aux[i]){ a[k] = aux[j++]; } else{ a[k] = aux[i++]; } } } //Instantiations template void merge<double>(double*, double*, int, int, int); template void merge<double>(vector<double>&, double *, int, int, int); template void merge<string>(vector<string>&, string *, int, int, int); template void iterative_mergesort<double>(double*, long int); template void iterative_mergesort<double>(vector<double>&); template void iterative_mergesort<string>(vector<string>&); template void recursive_mergesort<double>(double*, long int); template void recursive_mergesort<double>(vector<double>&); template void recursive_mergesort<string>(vector<string>&); template void sort<double>(double*, double*, int, int); template void sort<double>(vector<double>&, double*, int, int); template void sort<string>(vector<string>&, string*, int, int);
[ "Maverick@Adams-MacBook-Pro.local" ]
Maverick@Adams-MacBook-Pro.local
7adf28ed8b4383c76e12905a1fa74d2b57f09d04
b69ccb24f09c3d4a51dc965bee6554e22f22497b
/dynet/dynet/training.h
36e56a6815c6122b557e17d503bf28372cce126e
[ "Apache-2.0" ]
permissive
LorraineWuu/Mantidae
c466569c79a286bf8e71cdbf6978854345ce312d
ea2683b9865ec0ed555e93c4eb27edb6890336e5
refs/heads/master
2021-01-23T07:51:18.486937
2017-03-28T01:07:17
2017-03-28T01:07:17
null
0
0
null
null
null
null
UTF-8
C++
false
false
15,218
h
/** * \file training.h * \defgroup optimizers * \brief Training procedures * * The various trainers are defined here. * All trainers are structures inheriting from the `Trainer` struct. * * */ #ifndef DYNET_TRAINING_H_ #define DYNET_TRAINING_H_ #include <vector> #include <boost/serialization/export.hpp> #include "dynet/model.h" #include "dynet/shadow-params.h" #include "dynet/io-macros.h" #define DYNET_TRAINER_DEFINE_DEV_IMPL() \ void update_params(real scale, real gscale, size_t idx) override; \ void update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) override; \ void update_lookup_params(real scale, real gscale, size_t idx) override; \ template <class MyDevice> \ void update_rule_dev(const MyDevice & dev, real scale, real gscale, const std::vector<Tensor*> & values); \ void update_rule(real scale, real gscale, const std::vector<Tensor*> & values) override; namespace dynet { /** * \ingroup optimizers * * \struct Trainer * \brief General trainer struct * */ struct Trainer { /** * \brief General constructor for a Trainer * * \param m Model to be trained * \param e0 Initial learning rate * \param edecay Learning rate decay */ explicit Trainer(Model& m, real e0, real edecay = 0.0) : eta0(e0), eta(e0), eta_decay(edecay), epoch(), clipping_enabled(true), clip_threshold(5), clips(), updates(), clips_since_status(), updates_since_status(), sparse_updates_enabled(true), aux_allocated(false), model(&m) {} virtual ~Trainer(); // ----------------------------------------------------------------------------------- // added by Cong Duy Vu Hoang (vhoang2@student.unimelb.edu.au) void update_epoch_only(real r = 1.0){ epoch += r; } void update_epoch(real r, unsigned _max_epoch = 4) { epoch += r; //Trick: decrease learning rate after a fixed number of epochs (e.g. _max_epoch) if (epoch >= _max_epoch) eta /= eta_decay; } void update_learning_rate() { eta /= eta_decay; } // ----------------------------------------------------------------------------------- /** * \brief Update parameters * \details Update the parameters according to the appropriate update rule * * \param scale The scaling factor for the gradients */ void update(real scale = 1.0); /** * \brief Update subset of parameters * \details Update some but not all of the parameters included in the model. This * is the update_subset() function in the Python bindings. The * parameters to be updated are specified by index, which can be found * for Parameter and LookupParameter objects through the "index" variable * (or the get_index() function in the Python bindings). * * \param updated_params The parameter indices to be updated * \param updated_lookup_params The lookup parameter indices to be updated * \param scale The scaling factor for the gradients */ void update(const std::vector<unsigned> & updated_params, const std::vector<unsigned> & updated_lookup_params, real scale = 1.0); void update_epoch(real r = 1) { epoch += r; eta = eta0 / (1 + epoch * eta_decay); } /** * \brief Clip gradient * \details If clipping is enabled and the gradient is too big, return the amount to * scale the gradient by (otherwise 1) * * * \param scale The clipping limit * \return The appropriate scaling factor */ float clip_gradients(real scale); // TODO: This is unprotected temporarily until there is a better solution // for serializing the weight decay when saving models // Rescale all the parameters handled by this model void rescale_and_reset_weight_decay(); // learning rates real eta0; real eta; real eta_decay; real epoch; // clipping bool clipping_enabled; real clip_threshold; real clips; real updates; // the number of clips and status since the last print real clips_since_status; real updates_since_status; /** * \brief Whether to perform sparse updates * \details DyNet trainers support two types of updates for lookup parameters, * sparse and dense. Sparse updates are the default. They have the * potential to be faster, as they only touch the parameters that have * non-zero gradients. However, they may not always be faster (particulary * on GPU with mini-batch training), and are not precisely numerically * correct for some update rules such as MomentumTrainer and AdamTrainer. * Thus, if you set this variable to false, the trainer will perform dense * updates and be precisely correct, and maybe faster sometimes. */ bool sparse_updates_enabled; bool aux_allocated; void status() { std::cerr << "[epoch=" << epoch << " eta=" << eta << " clips=" << clips_since_status << " updates=" << updates_since_status << "] "; updates_since_status = clips_since_status = 0; } Model* model; // parameters and gradients live here protected: Trainer() {} virtual void alloc_impl() { } /** * \brief The actual rule to update the parameters * * \param scale Scale of the update (i.e. learning rate) * \param gscale Gradient scale based on clipping * \param values Values specific to the particular update rule being implemented */ virtual void update_rule(real scale, real gscale, const std::vector<Tensor*> & values) = 0; /** * \brief Parameter update function * * \param scale Scale of the update (i.e. learning rate) * \param gscale Gradient scale based on clipping * \param idx Index of the parameter */ virtual void update_params(real scale, real gscale, size_t idx) = 0; /** * \brief Sparse lookup parameter update function * * \param scale Scale of the update (i.e. learning rate) * \param gscale Gradient scale based on clipping * \param idx Index of the lookup parameter object * \param lidx Index of the specific entry within the lookup parameter object */ virtual void update_lookup_params(real scale, real gscale, size_t idx, size_t lidx) = 0; /** * \brief Dense lookup parameter update function * * \param scale Scale of the update (i.e. learning rate) * \param gscale Gradient scale based on clipping * \param idx Index of the lookup parameter object */ virtual void update_lookup_params(real scale, real gscale, size_t idx) = 0; private: DYNET_SERIALIZE_DECLARE() }; /** * \ingroup optimizers * * \brief Stochastic gradient descent trainer * \details This trainer performs stochastic gradient descent, the goto optimization procedure for neural networks. * In the standard setting, the learning rate at epoch \f$t\f$ is \f$\eta_t=\frac{\eta_0}{1+\eta_{\mathrm{decay}}t}\f$ * * Reference : [reference needed](ref.need.ed) * */ struct SimpleSGDTrainer : public Trainer { /** * \brief Constructor * * \param m Model to be trained * \param e0 Initial learning rate * \param edecay Learning rate decay parameter. */ explicit SimpleSGDTrainer(Model& m, real e0 = 0.1, real edecay = 0.0) : Trainer(m, e0, edecay) {} protected: DYNET_TRAINER_DEFINE_DEV_IMPL() private: SimpleSGDTrainer() {} DYNET_SERIALIZE_DECLARE() }; /** * \ingroup optimizers * * \brief Stochastic gradient descent with momentum * \details This is a modified version of the SGD algorithm with momentum to stablize the gradient trajectory. * The modified gradient is \f$\theta_{t+1}=\mu\theta_{t}+\nabla_{t+1}\f$ where \f$\mu\f$ is the momentum. * * Reference : [reference needed](ref.need.ed) * */ struct MomentumSGDTrainer : public Trainer { /** * \brief Constructor * * \param m Model to be trained * \param e0 Initial learning rate * \param mom Momentum * \param edecay Learning rate decay parameter */ explicit MomentumSGDTrainer(Model& m, real e0 = 0.01, real mom = 0.9, real edecay = 0.0) : Trainer(m, e0, edecay), momentum(mom) {} protected: DYNET_TRAINER_DEFINE_DEV_IMPL() virtual void alloc_impl() override; real momentum; // the following represent the current velocity std::vector<ShadowParameters> vp; std::vector<ShadowLookupParameters> vlp; //std::unordered_map<ParameterStorage*, Tensor> vp; //std::unordered_map<LookupParameterStorage*, std::unordered_map<unsigned, Tensor>> vl; private: MomentumSGDTrainer() {} DYNET_SERIALIZE_DECLARE() }; /** * \ingroup optimizers * * \brief Adagrad optimizer * \details The adagrad algorithm assigns a different learning rate to each parameter according to the following formula : * \f$\delta_\theta^{(t)}=-\frac{\eta_0}{\epsilon+\sum_{i=0}^{t-1}(\nabla_\theta^{(i)})^2}\nabla_\theta^{(t)}\f$ * * Reference : [Duchi et al., 2011](http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf) * */ struct AdagradTrainer : public Trainer { /** * \brief Constructor * * \param m Model to be trained * \param e0 Initial learning rate * \param eps Bias parameter \f$\epsilon\f$ in the adagrad formula * \param edecay Learning rate decay parameter */ explicit AdagradTrainer(Model& m, real e0 = 0.1, real eps = 1e-20, real edecay = 0.0) : Trainer(m, e0, edecay), epsilon(eps) {} protected: DYNET_TRAINER_DEFINE_DEV_IMPL() virtual void alloc_impl() override; real epsilon; std::vector<ShadowParameters> vp; std::vector<ShadowLookupParameters> vlp; private: AdagradTrainer() {} DYNET_SERIALIZE_DECLARE() }; /** * \ingroup optimizers * * \brief AdaDelta optimizer * \details The AdaDelta optimizer is a variant of Adagrad where * \f$\frac{\eta_0}{\sqrt{\epsilon+\sum_{i=0}^{t-1}(\nabla_\theta^{(i)})^2}}\f$ is replaced by * \f$\frac{\sqrt{\epsilon+\sum_{i=0}^{t-1}\rho^{t-i-1}(1-\rho)(\delta_\theta^{(i)})^2}}{\sqrt{\epsilon+\sum_{i=0}^{t-1}(\nabla_\theta^{(i)})^2}}\f$, * hence eliminating the need for an initial learning rate. * * Reference : [ADADELTA: An Adaptive Learning Rate Method](https://arxiv.org/pdf/1212.5701v1) * */ struct AdadeltaTrainer : public Trainer { /** * \brief Constructor * * \param m Model to be trained * \param eps Bias parameter \f$\epsilon\f$ in the adagrad formula * \param rho Update parameter for the moving average of updates in the numerator * \param edecay Learning rate decay parameter */ explicit AdadeltaTrainer(Model& m, real eps = 1e-6, real rho = 0.95, real edecay = 0.0) : Trainer(m, 1.0, edecay), epsilon(eps), rho(rho) {} protected: DYNET_TRAINER_DEFINE_DEV_IMPL() virtual void alloc_impl() override; real epsilon; real rho; std::vector<ShadowParameters> hg; // History of gradients std::vector<ShadowLookupParameters> hlg; std::vector<ShadowParameters> hd; // History of deltas std::vector<ShadowLookupParameters> hld; private: AdadeltaTrainer() {} DYNET_SERIALIZE_DECLARE() }; /** * \ingroup optimizers * * \brief RMSProp optimizer * \details The RMSProp optimizer is a variant of Adagrad where the squared sum of previous gradients is replaced with a moving average with parameter \f$\rho\f$. * * Reference : [reference needed](ref.need.ed) * */ struct RmsPropTrainer : public Trainer { /** * \brief Constructor * * \param m Model to be trained * \param e0 Initial learning rate * \param eps Bias parameter \f$\epsilon\f$ in the adagrad formula * \param rho Update parameter for the moving average (`rho = 0` is equivalent to using Adagrad) * \param edecay Learning rate decay parameter */ explicit RmsPropTrainer(Model& m, real e0 = 0.1, real eps = 1e-20, real rho = 0.95, real edecay = 0.0) : Trainer(m, e0, edecay), epsilon(eps), rho(rho) {} protected: DYNET_TRAINER_DEFINE_DEV_IMPL() virtual void alloc_impl() override; real epsilon; real rho; std::vector<real> hg; // History of gradients std::vector<std::vector<real> > hlg; private: RmsPropTrainer() {} DYNET_SERIALIZE_DECLARE() }; /** * \ingroup optimizers * * \brief Adam optimizer * \details The Adam optimizer is similar to RMSProp but uses unbiased estimates * of the first and second moments of the gradient * * Reference : [Adam: A Method for Stochastic Optimization](https://arxiv.org/pdf/1412.6980v8) * */ struct AdamTrainer : public Trainer { /** * \brief Constructor * * \param m Model to be trained * \param e0 Initial learning rate * \param beta_1 Moving average parameter for the mean * \param beta_2 Moving average parameter for the variance * \param eps Bias parameter \f$\epsilon\f$ * \param edecay Learning rate decay parameter */ explicit AdamTrainer(Model& m, float e0 = 0.001, float beta_1 = 0.9, float beta_2 = 0.999, float eps = 1e-8, real edecay = 0.0) : Trainer(m, e0, edecay), beta_1(beta_1), beta_2(beta_2), epsilon(eps) {} protected: DYNET_TRAINER_DEFINE_DEV_IMPL() virtual void alloc_impl() override; float beta_1; float beta_2; float epsilon; std::vector<ShadowParameters> m; // History of gradients std::vector<ShadowLookupParameters> lm; std::vector<ShadowParameters> v; // History of deltas std::vector<ShadowLookupParameters> lv; private: AdamTrainer() {} DYNET_SERIALIZE_DECLARE() }; // Written by Cong Duy Vu Hoang /** * \ingroup optimizers * * \brief Exponentiated gradient optimizer with adaptive learning rates * \details FIXME * * Reference : FIXME * */ struct AdaptiveEGTrainer : public Trainer { explicit AdaptiveEGTrainer(Model& m, real e0 = 0.1, real edecay = 0.0) : Trainer(m, e0, edecay) { } protected: DYNET_TRAINER_DEFINE_DEV_IMPL() virtual void alloc_impl() override; // the following represents the previous params, gradient magnitudes //std::vector<ShadowParameters> vp;// parameters //std::vector<ShadowLookupParameters> vlp;// lookup parameters //std::vector<float> v_etas;// adaptive learning rate vector std::vector<ShadowParameters> m; // History of gradients std::vector<ShadowLookupParameters> lm; std::vector<ShadowParameters> v; // History of deltas std::vector<ShadowLookupParameters> lv; private: AdaptiveEGTrainer() {} DYNET_SERIALIZE_DECLARE() }; // Written by Cong Duy Vu Hoang /** * \ingroup optimizers * * \brief Exponentiated gradient optimizer with momentum * \details FIXME * * Reference : FIXME * */ struct EGTrainer : public Trainer { explicit EGTrainer(Model& m, real e0 = 0.1, real mom = 0.9, real edecay = 0.0) : Trainer(m, e0, edecay), momentum(mom) {} protected: DYNET_TRAINER_DEFINE_DEV_IMPL() virtual void alloc_impl() override; real momentum;// with momentum std::vector<ShadowParameters> hp; // (previous) history of parameters std::vector<ShadowLookupParameters> hlp; private: EGTrainer() {} DYNET_SERIALIZE_DECLARE() }; } // namespace dynet BOOST_CLASS_EXPORT_KEY(dynet::SimpleSGDTrainer) BOOST_CLASS_EXPORT_KEY(dynet::MomentumSGDTrainer) BOOST_CLASS_EXPORT_KEY(dynet::AdagradTrainer) BOOST_CLASS_EXPORT_KEY(dynet::AdadeltaTrainer) BOOST_CLASS_EXPORT_KEY(dynet::RmsPropTrainer) BOOST_CLASS_EXPORT_KEY(dynet::AdamTrainer) BOOST_CLASS_EXPORT_KEY(dynet::EGTrainer) BOOST_CLASS_EXPORT_KEY(dynet::AdaptiveEGTrainer) #endif
[ "vhoang2@student.unimelb.edu.au" ]
vhoang2@student.unimelb.edu.au
a10ee9f418b526c17405a88a4513bb636a04ffdd
54d919fd0a506e732a32dad848fa6dfa1e0fc193
/src/core/callback.cpp
49f8b6a75f74052eeb027859c0c4cf95ed202865
[ "MIT" ]
permissive
t03cut4/chunkwm
f0372aca93207e31b14a8a9f8935adf414e9b06f
4313772bf5a25c2ce4340b70ec7579c6b94a4044
refs/heads/master
2020-03-19T19:13:49.212180
2018-06-09T23:36:50
2018-06-09T23:36:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
20,281
cpp
#include "config.h" #include "plugin.h" #include "wqueue.h" #include "state.h" #include "clog.h" #include "dispatch/carbon.h" #include "dispatch/workspace.h" #include "dispatch/event.h" #include "../common/accessibility/window.h" #include "../common/misc/assert.h" #include <stdio.h> #include <pthread.h> #define internal static #define ProcessPluginList(plugin_export, Context) \ plugin_list *List = BeginPluginList(plugin_export); \ for (plugin_list_iter It = List->begin(); \ It != List->end(); \ ++It) { \ plugin *Plugin = It->first; \ Plugin->Run(#plugin_export, \ (void *) Context); \ } \ EndPluginList(plugin_export) #define ProcessPluginListThreaded(plugin_export, Context) \ plugin_list *List = BeginPluginList(plugin_export); \ plugin_work WorkArray[List->size()]; \ int WorkCount = 0; \ for (plugin_list_iter It = List->begin(); \ It != List->end(); \ ++It) { \ plugin_work *Work = WorkArray + WorkCount++; \ Work->Plugin = It->first; \ Work->Export = (char *) #plugin_export; \ Work->Data = (void *) Context; \ AddWorkQueueEntry(&Queue, \ &PluginWorkCallback, \ Work); \ } \ EndPluginList(plugin_export); \ CompleteWorkQueue(&Queue) \ struct plugin_work { plugin *Plugin; char *Export; void *Data; }; internal work_queue Queue; internal WORK_QUEUE_CALLBACK(PluginWorkCallback) { plugin_work *Work = (plugin_work *) Data; Work->Plugin->Run(Work->Export, Work->Data); } // NOTE(koekeishiya): We pass a pointer to this function to every plugin as they are loaded. void ChunkwmBroadcast(const char *PluginName, const char *EventName, void *PluginData, size_t Size) { if (!PluginName || !EventName) { return; } void **Context = (void **) malloc(2 * sizeof(void *)); size_t TotalLength = strlen(PluginName) + strlen(EventName) + 2; char *Event = (char *) malloc(TotalLength); snprintf(Event, TotalLength, "%s_%s", PluginName, EventName); Context[0] = Event; if (Size) { void *Data = (void *) malloc(Size); memcpy(Data, PluginData, Size); Context[1] = Data; } else { Context[1] = NULL; } c_log(C_LOG_LEVEL_DEBUG, "chunkwm:%s:%s\n", PluginName, EventName); ConstructEvent(ChunkWM_PluginBroadcast, Context); } CHUNKWM_CALLBACK(Callback_ChunkWM_PluginBroadcast) { void **Context = (void **) Event->Context; char *PluginEvent = (char *) Context[0]; void *EventData = (void *) Context[1]; loaded_plugin_list *List = BeginLoadedPluginList(); plugin_work WorkArray[List->size()]; int WorkCount = 0; for (loaded_plugin_list_iter It = List->begin(); It != List->end(); ++It) { loaded_plugin *LoadedPlugin = It->second; if (strncmp(LoadedPlugin->Info->PluginName, PluginEvent, strlen(LoadedPlugin->Info->PluginName)) != 0) { plugin_work *Work = WorkArray + WorkCount++; Work->Plugin = LoadedPlugin->Plugin; Work->Export = PluginEvent; Work->Data = EventData; AddWorkQueueEntry(&Queue, &PluginWorkCallback, Work); } } EndLoadedPluginList(); CompleteWorkQueue(&Queue); if (EventData) { free(EventData); } free(PluginEvent); free(Context); } bool BeginCallbackThreads(int Count) { if ((Queue.Semaphore = sem_open("work_queue_semaphore", O_CREAT, 0644, 0)) == SEM_FAILED) { return false; } pthread_t Thread[Count]; for (int Index = 0; Index < Count; ++Index) { pthread_create(&Thread[Index], NULL, &WorkQueueThreadProc, &Queue); } return true; } CHUNKWM_CALLBACK(Callback_ChunkWM_PluginLoad) { plugin_fs *PluginFS = (plugin_fs *) Event->Context; LoadPlugin(PluginFS->Absolutepath, PluginFS->Filename); DestroyPluginFS(PluginFS); free(PluginFS); } CHUNKWM_CALLBACK(Callback_ChunkWM_PluginUnload) { plugin_fs *PluginFS = (plugin_fs *) Event->Context; UnloadPlugin(PluginFS->Absolutepath, PluginFS->Filename); DestroyPluginFS(PluginFS); free(PluginFS); } CHUNKWM_CALLBACK(Callback_ChunkWM_PluginCommand) { chunkwm_delegate *Delegate = (chunkwm_delegate *) Event->Context; ASSERT(Delegate); plugin *Plugin = GetPluginFromFilename(Delegate->Target); if (Plugin) { chunkwm_payload Payload = { Delegate->SockFD, Delegate->Command, Delegate->Message }; Plugin->Run("chunkwm_daemon_command", (void *) &Payload); } else { c_log(C_LOG_LEVEL_WARN, "chunkwm: plugin '%s' is not loaded.\n", Delegate->Target); } CloseSocket(Delegate->SockFD); free(Delegate->Target); free(Delegate->Command); free((char *)(Delegate->Message)); free(Delegate); } // NOTE(koekeishiya): Application-related callbacks. CHUNKWM_CALLBACK(Callback_ChunkWM_ApplicationLaunched) { carbon_application_details *Info = (carbon_application_details *) Event->Context; ASSERT(Info); c_log(C_LOG_LEVEL_DEBUG, "%d:%s launched\n", Info->PID, Info->ProcessName); macos_application *Application = GetApplicationFromPID(Info->PID); ASSERT(Application); #if 0 ProcessPluginList(chunkwm_export_application_launched, Application); #else ProcessPluginListThreaded(chunkwm_export_application_launched, Application); #endif /* * NOTE(koekeishiya): When an application is launched, we incorrectly * receive the applicationActivated first. We discard that notification * and restore it when we have the application to work with. */ workspace_application_details *WSInfo = BeginWorkspaceApplicationDetails(Info->ProcessName, Info->PSN, Info->PID); ConstructEvent(ChunkWM_ApplicationActivated, WSInfo); } CHUNKWM_CALLBACK(Callback_ChunkWM_ApplicationTerminated) { carbon_application_details *Info = (carbon_application_details *) Event->Context; ASSERT(Info); macos_application *Application = GetApplicationFromPID(Info->PID); if (Application) { c_log(C_LOG_LEVEL_DEBUG, "%d:%s terminated\n", Info->PID, Info->ProcessName); #if 0 ProcessPluginList(chunkwm_export_application_terminated, Application); #else ProcessPluginListThreaded(chunkwm_export_application_terminated, Application); #endif RemoveAndDestroyApplication(Application); } EndCarbonApplicationDetails(Info); } CHUNKWM_CALLBACK(Callback_ChunkWM_ApplicationActivated) { workspace_application_details *Info = (workspace_application_details *) Event->Context; ASSERT(Info); macos_application *Application = GetApplicationFromPID(Info->PID); if (Application) { c_log(C_LOG_LEVEL_DEBUG, "%d:%s activated\n", Info->PID, Info->ProcessName); #if 0 ProcessPluginList(chunkwm_export_application_activated, Application); #else ProcessPluginListThreaded(chunkwm_export_application_activated, Application); #endif } EndWorkspaceApplicationDetails(Info); } CHUNKWM_CALLBACK(Callback_ChunkWM_ApplicationDeactivated) { workspace_application_details *Info = (workspace_application_details *) Event->Context; ASSERT(Info); macos_application *Application = GetApplicationFromPID(Info->PID); if (Application) { c_log(C_LOG_LEVEL_DEBUG, "%d:%s deactivated\n", Info->PID, Info->ProcessName); #if 0 ProcessPluginList(chunkwm_export_application_deactivated, Application); #else ProcessPluginListThreaded(chunkwm_export_application_deactivated, Application); #endif } EndWorkspaceApplicationDetails(Info); } CHUNKWM_CALLBACK(Callback_ChunkWM_ApplicationVisible) { workspace_application_details *Info = (workspace_application_details *) Event->Context; ASSERT(Info); macos_application *Application = GetApplicationFromPID(Info->PID); if (Application) { c_log(C_LOG_LEVEL_DEBUG, "%d:%s visible\n", Info->PID, Info->ProcessName); #if 0 ProcessPluginList(chunkwm_export_application_unhidden, Application); #else ProcessPluginListThreaded(chunkwm_export_application_unhidden, Application); #endif } EndWorkspaceApplicationDetails(Info); } CHUNKWM_CALLBACK(Callback_ChunkWM_ApplicationHidden) { workspace_application_details *Info = (workspace_application_details *) Event->Context; ASSERT(Info); macos_application *Application = GetApplicationFromPID(Info->PID); if (Application) { c_log(C_LOG_LEVEL_DEBUG, "%d:%s hidden\n", Info->PID, Info->ProcessName); #if 0 ProcessPluginList(chunkwm_export_application_hidden, Application); #else ProcessPluginListThreaded(chunkwm_export_application_hidden, Application); #endif } EndWorkspaceApplicationDetails(Info); } CHUNKWM_CALLBACK(Callback_ChunkWM_SpaceChanged) { /* NOTE(koekeishiya): This event does not take an argument. */ ASSERT(Event->Context == NULL); /* * NOTE(koekeishiya): Applications that are not on our focused space fails to have their * existing windows added to our windw collection. We must force update our collection on * every space change. Windows that are already tracked is NOT added multiple times. */ UpdateWindowCollection(); #if 0 ProcessPluginList(chunkwm_export_space_changed, NULL); #else ProcessPluginListThreaded(chunkwm_export_space_changed, NULL); #endif } // NOTE(koekeishiya): Display-related callbacks CHUNKWM_CALLBACK(Callback_ChunkWM_DisplayAdded) { CGDirectDisplayID *DisplayId = (CGDirectDisplayID *) Event->Context; ASSERT(DisplayId); c_log(C_LOG_LEVEL_DEBUG, "%d: display added\n", *DisplayId); #if 0 ProcessPluginList(chunkwm_export_display_added, DisplayId); #else ProcessPluginListThreaded(chunkwm_export_display_added, DisplayId); #endif free(DisplayId); } CHUNKWM_CALLBACK(Callback_ChunkWM_DisplayRemoved) { CGDirectDisplayID *DisplayId = (CGDirectDisplayID *) Event->Context; ASSERT(DisplayId); c_log(C_LOG_LEVEL_DEBUG, "%d: display removed\n", *DisplayId); #if 0 ProcessPluginList(chunkwm_export_display_removed, DisplayId); #else ProcessPluginListThreaded(chunkwm_export_display_removed, DisplayId); #endif free(DisplayId); } CHUNKWM_CALLBACK(Callback_ChunkWM_DisplayMoved) { CGDirectDisplayID *DisplayId = (CGDirectDisplayID *) Event->Context; ASSERT(DisplayId); c_log(C_LOG_LEVEL_DEBUG, "%d: display moved\n", *DisplayId); #if 0 ProcessPluginList(chunkwm_export_display_moved, DisplayId); #else ProcessPluginListThreaded(chunkwm_export_display_moved, DisplayId); #endif free(DisplayId); } CHUNKWM_CALLBACK(Callback_ChunkWM_DisplayResized) { CGDirectDisplayID *DisplayId = (CGDirectDisplayID *) Event->Context; ASSERT(DisplayId); c_log(C_LOG_LEVEL_DEBUG, "%d: display resolution changed\n", *DisplayId); #if 0 ProcessPluginList(chunkwm_export_display_resized, DisplayId); #else ProcessPluginListThreaded(chunkwm_export_display_resized, DisplayId); #endif free(DisplayId); } CHUNKWM_CALLBACK(Callback_ChunkWM_DisplayChanged) { /* NOTE(koekeishiya): This event does not take an argument. */ ASSERT(Event->Context == NULL); /* * NOTE(koekeishiya): Applications that are not on our focused space fails to have their * existing windows added to our windw collection. We must force update our collection on * every space change. Windows that are already tracked is NOT added multiple times. */ UpdateWindowCollection(); #if 0 ProcessPluginList(chunkwm_export_space_changed, NULL); #else ProcessPluginListThreaded(chunkwm_export_display_changed, NULL); #endif } // NOTE(koekeishiya): Window-related callbacks CHUNKWM_CALLBACK(Callback_ChunkWM_WindowCreated) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); if (AddWindowToCollection(Window)) { c_log(C_LOG_LEVEL_DEBUG, "%s:%s%d window created\n", Window->Owner->Name, Window->Name, Window->Id); #if 0 ProcessPluginList(chunkwm_export_window_created, Window); #else ProcessPluginListThreaded(chunkwm_export_window_created, Window); #endif /* * NOTE(koekeishiya): When a new window is created, we incorrectly * receive the kAXFocusedWindowChangedNotification first, We discard * that notification and restore it when we have the window to work with. */ ConstructEvent(ChunkWM_WindowFocused, Window); } else { c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window is not destructible, ignore!\n", Window->Owner->Name, Window->Name, Window->Id); AXLibRemoveObserverNotification(&Window->Owner->Observer, Window->Ref, kAXUIElementDestroyedNotification); AXLibDestroyWindow(Window); } } CHUNKWM_CALLBACK(Callback_ChunkWM_WindowDestroyed) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window destroyed\n", Window->Owner->Name, Window->Name, Window->Id); #if 0 ProcessPluginList(chunkwm_export_window_destroyed, Window); #else ProcessPluginListThreaded(chunkwm_export_window_destroyed, Window); #endif AXLibDestroyWindow(Window); } CHUNKWM_CALLBACK(Callback_ChunkWM_WindowFocused) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); uint32_t Flags = Window->Flags; bool Result = __sync_bool_compare_and_swap(&Window->Flags, Flags, Flags); if (Result && !AXLibHasFlags(Window, Window_Invalid)) { /* * NOTE(koekeishiya): When a window is deminimized, we receive this notification before * the deminimized notification (window is not yet visible). Skip this notification and * post it after a 'ChunkWM_WindowDeminimized' event has been processed. */ if (!AXLibHasFlags(Window, Window_Minimized)) { c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window focused\n", Window->Owner->Name, Window->Name, Window->Id); #if 0 ProcessPluginList(chunkwm_export_window_focused, Window); #else ProcessPluginListThreaded(chunkwm_export_window_focused, Window); #endif } } else { c_log(C_LOG_LEVEL_DEBUG, "chunkwm:%s: __sync_bool_compare_and_swap failed\n", __FUNCTION__); } } CHUNKWM_CALLBACK(Callback_ChunkWM_WindowMoved) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); uint32_t Flags = Window->Flags; bool Result = __sync_bool_compare_and_swap(&Window->Flags, Flags, Flags); if (Result && !AXLibHasFlags(Window, Window_Invalid)) { Window->Position = AXLibGetWindowPosition(Window->Ref); c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window moved\n", Window->Owner->Name, Window->Name, Window->Id); #if 0 ProcessPluginList(chunkwm_export_window_moved, Window); #else ProcessPluginListThreaded(chunkwm_export_window_moved, Window); #endif } else { c_log(C_LOG_LEVEL_DEBUG, "chunkwm:%s: __sync_bool_compare_and_swap failed\n", __FUNCTION__); } } CHUNKWM_CALLBACK(Callback_ChunkWM_WindowResized) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); uint32_t Flags = Window->Flags; bool Result = __sync_bool_compare_and_swap(&Window->Flags, Flags, Flags); if (Result && !AXLibHasFlags(Window, Window_Invalid)) { Window->Position = AXLibGetWindowPosition(Window->Ref); Window->Size = AXLibGetWindowSize(Window->Ref); c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window resized\n", Window->Owner->Name, Window->Name, Window->Id); #if 0 ProcessPluginList(chunkwm_export_window_resized, Window); #else ProcessPluginListThreaded(chunkwm_export_window_resized, Window); #endif } else { c_log(C_LOG_LEVEL_DEBUG, "chunkwm:%s: __sync_bool_compare_and_swap failed\n", __FUNCTION__); } } CHUNKWM_CALLBACK(Callback_ChunkWM_WindowMinimized) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); uint32_t Flags = Window->Flags; bool Result = __sync_bool_compare_and_swap(&Window->Flags, Flags, Flags); if (Result && !AXLibHasFlags(Window, Window_Invalid)) { c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window minimized\n", Window->Owner->Name, Window->Name, Window->Id); AXLibAddFlags(Window, Window_Minimized); #if 0 ProcessPluginList(chunkwm_export_window_minimized, Window); #else ProcessPluginListThreaded(chunkwm_export_window_minimized, Window); #endif } else { c_log(C_LOG_LEVEL_DEBUG, "chunkwm:%s: __sync_bool_compare_and_swap failed\n", __FUNCTION__); } } CHUNKWM_CALLBACK(Callback_ChunkWM_WindowDeminimized) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); uint32_t Flags = Window->Flags; bool Result = __sync_bool_compare_and_swap(&Window->Flags, Flags, Flags); if (Result && !AXLibHasFlags(Window, Window_Invalid)) { if (AXLibHasFlags(Window, Window_Init_Minimized)) { if (Window->Mainrole) { CFRelease(Window->Mainrole); AXLibGetWindowRole(Window->Ref, &Window->Mainrole); } if (Window->Subrole) { CFRelease(Window->Subrole); AXLibGetWindowSubrole(Window->Ref, &Window->Subrole); } AXLibClearFlags(Window, Window_Init_Minimized); } c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window deminimized\n", Window->Owner->Name, Window->Name, Window->Id); AXLibClearFlags(Window, Window_Minimized); #if 0 ProcessPluginList(chunkwm_export_window_deminimized, Window); #else ProcessPluginListThreaded(chunkwm_export_window_deminimized, Window); #endif /* * NOTE(koekeishiya): When a window is deminimized, we incorrectly * receive the kAXFocusedWindowChangedNotification first, We discard * that notification and restore it when we have the window to work with. */ ConstructEvent(ChunkWM_WindowFocused, Window); } else { c_log(C_LOG_LEVEL_DEBUG, "chunkwm:%s: __sync_bool_compare_and_swap failed\n", __FUNCTION__); } } CHUNKWM_CALLBACK(Callback_ChunkWM_WindowSheetCreated) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window sheet created\n", Window->Owner->Name, Window->Name, Window->Id); #if 0 ProcessPluginList(chunkwm_export_window_sheet_created, Window); #else ProcessPluginListThreaded(chunkwm_export_window_sheet_created, Window); #endif AXLibDestroyWindow(Window); } /* * NOTE(koekeishiya): If a plugin has stored a pointer to our macos_window structs * and tries to access the 'name' member outside of 'PLUGIN_MAIN_FUNC', there will * be a race condition. Doing so is considered an error.. */ CHUNKWM_CALLBACK(Callback_ChunkWM_WindowTitleChanged) { macos_window *Window = (macos_window *) Event->Context; ASSERT(Window); uint32_t Flags = Window->Flags; bool Result = __sync_bool_compare_and_swap(&Window->Flags, Flags, Flags); if (Result && !AXLibHasFlags(Window, Window_Invalid)) { UpdateWindowTitle(Window); c_log(C_LOG_LEVEL_DEBUG, "%s:%s:%d window title changed\n", Window->Owner->Name, Window->Name, Window->Id); #if 0 ProcessPluginList(chunkwm_export_window_title_changed, Window); #else ProcessPluginListThreaded(chunkwm_export_window_title_changed, Window); #endif } else { c_log(C_LOG_LEVEL_DEBUG, "chunkwm:%s: __sync_bool_compare_and_swap failed\n", __FUNCTION__); } }
[ "aasvi93@hotmail.com" ]
aasvi93@hotmail.com
66ee7bff0f302796af826a87b2df9f2f697dfc05
ac2732913ca89a14ac92ab6e516701bd3ac277eb
/Assignment_7/assn_7.cpp
ef9f7868e272eca26262301f6d685a724bc87585
[]
no_license
kundankabra/Object-Oriented-Programming
c414e45b22a574280dc138fd431492dd361afc67
d92c13078f2bb061cf42410bcac10b364177c5e9
refs/heads/master
2023-01-22T21:59:18.545706
2020-12-07T15:03:48
2020-12-07T15:03:48
225,531,991
0
0
null
null
null
null
UTF-8
C++
false
false
941
cpp
#include<iostream> #include<list> using namespace std; void display(list<int> &l) { list<int>::iterator itr; for(itr=l.begin();itr!=l.end();++itr) { cout<<*itr<<"\t"; } cout<<endl; } int main() { list <int> l1; list<int> l2(5); int no,value; cout<<"Enter the no of elements in list 1: "; cin>>no; cout<<"Enter the values"<<endl; int i; for(i=0;i<no;i++){ cin>>value; l1.push_back(value); } display(l1); list<int>::iterator itr2; i=1; for(itr2=l2.begin();itr2!=l2.end();++itr2) { *itr2=i*2; i++; } cout<<"List 1 element are:"<<endl; display(l1); cout<<"List 2 element are:"<<endl; display(l2); list<int>listA,listB; listA=l1; listB=l2; l1.merge(l2); cout<<"Merge unsorted list:"<<endl; display(l1); listA.sort(); listB.sort(); listA.merge(listB); cout<<"Merge sorted list:"<<endl; display(listA); cout<<"Reverse list:"<<endl; listA.reverse(); display(listA); return 0; }
[ "kundan.21810729@viit.ac.in" ]
kundan.21810729@viit.ac.in
f100bf598793b975a47c81e07d17b931a0590fca
3943f4014015ae49a2c6c3c7018afd1d2119a7ed
/final_output/output_recur_large_cp/laguerre_formula_-10000.000000_10000.000000/8-19.cpp
2a774955d23c476c27862aec1dc31a5194ffe04f
[]
no_license
Cathy272272272/practicum
9fa7bfcccc23d4e40af9b647d9d98f5ada37aecf
e13ab8aa5cf5c037245b677453e14b586b10736d
refs/heads/master
2020-05-23T10:10:15.111847
2019-06-08T00:23:57
2019-06-08T00:23:57
186,689,468
0
0
null
null
null
null
UTF-8
C++
false
false
2,307
cpp
#include <iostream> #include <stdio.h> #include <assert.h> #include <math.h> extern "C" { #include "quadmath.h" } #ifndef IFT #define IFT float #endif #ifndef OFT #define OFT __float128 #endif template <class _Real> _Real __libcpp_generalized_laguerre_recurrence(unsigned __n,_Real __x) { if (__n == 0u) return _Real(1); _Real __delta = _Real(0) - __x; _Real __li = _Real(1) + _Real(0); const _Real __alpham1 = _Real(0) - _Real(1); for (unsigned __i = 2; __i <= __n; ++__i) { __delta = (__delta * (_Real(__i) + __alpham1) - __x * __li) / _Real(__i); __li += __delta; } return __li; } using namespace std; static const int k = 3; int main (int argc, char *argv[]) { assert(argc == 3); char *iname = argv[1]; char *oname = argv[2]; FILE *ifile = fopen(iname, "r"); FILE *ofile = fopen(oname, "w"); assert(ifile != NULL && ofile != NULL); fseek(ifile, 0, SEEK_END); unsigned long fsize = ftell(ifile); assert(fsize == (sizeof(IFT) * 1)); fseek(ifile, 0, SEEK_SET); IFT in_x; fread(&in_x, sizeof(IFT), 1, ifile); FT rel = 0; FT x = in_x; #ifdef ORIG rel = __libcpp_generalized_laguerre_recurrence(19, x + 0.0); #else rel = ( ( ( ( ( ( ( ( ( ( ( ( ( 1.0+ ( -19.0*x ) ) + ( 85.5* ( x*x ) ) ) + ( ( -161.5* ( x*x ) ) *x ) ) + ( 161.5* ( ( ( x*x ) *x ) *x ) ) ) + ( -96.9* ( ( ( ( x*x ) *x ) *x ) *x ) ) ) + ( 37.683333* ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) ) ) + ( -9.997619* ( ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) *x ) ) ) + ( 1.874554* ( ( ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) *x ) *x ) ) ) + ( -0.254569* ( ( ( ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) ) ) + ( 0.025457* ( ( ( ( ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) ) ) + ( -0.001893* ( ( ( ( ( ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) ) ) + ( 0.000105* ( ( ( ( ( ( ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) ) ) + ( -4e-06* ( ( ( ( ( ( ( ( ( ( ( ( x*x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) *x ) ) ) ; #endif OFT outv = rel; fwrite(&outv, sizeof(OFT), 1, ofile); fclose(ifile); fclose(ofile); return 0; }
[ "cathyxu@Cathys-MacBook-Pro.local" ]
cathyxu@Cathys-MacBook-Pro.local
8925eadacc7aff0b22efc4c6f7efea79399eb9cb
7bbf74f5114cf2298bc2f6c6ce01269fb255fca9
/4-5/studi.h
40d5b52e712ba6c5cb7292e6f67132d2ba5b30ea
[]
no_license
Helagoes/OOP_BJM
1267c0d594d6f9a3680080070156c4265d1ff8d5
f1632905eb8dba652ac8d0795cf454e587216826
refs/heads/master
2020-05-01T09:12:37.467816
2019-06-19T12:35:24
2019-06-19T12:35:24
177,394,672
0
0
null
null
null
null
UTF-8
C++
false
false
698
h
#ifndef _STUDI #define _STUDI #include <cstdlib> #include <iostream> #include <stdexcept> #include <fstream> class studi { public: bool in(std::string, size_t); //getter long g_matnr() const { return this->matnr; } std::string g_vorname() const { return this->vorname; } std::string g_nachname() const { return this->nachname; } //setter void s_matnr(long value) { this->matnr = value; } void s_vorname(std::string value) { this->vorname = value; } void s_nachname(std::string value) { this->nachname = value; } private: long matnr; std::string vorname; std::string nachname; }; std::ostream& operator<<(std::ostream&, const studi); bool operator>>(std::ifstream&, studi&); #endif
[ "noreply@github.com" ]
Helagoes.noreply@github.com
8c2d504668574875eb82246b19a522010cb71ada
bdbbc611761582b173c08a2cae6a9a355feaee9a
/C++ Project/class_construct_test/b.cpp
1eabed370d93fcba667aa35cbef87348e60c31ad
[]
no_license
lssxfy123/C-study
a79f043fab25d597c3bc19748600857e3ee3f9de
e88632838251dfb3947d2dd95423c66f409ee80e
refs/heads/master
2022-02-05T02:30:46.475740
2022-01-23T14:00:59
2022-01-23T14:00:59
41,584,370
0
0
null
null
null
null
GB18030
C++
false
false
463
cpp
#include "b.h" #include <iostream> // 注意,这里构造函数的形参应定义为引用类型,如果定义为普通类型的i, // 用其初始化引用ref后,构造函数执行完毕后,i会析构掉,引用ref的值就会是未知的随机数 B::B(int& i):ten(10), ref(i), a(i) { std::cout << "调用B构造函数" << std::endl; } B::~B() { } void B::PrintValue() { std::cout << ten << std::endl; std::cout << ref << std::endl; }
[ "liushenshenxfy@126.com" ]
liushenshenxfy@126.com
5cf33c0d130190c230369a0b65f3cfce3c2435aa
d203c7d37391ad12209d279368de397660b1b9a3
/8.c
b96f62302b65628c03c08d1a88b280e09a36b6df
[]
no_license
baswojuvishal/c-programming-3
8e2adf75e490ccf94fee66fdef1543c027ad0c30
23b5da87a955e825321f51c40ffb0bdaa8c18a23
refs/heads/master
2020-09-28T14:55:02.676157
2019-12-09T06:28:41
2019-12-09T06:28:41
226,800,574
0
0
null
null
null
null
UTF-8
C++
false
false
114
c
#include<stdio.h> int main() { int a=10,b=10; printf("a<<2=%d",a<<2); printf("b>>2=%d",b>>2); return 0; }
[ "noreply@github.com" ]
baswojuvishal.noreply@github.com
d8eb25c20dcc5d173b72602c11b12369d5d28ea1
1f5079b24785a0e6a8bef1f15e1bca939e94ba56
/Dev/C++/Mascaret/src/Tools/Network/HttpServer/httpResponse.cpp
460bf00699b3a98fdb2f8e8e7bed90985ca60623
[]
no_license
querrec/Mascaret
7d5d0628dfb93226a602f79a7a974c14a60a88e8
c71eba3667b3e3fa8a0b18a1f40219aee358c968
refs/heads/master
2021-01-17T08:12:10.024097
2016-04-14T13:27:52
2016-04-14T13:27:52
25,727,699
0
5
null
null
null
null
UTF-8
C++
false
false
2,998
cpp
#include <boost/asio.hpp> #include <boost/date_time/posix_time/posix_time.hpp> #include <boost/date_time/time_facet.hpp> #include "httpServer/httpResponse.h" #include <sstream> using std::string; using std::map; using std::ostringstream; HttpResponse::HttpResponse() { _isCommited=false; reset(); } HttpResponse::~HttpResponse() { } void HttpResponse::flushBuffer() { if(!_isCommited) { _isCommited=true; try{ boost::asio::write(*_socket,boost::asio::buffer(getFormattedStringResponse())); } catch(...) { return;} } else { boost::asio::write(*_socket,boost::asio::buffer(_buffer)); } _buffer=""; } void HttpResponse::reset() { if(!_isCommited) { _buffer=""; _headers.clear(); _headers["Content-Type"]="text/html"; _cookies.clear(); _status=200; } } string HttpResponse::getFormattedStringResponse() { ostringstream _ostream; _ostream << "HTTP/1.1 " << _status << " " << getMessageFromStatus() << "\r\n"; map<string,string>::iterator i = _headers.begin(); while(i != _headers.end()) { _ostream << i->first << ": " << i->second << "\r\n"; i++; } if(!_cookies.empty()) _ostream << "Set-Cookie: "; for(size_t j=0;j<_cookies.size();j++) { if(j > 0) _ostream << ";"; _ostream <<_cookies[j].getName() << "=" << _cookies[j].getValue(); if(_cookies[j].getExpires() != 0) { using namespace boost::gregorian; using namespace boost::posix_time; ptime now=microsec_clock::universal_time(); ptime expires=now + minutes(_cookies[j].getExpires()); time_facet* tf = new time_facet("%a, %d-%b-%Y %H:%M:%S GMT"); _ostream.imbue(std::locale(std::cout.getloc(), tf)); _ostream << "; expires= " << expires; } } if(!_cookies.empty()) _ostream << "\r\n"; _ostream << "\r\n"; _ostream << _buffer; _isCommited=true; return _ostream.str(); } void HttpResponse::write(long l) { ostringstream valStr; valStr << l; _buffer+=valStr.str(); } void HttpResponse::write(int i) { ostringstream valStr; valStr << i; _buffer+=valStr.str(); } void HttpResponse::write(const string& content) { _buffer+=content; } string HttpResponse::getMessageFromStatus() { switch(_status) { case 200: return "OK"; case 201: return "CREATED"; case 202: return "CREATED"; case 203: return "PARTIAL INFORMATION"; case 204: return "NO RESPONSE"; case 205: return "RESET CONTENT"; case 206: return "PARTIAL CONTENT"; case 301: return "MOVED"; case 302: return "FOUND"; case 303: return "METHOD"; case 304: return "NOT MODIFIED"; case 400: return "BAD REQUEST"; case 401: return "UNAUTHORIZED"; case 402: return "PAYMENT REQUIRED"; case 403: return "FORBIDDEN"; case 404: return "NOT FOUND"; case 500: return "INTERNAL ERROR"; case 501: return "NOT IMPLEMENTED"; case 502: return "BAD GATEWAY"; case 503: return "SERVICE UNAVAILABLE"; case 504: return "GATEWAY TIMEOUT"; } return "UNKNOW"; }
[ "querrec@querrecPortable.(none)" ]
querrec@querrecPortable.(none)
9f891c0dbc4bf1e3e04e86200d63b60eb4260f9a
73cfd700522885a3fec41127e1f87e1b78acd4d3
/_Include/boost/spirit/home/classic/iterator/position_iterator_fwd.hpp
c67c6aef05f9dfff4fee3b2a6132462b409a9a38
[]
no_license
pu2oqa/muServerDeps
88e8e92fa2053960671f9f57f4c85e062c188319
92fcbe082556e11587887ab9d2abc93ec40c41e4
refs/heads/master
2023-03-15T12:37:13.995934
2019-02-04T10:07:14
2019-02-04T10:07:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
2,223
hpp
//////////////////////////////////////////////////////////////////////////////// // position_iterator_fwd.hpp /*============================================================================= Copyright (c) 2006 Tobias Schwinger Copyright (c) 2002-2006 Hartmut Kaiser http://spirit.sourceforge.net/ Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt) =============================================================================*/ #if !defined(BOOST_SPIRIT_POSITION_ITERATOR_FWD_HPP) #define BOOST_SPIRIT_POSITION_ITERATOR_FWD_HPP #include <string> #include <boost/detail/iterator.hpp> // for boost::detail::iterator_traits #include <boost/spirit/home/classic/namespace.hpp> #include <boost/spirit/home/classic/core/nil.hpp> namespace boost { namespace spirit { BOOST_SPIRIT_CLASSIC_NAMESPACE_BEGIN template <typename String = std::string> struct file_position_base; typedef file_position_base<std::string> file_position; template <typename String = std::string> struct file_position_without_column_base; typedef file_position_without_column_base<std::string> file_position_without_column; template < typename ForwardIteratorT, typename PositionT = file_position_base< std::basic_string< typename boost::detail::iterator_traits<ForwardIteratorT>::value_type > >, typename SelfT = nil_t > class position_iterator; template < typename ForwardIteratorT, typename PositionT = file_position_base< std::basic_string< typename boost::detail::iterator_traits<ForwardIteratorT>::value_type > > > class position_iterator2; template <typename PositionT> class position_policy; BOOST_SPIRIT_CLASSIC_NAMESPACE_END }} // namespace BOOST_SPIRIT_CLASSIC_NS #endif ///////////////////////////////////////////////// // vnDev.Games - Trong.LIVE - DAO VAN TRONG // ////////////////////////////////////////////////////////////////////////////////
[ "langley.joshua@gmail.com" ]
langley.joshua@gmail.com
6ebb8a93881130abe0db76a771373fb47afc3482
bc3f4abb517829c60f846e5cd9787ac61def945b
/cpp_boost/boost/boost/geometry/algorithms/detail/buffer/buffer_inserter.hpp
eac044b7a84b56cedae354827db624d868ddab09
[]
no_license
ngzHappy/cpc2
f3a7a0082e7ab3bd995820384c938ef6f1904a34
2830d68fec95ba0afeabd9469e919f8e6deb41b3
refs/heads/master
2020-12-25T17:24:17.726694
2016-08-08T13:40:06
2016-08-08T13:40:07
58,794,358
0
0
null
null
null
null
UTF-8
C++
false
false
32,670
hpp
// Boost.Geometry (aka GGL, Generic Geometry Library) // Copyright (c) 2012-2014 Barend Gehrels, Amsterdam, the Netherlands. // Use, modification and distribution is subject to the Boost Software License, // Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at // http://www.boost.org/LICENSE_1_0.txt) #ifndef BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_INSERTER_HPP #define BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_INSERTER_HPP #include <cstddef> #include <iterator> #include <boost/core/ignore_unused.hpp> #include <boost/numeric/conversion/cast.hpp> #include <boost/range.hpp> #include <boost/geometry/core/assert.hpp> #include <boost/geometry/core/closure.hpp> #include <boost/geometry/core/exterior_ring.hpp> #include <boost/geometry/core/interior_rings.hpp> #include <boost/geometry/util/condition.hpp> #include <boost/geometry/util/math.hpp> #include <boost/geometry/strategies/buffer.hpp> #include <boost/geometry/strategies/side.hpp> #include <boost/geometry/algorithms/detail/buffer/buffered_piece_collection.hpp> #include <boost/geometry/algorithms/detail/buffer/line_line_intersection.hpp> #include <boost/geometry/algorithms/detail/buffer/parallel_continue.hpp> #include <boost/geometry/algorithms/assign.hpp> #include <boost/geometry/algorithms/num_interior_rings.hpp> #include <boost/geometry/algorithms/simplify.hpp> #include <boost/geometry/views/detail/normalized_view.hpp> #if defined(BOOST_GEOMETRY_BUFFER_SIMPLIFY_WITH_AX) #include <boost/geometry/strategies/cartesian/distance_projected_point_ax.hpp> #endif namespace boost { namespace geometry { #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace buffer { template <typename Range, typename DistanceStrategy> inline void simplify_input(Range const& range, DistanceStrategy const& distance, Range& simplified) { // We have to simplify the ring before to avoid very small-scaled // features in the original (convex/concave/convex) being enlarged // in a very large scale and causing issues (IP's within pieces). // This might be reconsidered later. Simplifying with a very small // distance (1%% of the buffer) will never be visible in the result, // if it is using round joins. For miter joins they are even more // sensitive to small scale input features, however the result will // look better. // It also gets rid of duplicate points #if ! defined(BOOST_GEOMETRY_BUFFER_SIMPLIFY_WITH_AX) geometry::simplify(range, simplified, distance.simplify_distance()); #else typedef typename boost::range_value<Range>::type point_type; typedef strategy::distance::detail::projected_point_ax<> ax_type; typedef typename strategy::distance::services::return_type < strategy::distance::detail::projected_point_ax<>, point_type, point_type >::type return_type; typedef strategy::distance::detail::projected_point_ax_less < return_type > comparator_type; typedef strategy::simplify::detail::douglas_peucker < point_type, strategy::distance::detail::projected_point_ax<>, comparator_type > dp_ax; return_type max_distance(distance.simplify_distance() * 2.0, distance.simplify_distance()); comparator_type comparator(max_distance); dp_ax strategy(comparator); geometry::simplify(range, simplified, max_distance, strategy); #endif if (boost::size(simplified) == 2 && geometry::equals(geometry::range::front(simplified), geometry::range::back(simplified))) { traits::resize<Range>::apply(simplified, 1); } } template <typename RingOutput> struct buffer_range { typedef typename point_type<RingOutput>::type output_point_type; typedef typename coordinate_type<RingOutput>::type coordinate_type; template < typename Collection, typename Point, typename DistanceStrategy, typename JoinStrategy, typename EndStrategy, typename RobustPolicy > static inline void add_join(Collection& collection, Point const& penultimate_input, Point const& previous_input, output_point_type const& prev_perp1, output_point_type const& prev_perp2, Point const& input, output_point_type const& perp1, output_point_type const& perp2, strategy::buffer::buffer_side_selector side, DistanceStrategy const& distance, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, RobustPolicy const& ) { output_point_type intersection_point; geometry::assign_zero(intersection_point); strategy::buffer::join_selector join = get_join_type(penultimate_input, previous_input, input); if (join == strategy::buffer::join_convex) { // Calculate the intersection-point formed by the two sides. // It might be that the two sides are not convex, but continue // or spikey, we then change the join-type join = line_line_intersection::apply( perp1, perp2, prev_perp1, prev_perp2, intersection_point); } switch(join) { case strategy::buffer::join_continue : // No join, we get two consecutive sides break; case strategy::buffer::join_concave : { std::vector<output_point_type> range_out; range_out.push_back(prev_perp2); range_out.push_back(previous_input); collection.add_piece(strategy::buffer::buffered_concave, previous_input, range_out); range_out.clear(); range_out.push_back(previous_input); range_out.push_back(perp1); collection.add_piece(strategy::buffer::buffered_concave, previous_input, range_out); } break; case strategy::buffer::join_spike : { // For linestrings, only add spike at one side to avoid // duplicates std::vector<output_point_type> range_out; end_strategy.apply(penultimate_input, prev_perp2, previous_input, perp1, side, distance, range_out); collection.add_endcap(end_strategy, range_out, previous_input); collection.set_current_ring_concave(); } break; case strategy::buffer::join_convex : { // The corner is convex, we create a join // TODO (future) - avoid a separate vector, add the piece directly std::vector<output_point_type> range_out; if (join_strategy.apply(intersection_point, previous_input, prev_perp2, perp1, distance.apply(previous_input, input, side), range_out)) { collection.add_piece(strategy::buffer::buffered_join, previous_input, range_out); } } break; } } static inline strategy::buffer::join_selector get_join_type( output_point_type const& p0, output_point_type const& p1, output_point_type const& p2) { typedef typename strategy::side::services::default_strategy < typename cs_tag<output_point_type>::type >::type side_strategy; int const side = side_strategy::apply(p0, p1, p2); return side == -1 ? strategy::buffer::join_convex : side == 1 ? strategy::buffer::join_concave : parallel_continue ( get<0>(p2) - get<0>(p1), get<1>(p2) - get<1>(p1), get<0>(p1) - get<0>(p0), get<1>(p1) - get<1>(p0) ) ? strategy::buffer::join_continue : strategy::buffer::join_spike; } template < typename Collection, typename Iterator, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename RobustPolicy > static inline strategy::buffer::result_code iterate(Collection& collection, Iterator begin, Iterator end, strategy::buffer::buffer_side_selector side, DistanceStrategy const& distance_strategy, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, RobustPolicy const& robust_policy, output_point_type& first_p1, output_point_type& first_p2, output_point_type& last_p1, output_point_type& last_p2) { boost::ignore_unused(side_strategy); typedef typename std::iterator_traits < Iterator >::value_type point_type; point_type second_point, penultimate_point, ultimate_point; // last two points from begin/end /* * last.p1 last.p2 these are the "previous (last) perpendicular points" * -------------- * | | * *------------*____ <- *prev * pup | | p1 "current perpendicular point 1" * | | * | | this forms a "side", a side is a piece * | | * *____| p2 * * ^ * *it * * pup: penultimate_point */ strategy::buffer::result_code result = strategy::buffer::result_no_output; bool first = true; Iterator it = begin; std::vector<output_point_type> generated_side; generated_side.reserve(2); for (Iterator prev = it++; it != end; ++it) { generated_side.clear(); strategy::buffer::result_code error_code = side_strategy.apply(*prev, *it, side, distance_strategy, generated_side); if (error_code == strategy::buffer::result_no_output) { // Because input is simplified, this is improbable, // but it can happen for degenerate geometries // Further handling of this side is skipped continue; } else if (error_code == strategy::buffer::result_error_numerical) { return error_code; } BOOST_GEOMETRY_ASSERT(! generated_side.empty()); result = strategy::buffer::result_normal; if (! first) { add_join(collection, penultimate_point, *prev, last_p1, last_p2, *it, generated_side.front(), generated_side.back(), side, distance_strategy, join_strategy, end_strategy, robust_policy); } collection.add_side_piece(*prev, *it, generated_side, first); penultimate_point = *prev; ultimate_point = *it; last_p1 = generated_side.front(); last_p2 = generated_side.back(); prev = it; if (first) { first = false; second_point = *it; first_p1 = generated_side.front(); first_p2 = generated_side.back(); } } return result; } }; template < typename Multi, typename PolygonOutput, typename Policy > struct buffer_multi { template < typename Collection, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > static inline void apply(Multi const& multi, Collection& collection, DistanceStrategy const& distance_strategy, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy) { for (typename boost::range_iterator<Multi const>::type it = boost::begin(multi); it != boost::end(multi); ++it) { Policy::apply(*it, collection, distance_strategy, side_strategy, join_strategy, end_strategy, point_strategy, robust_policy); } } }; struct visit_pieces_default_policy { template <typename Collection> static inline void apply(Collection const&, int) {} }; template < typename OutputPointType, typename Point, typename Collection, typename DistanceStrategy, typename PointStrategy > inline void buffer_point(Point const& point, Collection& collection, DistanceStrategy const& distance_strategy, PointStrategy const& point_strategy) { collection.start_new_ring(); std::vector<OutputPointType> range_out; point_strategy.apply(point, distance_strategy, range_out); collection.add_piece(strategy::buffer::buffered_point, range_out, false); collection.set_piece_center(point); collection.finish_ring(strategy::buffer::result_normal); } }} // namespace detail::buffer #endif // DOXYGEN_NO_DETAIL #ifndef DOXYGEN_NO_DISPATCH namespace dispatch { template < typename Tag, typename RingInput, typename RingOutput > struct buffer_inserter {}; template < typename Point, typename RingOutput > struct buffer_inserter<point_tag, Point, RingOutput> { template < typename Collection, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > static inline void apply(Point const& point, Collection& collection, DistanceStrategy const& distance_strategy, SideStrategy const& , JoinStrategy const& , EndStrategy const& , PointStrategy const& point_strategy, RobustPolicy const& ) { detail::buffer::buffer_point < typename point_type<RingOutput>::type >(point, collection, distance_strategy, point_strategy); } }; template < typename RingInput, typename RingOutput > struct buffer_inserter<ring_tag, RingInput, RingOutput> { typedef typename point_type<RingOutput>::type output_point_type; template < typename Collection, typename Iterator, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename RobustPolicy > static inline strategy::buffer::result_code iterate(Collection& collection, Iterator begin, Iterator end, strategy::buffer::buffer_side_selector side, DistanceStrategy const& distance_strategy, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, RobustPolicy const& robust_policy) { output_point_type first_p1, first_p2, last_p1, last_p2; typedef detail::buffer::buffer_range<RingOutput> buffer_range; strategy::buffer::result_code result = buffer_range::iterate(collection, begin, end, side, distance_strategy, side_strategy, join_strategy, end_strategy, robust_policy, first_p1, first_p2, last_p1, last_p2); // Generate closing join if (result == strategy::buffer::result_normal) { buffer_range::add_join(collection, *(end - 2), *(end - 1), last_p1, last_p2, *(begin + 1), first_p1, first_p2, side, distance_strategy, join_strategy, end_strategy, robust_policy); } // Buffer is closed automatically by last closing corner return result; } template < typename Collection, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > static inline strategy::buffer::result_code apply(RingInput const& ring, Collection& collection, DistanceStrategy const& distance, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy) { RingInput simplified; detail::buffer::simplify_input(ring, distance, simplified); strategy::buffer::result_code code = strategy::buffer::result_no_output; std::size_t n = boost::size(simplified); std::size_t const min_points = core_detail::closure::minimum_ring_size < geometry::closure<RingInput>::value >::value; if (n >= min_points) { detail::normalized_view<RingInput const> view(simplified); if (distance.negative()) { // Walk backwards (rings will be reversed afterwards) code = iterate(collection, boost::rbegin(view), boost::rend(view), strategy::buffer::buffer_side_right, distance, side_strategy, join_strategy, end_strategy, robust_policy); } else { code = iterate(collection, boost::begin(view), boost::end(view), strategy::buffer::buffer_side_left, distance, side_strategy, join_strategy, end_strategy, robust_policy); } } if (code == strategy::buffer::result_no_output && n >= 1) { // Use point_strategy to buffer degenerated ring detail::buffer::buffer_point<output_point_type> ( geometry::range::front(simplified), collection, distance, point_strategy ); } return code; } }; template < typename Linestring, typename Polygon > struct buffer_inserter<linestring_tag, Linestring, Polygon> { typedef typename ring_type<Polygon>::type output_ring_type; typedef typename point_type<output_ring_type>::type output_point_type; typedef typename point_type<Linestring>::type input_point_type; template < typename Collection, typename Iterator, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename RobustPolicy > static inline strategy::buffer::result_code iterate(Collection& collection, Iterator begin, Iterator end, strategy::buffer::buffer_side_selector side, DistanceStrategy const& distance_strategy, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, RobustPolicy const& robust_policy, output_point_type& first_p1) { input_point_type const& ultimate_point = *(end - 1); input_point_type const& penultimate_point = *(end - 2); // For the end-cap, we need to have the last perpendicular point on the // other side of the linestring. If it is the second pass (right), // we have it already from the first phase (left). // But for the first pass, we have to generate it output_point_type reverse_p1; if (side == strategy::buffer::buffer_side_right) { reverse_p1 = first_p1; } else { std::vector<output_point_type> generated_side; strategy::buffer::result_code code = side_strategy.apply(ultimate_point, penultimate_point, strategy::buffer::buffer_side_right, distance_strategy, generated_side); if (code != strategy::buffer::result_normal) { // No output or numerical error return code; } reverse_p1 = generated_side.front(); } output_point_type first_p2, last_p1, last_p2; strategy::buffer::result_code result = detail::buffer::buffer_range<output_ring_type>::iterate(collection, begin, end, side, distance_strategy, side_strategy, join_strategy, end_strategy, robust_policy, first_p1, first_p2, last_p1, last_p2); if (result == strategy::buffer::result_normal) { std::vector<output_point_type> range_out; end_strategy.apply(penultimate_point, last_p2, ultimate_point, reverse_p1, side, distance_strategy, range_out); collection.add_endcap(end_strategy, range_out, ultimate_point); } return result; } template < typename Collection, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > static inline strategy::buffer::result_code apply(Linestring const& linestring, Collection& collection, DistanceStrategy const& distance, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy) { Linestring simplified; detail::buffer::simplify_input(linestring, distance, simplified); strategy::buffer::result_code code = strategy::buffer::result_no_output; std::size_t n = boost::size(simplified); if (n > 1) { collection.start_new_ring(); output_point_type first_p1; code = iterate(collection, boost::begin(simplified), boost::end(simplified), strategy::buffer::buffer_side_left, distance, side_strategy, join_strategy, end_strategy, robust_policy, first_p1); if (code == strategy::buffer::result_normal) { code = iterate(collection, boost::rbegin(simplified), boost::rend(simplified), strategy::buffer::buffer_side_right, distance, side_strategy, join_strategy, end_strategy, robust_policy, first_p1); } collection.finish_ring(code); } if (code == strategy::buffer::result_no_output && n >= 1) { // Use point_strategy to buffer degenerated linestring detail::buffer::buffer_point<output_point_type> ( geometry::range::front(simplified), collection, distance, point_strategy ); } return code; } }; template < typename PolygonInput, typename PolygonOutput > struct buffer_inserter<polygon_tag, PolygonInput, PolygonOutput> { private: typedef typename ring_type<PolygonInput>::type input_ring_type; typedef typename ring_type<PolygonOutput>::type output_ring_type; typedef buffer_inserter<ring_tag, input_ring_type, output_ring_type> policy; template < typename Iterator, typename Collection, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > static inline void iterate(Iterator begin, Iterator end, Collection& collection, DistanceStrategy const& distance, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy, bool is_interior) { for (Iterator it = begin; it != end; ++it) { collection.start_new_ring(); strategy::buffer::result_code const code = policy::apply(*it, collection, distance, side_strategy, join_strategy, end_strategy, point_strategy, robust_policy); collection.finish_ring(code, is_interior); } } template < typename InteriorRings, typename Collection, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > static inline void apply_interior_rings(InteriorRings const& interior_rings, Collection& collection, DistanceStrategy const& distance, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy) { iterate(boost::begin(interior_rings), boost::end(interior_rings), collection, distance, side_strategy, join_strategy, end_strategy, point_strategy, robust_policy, true); } public: template < typename Collection, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > static inline void apply(PolygonInput const& polygon, Collection& collection, DistanceStrategy const& distance, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy) { { collection.start_new_ring(); strategy::buffer::result_code const code = policy::apply(exterior_ring(polygon), collection, distance, side_strategy, join_strategy, end_strategy, point_strategy, robust_policy); collection.finish_ring(code, false, geometry::num_interior_rings(polygon) > 0u); } apply_interior_rings(interior_rings(polygon), collection, distance, side_strategy, join_strategy, end_strategy, point_strategy, robust_policy); } }; template < typename Multi, typename PolygonOutput > struct buffer_inserter<multi_tag, Multi, PolygonOutput> : public detail::buffer::buffer_multi < Multi, PolygonOutput, dispatch::buffer_inserter < typename single_tag_of < typename tag<Multi>::type >::type, typename boost::range_value<Multi const>::type, typename geometry::ring_type<PolygonOutput>::type > > {}; } // namespace dispatch #endif // DOXYGEN_NO_DISPATCH #ifndef DOXYGEN_NO_DETAIL namespace detail { namespace buffer { template < typename GeometryOutput, typename GeometryInput, typename OutputIterator, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy, typename VisitPiecesPolicy > inline void buffer_inserter(GeometryInput const& geometry_input, OutputIterator out, DistanceStrategy const& distance_strategy, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy, VisitPiecesPolicy& visit_pieces_policy ) { boost::ignore_unused(visit_pieces_policy); typedef detail::buffer::buffered_piece_collection < typename geometry::ring_type<GeometryOutput>::type, RobustPolicy > collection_type; collection_type collection(robust_policy); collection_type const& const_collection = collection; bool const areal = boost::is_same < typename tag_cast<typename tag<GeometryInput>::type, areal_tag>::type, areal_tag >::type::value; bool const linear = boost::is_same < typename tag_cast<typename tag<GeometryInput>::type, linear_tag>::type, linear_tag >::type::value; dispatch::buffer_inserter < typename tag_cast < typename tag<GeometryInput>::type, multi_tag >::type, GeometryInput, GeometryOutput >::apply(geometry_input, collection, distance_strategy, side_strategy, join_strategy, end_strategy, point_strategy, robust_policy); collection.get_turns(); collection.classify_turns(linear); if (BOOST_GEOMETRY_CONDITION(areal)) { collection.check_remaining_points(distance_strategy); } // Visit the piece collection. This does nothing (by default), but // optionally a debugging tool can be attached (e.g. console or svg), // or the piece collection can be unit-tested // phase 0: turns (before discarded) visit_pieces_policy.apply(const_collection, 0); collection.discard_rings(); collection.block_turns(); collection.enrich(); // phase 1: turns (after enrichment/clustering) visit_pieces_policy.apply(const_collection, 1); collection.traverse(); // Reverse all offsetted rings / traversed rings if: // - they were generated on the negative side (deflate) of polygons // - the output is counter clockwise // and avoid reversing twice bool reverse = distance_strategy.negative() && areal; if (BOOST_GEOMETRY_CONDITION( geometry::point_order<GeometryOutput>::value == counterclockwise)) { reverse = ! reverse; } if (reverse) { collection.reverse(); } if (BOOST_GEOMETRY_CONDITION(distance_strategy.negative() && areal)) { collection.discard_nonintersecting_deflated_rings(); } collection.template assign<GeometryOutput>(out); // Visit collection again // phase 2: rings (after traversing) visit_pieces_policy.apply(const_collection, 2); } template < typename GeometryOutput, typename GeometryInput, typename OutputIterator, typename DistanceStrategy, typename SideStrategy, typename JoinStrategy, typename EndStrategy, typename PointStrategy, typename RobustPolicy > inline void buffer_inserter(GeometryInput const& geometry_input, OutputIterator out, DistanceStrategy const& distance_strategy, SideStrategy const& side_strategy, JoinStrategy const& join_strategy, EndStrategy const& end_strategy, PointStrategy const& point_strategy, RobustPolicy const& robust_policy) { detail::buffer::visit_pieces_default_policy visitor; buffer_inserter<GeometryOutput>(geometry_input, out, distance_strategy, side_strategy, join_strategy, end_strategy, point_strategy, robust_policy, visitor); } #endif // DOXYGEN_NO_DETAIL }} // namespace detail::buffer }} // namespace boost::geometry #endif // BOOST_GEOMETRY_ALGORITHMS_DETAIL_BUFFER_BUFFER_INSERTER_HPP
[ "819869472@qq.com" ]
819869472@qq.com
15994e722495a3f88fbd71dc9135441f8c9b7fa7
c07a44016da3ae7920d581754ea07cab54d4e6e9
/22- Trie Data Structure/maxXorpair.cpp
3156559f8a5bae832d97026c251a4f2a4714de88
[ "MIT" ]
permissive
zee-bit/C-plus-plus-Algorithms
4f8cced9695bb9e430a789767bd56dcebc6a7caf
e8351f6b54aebf6e61cbf7869fd40d19ab3b370e
refs/heads/master
2023-02-04T05:39:05.769862
2020-10-02T09:22:25
2020-10-02T09:22:25
300,564,794
0
0
MIT
2020-12-25T19:16:55
2020-10-02T09:27:02
null
UTF-8
C++
false
false
1,486
cpp
#include<iostream> #include<math.h> using namespace std; class trieNode{ public: trieNode *left; trieNode *right; }; void insert(int n, trieNode*head){ trieNode *curr= head; for(int i=31; i>=0;i--){ int bit= (n>>i)&1; if(bit==0){ if(curr->left==NULL){ curr->left= new trieNode(); } curr= curr->left; }else{ if(curr->right==NULL){ curr->right= new trieNode(); } curr= curr->left; } } } int findMaxXorpair(trieNode*head, int *arr, int n,int el){ int max_xor= INT_MIN; trieNode *curr= head; int value= el; int curr_xor=0; for(int j=31;j>=0;j--){ int b= (value>>i)&1; if(b==0){ if(curr->right!=NULL){ curr= curr->right; curr_xor+= (int)pow(2,j); } else { curr= curr->left; } }else{ if(curr->left!=NULL){ curr= curr->left; curr_xor+= (int)pow(2,j); } else { curr= curr->right; } } } if(curr_xor>max_xor) max_xor= curr_xor; reuturn max_xor; } int main(){ int n; cin>>n; int *arr= new int[n]; for(int i=0;i<n;i++){ cin>>arr[i]; } trieNode *head= new trieNode(); int result= INT_MIN; for(int i=0;i<n;i++){ insert(arr[i],head); int x= findMaxXorpair(head,arr,n,arr[i]); result = (result<x)?x:result; } cout<<result<<endl; return 0; }
[ "dev.18715@knit.ac.in" ]
dev.18715@knit.ac.in
a22053207b4e0d911187a957959022a5a4a877ed
8878071b2e73220de8d5407c16af657902e4aae1
/GitTest_01/GitTest_01/main.cpp
4a02f24fc704543e3cbe2dccd457885a10d5e25a
[]
no_license
liujun1994/ZTSS-
0462f64015a602ac29180b53d1089d336bff3346
9fe28636bb1a513a59907e4b18eb164dede0fd72
refs/heads/master
2021-07-17T21:54:44.969781
2017-10-25T07:09:28
2017-10-25T07:09:28
108,227,746
0
0
null
2017-10-25T07:09:53
2017-10-25T06:15:10
C++
UTF-8
C++
false
false
392
cpp
// // main.cpp // GitTest_01 // // Created by Admin on 17/10/25. // Copyright © 2017年 Admin. All rights reserved. // #include <iostream> using namespace std; int main(int argc, const char * argv[]) { // insert code here... cout << "Hello, World!\n"; cout<<"这是分支一的皂搓"<<endl; //删除分支1 //合拼分支1 //啦啦啦吕老师 return 0; }
[ "523274522@qq.com" ]
523274522@qq.com
a0db5124715ce358be59342d2c43b9c59ea93c9e
1ceda244af2ad34061469872691406a2c09c1a89
/Hourly.cpp
1ee37aacc5a89abe589d107ec188dbdf1682b69e
[]
no_license
klingz1/KlingsLandscapingSoftware
a5e1f48aaa190f018ae0dbc512f989c765952946
d6c284aa844438b32f576e6ef59f0ff82c2f792d
refs/heads/master
2020-05-18T08:10:41.561002
2013-10-08T04:05:14
2013-10-08T04:05:14
null
0
0
null
null
null
null
UTF-8
C++
false
false
340
cpp
#include "Hourly.h" Hourly::Hourly(string da, double pr, string des, Customer* cust, bool pa, double amtPa, string hrs, double ra) : Job(da, pr, des, cust, pa, amtPa) { hours = hrs; rate = ra; } string Hourly::toString() { ostringstream os; os << Job::toString() << ", " << hours << ", " << rate; return os.str(); }
[ "klingz1@zack---1312435.(none)" ]
klingz1@zack---1312435.(none)
3ef914d3e97bf4b2495c067c93e377bd1644802b
e818e0604894788b8e161c61fbc1051fe1eb9c04
/LINKED LIST/ll queue as ll.cpp
2eb37d5af81e279ebab11a702aaaa14ce75ea3ab
[]
no_license
RamanjaneyuluErni/Data-Structures
bae1c14241df78eeaa9677a8115ca8529948dc05
db868bc0708231ec20211350365dd692f4b7769d
refs/heads/master
2020-03-25T06:59:00.985824
2018-08-04T14:32:00
2018-08-04T14:32:00
143,535,335
0
0
null
null
null
null
UTF-8
C++
false
false
2,428
cpp
#include<iostream> using namespace std; struct queue{ int sice; int front; int rear; int element[20]; }; int dequeue(struct queue &q) {if(q.front==-1) {cout<<"queue is empty\n";} else { int t; t=q.element[q.front]; if(q.front==q.rear) {q.front=-1;q.rear=-1;} else {q.front=(q.front+1)%(q.sice);} return(t); } } void enqueue(struct queue &q,int x) {if((q.rear+1)%(q.sice)==q.front) {cout<<"queue is full\n";} else{ if(q.rear==-1){q.front=0;q.rear=0; } else{ q.rear=(q.rear+1)%q.sice;} q.element[q.rear]=x;} } void addbeg(struct queue &q1,struct queue &q2,int n) { enqueue(q2,n);int k; while(q1.front!=-1) { k=dequeue(q1); enqueue(q2,k); } } void addend(struct queue &q1,int n) { enqueue(q1,n); } void delbeg(struct queue &q1,struct queue &q2) { int p=dequeue(q1);enqueue(q2,p); } void delend(struct queue &q1) {q1.rear=(q1.rear-1)%(q1.sice); } void addafter(struct queue &q1,struct queue &q2,int p,int x) {int j; while(q1.front!=-1) { if((q1.front)%(q1.sice)==p) {enqueue(q2,x); } j=dequeue(q1); enqueue(q2,j); } } void delafter(struct queue &q1,struct queue &q2,int p) {int j; while(q1.front!=-1) {if((q1.front)%(q1.sice)==p) {q1.front=(q1.front+1)%(q1.sice);} enqueue(q2,dequeue(q1));} } void print(struct queue &q) { while(q.front!=-1) {cout<<dequeue(q)<<" ";} } int main() { struct queue s1,s2; s1.sice=20;s2.sice=20;s1.front=-1;s2.front=-1;s1.rear=-1;s2.rear=-1; int a[20],n,p,x,pos; cout<<"enter array size\n";cin>>n; cout<<"enter array elements\n"; for(int i=0;i<n;i++) {cin>>a[i];} for(int i=0;i<n;i++) {enqueue(s1,a[i]);} cout<<"press: 1.add-begin \n 2.add-end \n 3.delete-begin \n 4.delete-end \n 5.add-after \n 6.delete-after\n"; cin>>p; switch(p) {case 1:cout<<"enter element\n";cin>>x; addbeg(s1,s2,x); print(s2);break; case 2:cout<<"enter element\n";cin>>x; addend(s1,x); print(s1);break; case 3:delbeg(s1,s2); print(s1);break; case 4:delend(s1); print(s1);break; case 5:cout<<"enter position\n";cin>>pos; cout<<"enter element to be added\n";cin>>x; addafter(s1,s2,pos,x);print(s2);break; case 6:cout<<"enter position\n";cin>>pos; delafter(s1,s2,pos);print(s2);} return 0; }
[ "noreply@github.com" ]
RamanjaneyuluErni.noreply@github.com
273fcd94bf9e7e0de9e45b7466b2e4573ba69ffb
0da8c897503c7cfd48ef0295a65ca2d2d892af4f
/lib/algorithms/flow/unit_flow.h
36e55abc2941618c3a9f48f00a466b7018e9576d
[ "MIT" ]
permissive
c-goetz/VieCut
77c233a31e2e1d2b17a97ae58e3d01a0dcddcb3a
b187f0638aee31aa2cd691f890853afb6ea9d837
refs/heads/master
2020-07-19T04:36:52.759870
2019-09-04T14:17:48
2019-09-04T14:17:48
206,374,906
0
0
MIT
2019-09-04T17:28:57
2019-09-04T17:28:56
null
UTF-8
C++
false
false
5,979
h
/****************************************************************************** * unit_flow.h * * Source of VieCut. * ****************************************************************************** * Copyright (C) 2017 Alexander Noe <alexander.noe@univie.ac.at> * * Published under the MIT license in the LICENSE file. *****************************************************************************/ #pragma once #include <algorithm> #include <cstdint> #include <cstdlib> #include <queue> #include <utility> #include <vector> #include "common/definitions.h" #include "data_structure/flow_graph.h" #include "data_structure/graph_access.h" #include "tlx/logger.hpp" class unit_flow { public: static constexpr bool debug = false; unit_flow() { } virtual ~unit_flow() { } void init(flow_graph fg, const std::vector<EdgeWeight>& delta_src, EdgeWeight unit_cap, NodeID max_height, FlowType w) { m_f.resize(fg.number_of_nodes()); m_fg = &fg; m_delta_src = delta_src; m_unit_cap = unit_cap; m_max_height = max_height; m_w = w; m_current_edge.resize(fg.number_of_nodes(), 0); m_height.resize(fg.number_of_nodes(), 0); for (NodeID n = 0; n < fg.number_of_nodes(); ++n) { m_f[n] = delta_src[n]; if (delta_src[n] > (EdgeWeight)fg.getCapacity(n)) { LOG << "Inserting" << n; Q.push(std::make_pair(0, n)); } } pushCtr = 0; relabelCtr = 0; done = false; } void run() { LOG << "START: graph with n=" << m_fg->number_of_nodes() << " m=" << m_fg->number_of_edges(); if (Q.empty()) return; m_v = Q.top().second; Q.pop(); while (!done) { pushRelabel(m_v); } std::vector<size_t> heights(m_max_height + 1, 0); for (size_t i = 0; i < m_height.size(); ++i) { heights[m_height[i]]++; } LOG << "DONE: graph with n=" << m_fg->number_of_nodes() << " m=" << m_fg->number_of_edges() << " pushes: " << pushCtr << " relabels: " << relabelCtr; } FlowType excess(NodeID v) { return std::max(m_f[v] - m_fg->getCapacity(v), (FlowType)0); } FlowType flow(NodeID v) { return m_f[v]; } NodeID height(NodeID v) { return m_height[v]; } private: struct cmp { bool operator () (const std::pair<EdgeWeight, NodeID>& p1, const std::pair<EdgeWeight, NodeID>& p2) { return p1.first > p2.first; } }; bool applicable(NodeID v, EdgeID e) { NodeID tgt = m_fg->getEdgeTarget(v, e); return (excess(v) > 0) && (m_height[v] == m_height[tgt] + 1) && (m_fg->getEdgeCapacity(v, e) > m_fg->getEdgeFlow(v, e)) && (m_f[tgt] < m_w * m_fg->getCapacity(tgt)); } void push(NodeID v, EdgeID e) { ++pushCtr; NodeID tgt = m_fg->getEdgeTarget(v, e); LOG << "pushing from " << v << " to " << tgt; FlowType flow = m_fg->getEdgeFlow(v, e); assert(m_f[tgt] < m_w * m_fg->getCapacity(tgt)); EdgeWeight supply = std::min(excess(v), std::min( m_fg->getEdgeCapacity(v, e) - flow, (m_w * m_fg->getCapacity(tgt)) - m_f[tgt])); EdgeID rev = m_fg->getReverseEdge(v, e); m_fg->setEdgeFlow(v, e, flow + supply); m_fg->setEdgeFlow(tgt, rev, m_fg->getEdgeFlow(tgt, rev) - supply); m_f[v] -= supply; bool active_before = active(tgt); m_f[tgt] += supply; if (!active(v)) { if (!Q.empty()) { m_v = Q.top().second; Q.pop(); } else { done = true; } } if (!active_before && active(tgt)) { Q.push(std::make_pair(m_height[tgt], tgt)); if (done) { m_v = Q.top().second; Q.pop(); done = false; } } } bool active(NodeID v) { return m_height[v] < m_max_height && excess(v) > 0; } void relabel(NodeID v) { ++relabelCtr; LOG << "Relabel " << v; assert(active(v)); for (EdgeID e : m_fg->edges_of(v)) { assert(m_fg->getEdgeFlow(v, e) == m_fg->getEdgeCapacity(v, e) || m_height[v] <= m_height[m_fg->getEdgeTarget(v, e)] || m_fg->getEdgeCapacity(v, e) == 0); LOG0 << e; } ++m_height[v]; if (m_height[v] < m_max_height) { Q.push(std::make_pair(m_height[v], v)); } if (!Q.empty()) { m_v = Q.top().second; Q.pop(); } else { done = true; } } void pushRelabel(NodeID v) { LOG << "PushRelabel " << v; EdgeID e = m_current_edge[v]; if (m_fg->get_first_invalid_edge(v)) { if (applicable(v, e)) { push(v, e); } else { if (m_height[v] && e + 1 < m_fg->get_first_invalid_edge(v)) { ++m_current_edge[v]; } else { relabel(v); m_current_edge[v] = 0; } } } else { Q.pop(); } } private: std::priority_queue<std::pair<EdgeWeight, NodeID>, std::vector<std::pair<EdgeWeight, NodeID> >, cmp> Q; std::vector<EdgeID> m_current_edge; std::vector<NodeID> m_height; std::vector<FlowType> m_f; flow_graph* m_fg; std::vector<EdgeWeight> m_delta_src; EdgeWeight m_unit_cap; NodeID m_max_height; FlowType m_w; NodeID m_v; bool done; size_t pushCtr, relabelCtr; };
[ "alexander.noe@univie.ac.at" ]
alexander.noe@univie.ac.at
5c7ff3f74da320534de868baea6ef3b5eea42797
10add2fa4572990f6cba06e7d0817f6965d8cfa0
/Math/计算方法/PB18111697_王章瀚_1/PB18111697_王章瀚_1/PB18111697_王章瀚_1.cpp
4d5c4eb0e8506ac99ddc98618ea7cab21d1927f0
[ "MIT" ]
permissive
LearnerM/USTC-CS-Resources
0d2a156480ebbee8bbd7080b3026e745c52ac892
8dae043524f236e894c3e81f51f7701f0de23968
refs/heads/master
2023-06-11T09:52:08.590845
2021-07-04T05:30:50
2021-07-04T05:30:50
null
0
0
null
null
null
null
UTF-8
C++
false
false
726
cpp
#include "pch.h" #include <iostream> #include <stdio.h> #include <cmath> using namespace std; // 设置允许截断误差值 const double TRUNCATION_ERROR = 1e-13; // 计算在允许截断误差下的k应计算到多少位 const double MAX_K = 1/pow(2*TRUNCATION_ERROR, 0.5) + 1; // x及x的个数 const int X_NUM = 7; const double array_x[] = { 0.0, 0.5, 1.0, pow(2, 0.5), 10.0, 100.0, 300.0 }; double psi(double x) { double answer = 0; double k = 1; // 先计算(psi(x)-psi(1))/(1-x),其收敛速度更快 while (k <= MAX_K) { answer += 1/(k*(k+x)*(k+1)); k++; } return 1 + (answer)*(1 - x); } int main() { for (int i = 0; i < X_NUM; i++) { printf("x=%lf,y=%.15e\n", array_x[i], psi(array_x[i])); } }
[ "hankzhwang@gmail.com" ]
hankzhwang@gmail.com
89d21cf961b723988f7e42a49df8738ffaa02fdb
c591b56220405b715c1aaa08692023fca61f22d4
/syeda reeha quasar/milestone 6/all prime numbers from 1 to n.cpp
912ce9a82a53154dbd7691e86dd1380f7cf33898
[]
no_license
Girl-Code-It/Beginner-CPP-Submissions
ea99a2bcf8377beecba811d813dafc2593ea0ad9
f6c80a2e08e2fe46b2af1164189272019759935b
refs/heads/master
2022-07-24T22:37:18.878256
2021-11-16T04:43:08
2021-11-16T04:43:08
263,825,293
37
105
null
2023-06-05T09:16:10
2020-05-14T05:39:40
C++
UTF-8
C++
false
false
268
cpp
#include<iostream> using namespace std; int main () { int num , i,end, isprime ; cout<<"print all prime numbers from 1 to n"<<endl; cin >>end; for(i=2; i<=end;i++) { isprime=1; for(num=2; num<=i/2;num++) { if(i%num==0) isprime=0; } if(isprime==1) cout<<i<<endl; } }
[ "reeha.saba@gmail.com" ]
reeha.saba@gmail.com
fe05875edd60a263dcb0a5990692db3a112b15a7
aa4bdcdf47e15ec43b073e602ca15e7e8dc916b0
/BipartiteUnionFind.cpp
70fc1ab820848057c100726ef3cdde5f4f91e812
[]
no_license
newpolaris/algorithm
dbd51d036f4f892702403200919efb872aa92ec6
70e7fdc96811da7cda681cb96d7b5041d7932c76
refs/heads/master
2021-01-12T17:16:36.359070
2019-11-24T17:29:34
2019-11-24T17:29:34
71,535,310
0
0
null
null
null
null
UTF-8
C++
false
false
2,890
cpp
#include <iostream> #include <string> #include <vector> #include <map> using namespace std; struct BipartiteUnionFind { vector<int> parent, rank, enemy, size; BipartiteUnionFind(int n) : parent(n), rank(n, 0), enemy(n, -1), size(n, 1) { for (int i = 0; i < n; i++) parent[i] = i; } int find(int u) { if (u == parent[u]) return u; return parent[u] = find(parent[u]); } int merge(int a, int b) { // a나 b가 공집합인 경우 나머지 하나를 반환한다. if (a == -1 || b == -1) return max(a, b); a = find(a), b = find(b); // 이미 둘이 같은 트리에 속한 경우 if (a == b) return a; if (rank[a] > rank[b]) swap(a, b); // 이제 항상 rank[b]가 더 크므로 a를 b의 자식으로 넣는다. if (rank[a] == rank[b]) rank[b]++; parent[a] = b; size[b] += size[a]; return b; } // u와v가 서로 적대하는 집합에 속한다. bool dis(int u, int v) { // 우선 루트를 찾는다. u = find(u), v = find(v); // 같은 집합에 속해 있으면 모순! if (u == v) return false; // 적의 적은 나의 동지 int a = merge(u, enemy[v]), b = merge(v, enemy[u]); enemy[a] = b; enemy[b] = a; return true; } // u와 v가 같은 집합에 속한다. bool ack(int u, int v) { // 우선 루트를 찾는다. u = find(u), v = find(v); // 두 집합이 서로 적대 관계라면 모순! if (enemy[u] == v) return false; //동지의 적은 나의 적 int a = merge(u, v), b = merge(enemy[u], enemy[v]); enemy[a] = b; // u, v 모두 아직 적대 집합이 설정되지 않았다면 b 가 -1 일 수 있다. if (b != -1) enemy[b] = a; return true; } // 확인만 한다, 같은 집합 0, 다르면 1, 모르겠으면 2 int check(int a, int b) { a = find(a), b = find(b); if (a == b) return 0; auto ea = enemy[a], eb = enemy[b]; if (a == eb) return 1; return 2; } }; int main() { #ifdef _DEBUG freopen("../algospot/editorwars.in", "r", stdin); #endif int C, N, M, a, b, e; string w; cin >> C; while (C--) { cin >> N >> M; bool bPass = true; BipartiteUnionFind A(N); for (int i = 1; i <= M; i++) { cin >> w >> a >> b; if (!bPass) continue; bPass = (w == "ACK") ? A.ack(a, b) : A.dis(a, b); if (!bPass) { cout << "CONTRADICTION AT " << i << endl; } } if (!bPass) continue; int ret = 0; for (int node = 0; node < N; ++node) { if (A.find(node) == node) { int enemy = A.enemy[node]; // 같은 모임 쌍을 두 번 세지 않기 위해, // enemy < node인 경우 만 센다. // enemy == -1 인경우도 정확히 한번 씩 세게 된다. if (enemy > node) continue; int mySize = A.size[node]; int enemySize = (enemy == -1 ? 0 : A.size[enemy]); // 두 집합 중 큰 집합을 더한다. ret += max(mySize, enemySize); } } cout << "MAX PARTY SIZE IS " << ret << endl; } return 0; }
[ "newpolaris@gmail.com" ]
newpolaris@gmail.com
092ac17711a1b4d7c6a230c6069fcd435381d678
040eab433f00786ec34142f242c0735e8c19fd9c
/samples/batcat/src/MyApp.hpp
473207ce3e67e765f296bad9ce74f788ed48c6aa
[ "Zlib" ]
permissive
MORTAL2000/crogine
d7c73f174dfd7b1cf89ee693f98c7ecd41bb11f4
488b46dc3f706def8fdae30346c248f01c95b49c
refs/heads/master
2020-12-20T20:52:56.810085
2020-01-24T15:41:32
2020-01-24T15:41:32
null
0
0
null
null
null
null
UTF-8
C++
false
false
1,565
hpp
/*----------------------------------------------------------------------- Matt Marchant 2017 http://trederia.blogspot.com crogine test application - Zlib license. This software is provided 'as-is', without any express or implied warranty.In no event will the authors be held liable for any damages arising from the use of this software. Permission is granted to anyone to use this software for any purpose, including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions : 1. The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation would be appreciated but is not required. 2. Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software. 3. This notice may not be removed or altered from any source distribution. -----------------------------------------------------------------------*/ #ifndef MY_APP_HPP_ #define MY_APP_HPP_ //implements the cro::App class #include <crogine/core/App.hpp> #include <crogine/core/StateStack.hpp> class MyApp final : public cro::App { public: MyApp(); ~MyApp() = default; private: cro::StateStack m_stateStack; void handleEvent(const cro::Event&) override; void handleMessage(const cro::Message&) override; void simulate(cro::Time) override; void render() override; bool initialise() override; void finalise() override; }; #endif //MY_APP_HPP_
[ "matty_styles@hotmail.com" ]
matty_styles@hotmail.com
8ba727dfa61e72c939322c529222caec589e5b7f
b12bcb039791d3523a410522403230f5404fd8de
/DesignPattern/Learning-010/BMW.h
f4e7a8692215f1c1340c34cb40c9ac559a7f969c
[]
no_license
cool-cola/leetcode
dee3bde66661d467c5a9bed4d59f765f83e9ad77
a8b9eb879a2e88d1ce7dce71baccee1ad772a797
refs/heads/master
2021-01-11T03:05:27.480822
2017-03-09T07:54:11
2017-03-09T07:54:11
71,098,116
0
0
null
null
null
null
UTF-8
C++
false
false
220
h
#pragma once #include <iostream> //#include "Car.h" class CCar; class CBMW : public CCar { public: CBMW() {} virtual ~CBMW() {} virtual void driverV() override { std::cout << "Driving BMW..." << std::endl; } };
[ "1173573041@qq.com" ]
1173573041@qq.com
0ccdd12286d4a26471c96ecb079e3d91d9069c98
de33200cd65614455b30bacaa6a5b209cbabf114
/baekjoon/2661.cpp
4d8280df9500e7f54409c3ba6c0ed0a0dc69069b
[]
no_license
DongOnee/algorithm
4b3367ea5e6346d44dbaa66328057654596b9ab2
662352f9fcfafdaa66b00af1806eeea2cf7ff0d1
refs/heads/master
2022-03-14T06:48:37.097846
2022-03-04T06:34:42
2022-03-04T06:34:42
138,333,071
0
0
null
null
null
null
UTF-8
C++
false
false
1,323
cpp
/** * 19.2.12. */ #include <cstdio> #include <string> using namespace std; string s; int len; bool chk() { int chk_len = len/2; int size=0; while(size<chk_len) { size +=1; string subs1 = s.substr(len-size, size); string subs2 = s.substr(len-size*2, size); // printf("string : %s\tsub_s 2 : %s\tsubs_s 1 : %s\n", s.c_str(), subs2.c_str(), subs1.c_str()); if (subs1.compare(subs2) == 0) return false; // same same... } return true; } int main(int argc, char const *argv[]) { int N; scanf("%d", &N); s = "1"; len = 1; int input_=1; while (len<N) { len +=1; for ( ; input_<4; input_++) { s.push_back(input_+'0'); if (chk()) { input_=1; break; } s.pop_back(); } if (input_ == 4) { // 마지막 3 이라는뜻~ // s.pop_back(); len-=1; input_ = s.at(len-1) -'0'+1; // printf("%d", input_); s.pop_back(); len-=1; } } printf("%s\n", s.c_str()); return 0; } /* 1 12 121 1213 12131 121312 1213121 12131231 12132123 */
[ "dongwon5520@gmail.com" ]
dongwon5520@gmail.com
4791dcd6631fd1a53fc7c943b0fef9b5887ba90c
c83e3f54a7b012396aef1a634cd87adb75ec2e1c
/2B/zad_1_8_str_29.cpp
c9deef0e5f32df03c2803feac042fc96c3c0159e
[]
no_license
JakubMazurek/zsk
83acfe6c416aaf0fc5db6507bce6877c58ccbc20
0fe46ce98495a60ab88bd9a162802aeb34f25f9f
refs/heads/master
2021-08-14T17:28:45.266562
2017-11-16T10:25:25
2017-11-16T10:25:25
null
0
0
null
null
null
null
UTF-8
C++
false
false
291
cpp
#include <iostream> #include <cstdlib> #include <cmath> #include <ctime> using namespace std; int main() { int n, s, i; cout<<"Podaj n: "; cin>>n; s=1; i=3; while(i<=n+2){ s=s*i; i=i+1; } cout<<s<<endl; system("pause"); return 0; }
[ "zskgit@gmail.com" ]
zskgit@gmail.com
840110cc3566b5012e2b78042a449a39a3db9d5d
c4ff0549531983342b89b4ccafab46632ecd4bc5
/Polinomials/Poly.h
c1427d92b72abf1424af47b1a7130678492c84d0
[]
no_license
tom1322s/OOPC
30187a4a851869ed014e41f3a86fdf181418c870
a1e38b6ab585c503c915ec7b0a2c2c36c30f45b1
refs/heads/master
2022-03-29T00:36:41.387526
2020-01-19T19:27:12
2020-01-19T19:27:12
null
0
0
null
null
null
null
UTF-8
C++
false
false
683
h
// // Created by maciek on 01/11/2019. // #pragma once #include <map> #include <iostream> #include <functional> class Poly { private: std::map<unsigned int, double, std::greater<>> data; public: Poly(); Poly(double src); //Poly(const Poly& src); double& operator [] (unsigned int key); double operator () (double x) const; friend std::ostream& operator << (std::ostream& out, const Poly& src); //Poly& operator = (const Poly& src); friend Poly operator + (const Poly& prev, const Poly& src); friend Poly operator - (const Poly& prev, const Poly& src); friend Poly operator * (const Poly& prev, const Poly& src); friend Poly operator - (const Poly& src); };
[ "mpodsedkowski@gmail.com" ]
mpodsedkowski@gmail.com
bcdb88745bf65a263b463e48a35eea69d47ed107
23017336d25e6ec49c4a51f11c1b3a3aa10acf22
/csc3750/prog8/Light.cpp
20cf3049b2400d72bc2ca2773bb698d7cc7d1a89
[]
no_license
tjshaffer21/School
5e7681c96e0c10966fc7362931412c4244507911
4aa5fc3a8bbbbb8d46d045244e8a7f84e71c768f
refs/heads/master
2020-05-27T19:05:06.422314
2011-05-17T19:55:40
2011-05-17T19:55:40
1,681,224
1
1
null
2017-07-29T13:35:54
2011-04-29T15:36:55
C++
UTF-8
C++
false
false
537
cpp
/** Class provided by Dr. Boshart. */ #include "Light.h" Light::Light() { location = new Vertex(0, 0, 0); color = new Color(1.0, 1.0, 1.0); } Light::~Light() { delete location; delete color; } void Light::setLocation(Vertex* l) { Vertex* temp = location; location = l; delete temp; } void Light::setColor(Color* c) { Color* temp = color; color = c; delete temp; } Vertex* Light::getLocation() { return location; } Color* Light::getColor() { return color; }
[ "tjshaffer21@gmail.com" ]
tjshaffer21@gmail.com
c19b633db944ebff0f61d834c7e522d9068e5776
9e34e84c20760a9a37512c675074974ac7e56275
/more-source/2010-2011/kbtu_lksh/finalcontest/i.cpp
05b81d04ea12d0cb592a6c6746230f4f0e328514
[]
no_license
Slava/competitiveProgramming
2b7f26bf24143b459c6e2625ef1ea343a926bb76
b68391720b9f9efc4162a66ca07d9448cffc1453
refs/heads/master
2021-01-21T12:40:40.053352
2020-01-06T19:21:45
2020-01-06T19:21:45
9,552,080
8
6
null
null
null
null
UTF-8
C++
false
false
985
cpp
#define file "I" #include <cstdio> #include <algorithm> #include <utility> #include <iostream> #include <cstdlib> using namespace std; #define mp make_pair #define f first #define s second pair<int, pair<int,int> >a[1000010]; int n, m, p[1010], ans; int get(int x) { if (p[x] != x) p[x] = get(p[x]); return p[x]; } void unite(int x, int y) { if (rand() & 1) p[x] = y; else p[y] = x; } int main() { freopen(file ".in", "r", stdin); freopen(file ".out", "w", stdout); scanf("%d%d", &n, &m); for (int i = 1; i <= n; i++) p[i] = i; for (int i = 0; i < m; i++) { cin >> a[i].s.f >> a[i].s.s >> a[i].f; a[i].f *= -1; } sort(a, a + m); for (int i = 0; i < m; i++) { int x = get(a[i].s.f); int y = get(a[i].s.s); if (x != y) { unite(x, y); ans += a[i].f; } } cout << -ans; return 0; }
[ "slava@meteor.com" ]
slava@meteor.com
e07b7c7cf0c52b327e89e1a4426e65d396d9d24d
d5fb06cb16884ca739ce4f921bba521ee544ccbd
/Algorithms and Data Stuctures/2 term/Lab 6/Source.cpp
b7aa48c048008548a4a4463728d7b8a7688b9d5a
[]
no_license
SYaroslav2/KPI
adcfe30e3e445f174b11178847627af8c3ea3c50
f6538fe6c72450e6a95803a363d01a648e6b354d
refs/heads/main
2023-05-31T03:24:17.546377
2021-06-16T09:23:19
2021-06-16T09:23:19
377,416,185
0
0
null
null
null
null
UTF-8
C++
false
false
3,863
cpp
#include <stdio.h> #include <stdlib.h> #include <conio.h> #include <math.h> typedef struct list { float inf; struct list *link; }; struct list * init(float a) { struct list *lst; lst = (struct list*)malloc(sizeof(struct list)); lst->inf = a; lst->link = NULL; return (lst); } struct list * addelem(list * lst, float number) { struct list *temp, *p; temp = (struct list*)malloc(sizeof(list)); p = lst->link; lst->link = temp; temp->inf = number; temp->link = p; return (temp); } void listprint(list *lst) { struct list *p; p = lst; do { printf(" %2.0f", p->inf); p = p->link; } while (p != NULL); } struct list *swap(struct list *lst_1, struct list *lst_2, struct list *head) { struct list *prev_1, *prev_2, *next_1, *next_2; prev_1 = head; prev_2 = head; if (prev_1 == lst_1) prev_1 = NULL; else { while (prev_1->link != lst_1) { prev_1 = prev_1->link; } } if (prev_2 == lst_2) prev_2 = NULL; else { while (prev_2->link != lst_2) { prev_2 = prev_2->link; } } next_1 = lst_1->link; next_2 = lst_2->link; if (lst_2 == next_1) { lst_2->link = lst_1; lst_1->link = next_2; if (lst_1 != head) prev_1->link = lst_2; } else if (lst_1 == next_2) { lst_1->link = lst_2; lst_2->link = next_1; if (lst_2 != head) prev_2->link = lst_2; } else { if (lst_1 != head) prev_1->link = lst_2; lst_2->link = next_1; if (lst_2 != head) prev_2->link = lst_1; lst_1->link = next_2; } if (lst_1 == head) return(lst_2); if (lst_2 == head) return(lst_1); return(head); } struct list *deletehead(list *root) { struct list *temp; temp = root->link; free(root); return(temp); } int main() { float N = 40; struct list *lst, *root, *lst_1, *lst_2, *p_k; lst = init(-1); root = lst; int count_1 = 0, counter = 0; for (int i = 2; i <= N; i++) { if ((i > (5 + count_1)) && (i <= (10 + count_1))) { counter++; if (counter >= 5) { count_1 = count_1 + 10; counter = 0; } lst = addelem(lst, i); } else lst = addelem(lst, -i); } printf("\n The old list:\n"); listprint(root); lst_1 = root; lst_2 = root; count_1 = 0; counter = 0; int i_1 = 5, i_2 = 10, integer_1 = 10, integer_2 = 15 ; while (1) { lst_1 = root; for (int i = 0; i < i_1; i++) { lst_1 = lst_1->link; } i_1 = i_1 + 1; if (i_1 > 25) { if (i_1 == integer_1 + 1) { i_1 = i_1 + 14; integer_1 = 20 + integer_1; if (i_1 >= N) break; } } else { if (N == 20) { if (i_1 == integer_1 + 1) { i_1 = i_1 + 15; integer_1 = 20 + integer_1; if (i_1 >= N) break; } } else if (N > 20) { if (i_1 == integer_1) { i_1 = i_1 + 15; integer_1 = 20 + integer_1; if (i_1 >= N) break; } } } lst_2 = root; for (int i = 0; i < i_2; i++) { lst_2 = lst_2->link; } i_2 = i_2 + 1; if (i_2 > 30) { if (i_2 == integer_2+1) { i_2 = i_2 + 14; integer_2 = 20 + integer_2; if (i_2 >= N) { break; } } } else { if (N == 20) { if (i_2 == integer_2 + 1) { i_2 = i_2 + 15; integer_2 = 20 + integer_2; if (i_2 >= N) { break; } } } else if (N > 20) { if (i_2 == integer_2) { i_2 = i_2 + 15; integer_2 = 20 + integer_2; if (i_2 >= N) { break; } } } } root = swap(lst_1, lst_2, root); } printf("\n"); printf(" The new list:\n"); listprint(root); lst = root; while (lst != NULL) lst = deletehead(lst); free(lst); _getch(); return 0; }
[ "noreply@github.com" ]
SYaroslav2.noreply@github.com
164d899eecc86b50639574038aa1baf1497f76c3
a24ddbfdf20dfa041d12eef4e88e7f4ca23bf09b
/jni/src/TextRenderer.cpp
982f7dbd0184b56651e10dfa5f54b56c24b2faf2
[]
no_license
gra3/Project-Kona
34421647a21638b1f623ca7fe101b410e6cf839b
837193490d14f470faba5a2fdc6795a4facb8bc5
refs/heads/master
2021-06-11T06:49:42.157297
2017-01-07T03:55:46
2017-01-07T03:55:46
78,257,302
0
0
null
null
null
null
UTF-8
C++
false
false
1,362
cpp
#include "TextRenderer.h" TextRenderer::TextRenderer() { } TextRenderer::TextRenderer( SDL_Renderer* renderer, std::string fontName ): renderer( nullptr ), surface( nullptr ), texture( nullptr), font( nullptr ), fontName( fontName ) { this->renderer = renderer; } TextRenderer::~TextRenderer() { TTF_CloseFont( font ); } void TextRenderer::SetFont( int pointSize ) { if ( font != nullptr ) TTF_CloseFont( font ); font = TTF_OpenFont( fontName.c_str(), pointSize ); } void TextRenderer::DrawInRegion( SDL_Rect region, std::string text, SDL_Color color ) { int w; int h; auto drawText = false; auto pointSize = static_cast< int >( region.h * 0.75 ); SDL_Rect regionToBeDrawnTo = region; while ( !drawText ) { SetFont( pointSize ); surface = TTF_RenderText_Blended( font, text.c_str(), color ); texture = SDL_CreateTextureFromSurface( renderer, surface ); SDL_QueryTexture( texture, nullptr, nullptr, &w, &h ); if ( w > region.w || h > region.h ) { pointSize--; SDL_DestroyTexture( texture ); } else { regionToBeDrawnTo.w = w; regionToBeDrawnTo.h = h; regionToBeDrawnTo.x += ( region.w - w ) / 2; regionToBeDrawnTo.y += ( region.h - h ) / 2; drawText = true; } SDL_FreeSurface( surface ); } SDL_RenderCopy( renderer, texture, nullptr, &regionToBeDrawnTo ); SDL_DestroyTexture( texture ); }
[ "gra3@zips.uakron.edu" ]
gra3@zips.uakron.edu
07c72438d0a9d3bf0a9efa00585e0eaf4afe9890
48977d8586d355ea5c7ed5ddc65d6126ae3f3ecc
/proyecto.h
26ca6b8c3ad8423004588f7ae422aa0ac6c607cb
[]
no_license
EdwinGeul01/Read-bmp-cpp
71fe4a8a0a3cdfe6f3655765e6cea2b298953f56
c0282866f50cef6ea099480239bd21db7c3abde8
refs/heads/master
2022-09-07T20:56:21.098020
2020-02-18T00:03:53
2020-02-18T00:03:53
null
0
0
null
null
null
null
UTF-8
C++
false
false
492
h
#ifndef PROYECTO_H #define PROYECTO_H #include <QMainWindow> #include <stdio.h> #include <string.h> #include <iostream> QT_BEGIN_NAMESPACE namespace Ui { class proyecto; } QT_END_NAMESPACE class proyecto : public QMainWindow { Q_OBJECT public: proyecto(QWidget *parent = nullptr ); ~proyecto(); private slots: void on_btnsalir_clicked(); void on_btnShowFile_pressed(); void on_btnReadFile_pressed(); private: Ui::proyecto *ui; }; #endif // PROYECTO_H
[ "edwingeul01@gmail.com" ]
edwingeul01@gmail.com
6476d1e2fc426792bb8b90fea5b28b8f28897de1
f37662e0bffbcb703d20caf5b051454eafdca65b
/Review/THK/Framework111/Reference/Headers/Graphic_Device.h
fdbe5de596300e942307244bc6a93acf145c1989
[]
no_license
TeaHoonJJang/SR_TEST
2851f222999673acd35a0c5d8b2822ecd9e47431
e3da5845cce19909dfd4439508b428c466210a14
refs/heads/main
2023-01-10T00:49:05.443033
2020-11-17T09:07:19
2020-11-17T09:07:19
null
0
0
null
null
null
null
UHC
C++
false
false
1,345
h
#pragma once #ifndef __GRAPHIC_DEVICE_H__ #include "Base.h" class ENGINE_DLL CGraphic_Device final : public CBase { DECLARE_SINGLETON(CGraphic_Device) private: CGraphic_Device(); virtual ~CGraphic_Device() =default; public: LPDIRECT3DDEVICE9 Get_Device() { return m_pDevice; } public: HRESULT Ready_Graphic_Device(HWND hWnd, _uint iWinCX, _uint iWinCY, EDisplayMode eDisplayMode); void Render_Begin(); void Render_End(HWND hWND = nullptr); public: virtual void Free() override; private: LPDIRECT3D9 m_pSDK; // 그래픽카드의 수준을 조사하고 생성하는 객체. LPDIRECT3DDEVICE9 m_pDevice; // 애가 실질적으로 그래픽 장치를 제어하는 객체. // 장치를 생성하는 과정. //1. 장치를 제어하기 위한 객체를 생성하는 객체(m_pSdk)를 생성. //2. 장치의 수준을 조사해야한다. //3. 수준에 맞는 장치를 제어하기 위한 객체 생성. /* com - component Object Model의 약자. 우리가 배우고 있는 다이렉트에서는 장치 혹은 어떠한 데이터를 다루는 기능들을 하나의 부품처럼 제공해주고 있다. 그리고 사용자는 이 부품들을 이용하여 마치 레고를 조립하듯 프로그램을 구성해 나가야 한다. */ }; #define __GRAPHIC_DEVICE_H__ #endif
[ "rlaxogns5755@naver.com" ]
rlaxogns5755@naver.com
c44a048fd981bdc303f2974652703c9aa3ce5b61
691ef71d083ab1faa59487c683e6a7329f365a68
/Eudora71/Eudora/SpellDialog.h
102b7c37ce9691851b0affddb89e804fa166854f
[]
no_license
radtek/eudora-win
6313d935fe650b39c54c7934e767c28425b29b93
37c39ac8e27d2ab0f11ed867c998b3106e69c1d7
refs/heads/master
2023-03-16T18:36:37.976634
2018-09-07T08:55:38
2018-09-07T08:55:38
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,176
h
#if !defined(AFX_SPELLDIALOG_H__4056D7B2_08FF_11D1_9818_00805FD2F268__INCLUDED_) #define AFX_SPELLDIALOG_H__4056D7B2_08FF_11D1_9818_00805FD2F268__INCLUDED_ #if _MSC_VER >= 1000 #pragma once #endif // _MSC_VER >= 1000 // SpellDialog.h : header file // #define SpellCheck_DLL_ FALSE #include "ssce.h" #define SpellCheck_CHAR unsigned char #define MAX_SEARCH_DEPTH 3 #define ALT_WORD_SCORE_RANGE 20 // accept only top 20% #define MIN_ALT_WORD_SCORE 50 // ignore scores < 50% #define MAX_SUGGESTIONS 32 #define MAX_MAIN_LEX_FILES 5 // max files forming main lexicon #define MAX_FILE_NAME ( _MAX_FNAME + _MAX_EXT + 2 ) // Lexicon selectors: #define SpellCheckD_PERM_CHANGE_LEX 0 #define SpellCheckD_PERM_IGNORE_LEX 1 #define SpellCheckD_PERM_SUGGEST_LEX 2 typedef S16 (CALLBACK* ADDTOLEXFUNCPTR)(S16, S16, const SpellCheck_CHAR*, const SpellCheck_CHAR*); typedef S16 (CALLBACK* CHECKBLOCKFUNCPTR)(S16, S16, U32, SpellCheck_CHAR*, S16, SpellCheck_CHAR*, S16); typedef S16 (CALLBACK* CHECKWORDFUNCPTR)(S16, U32, const SpellCheck_CHAR*, SpellCheck_CHAR*, S16) ; typedef S16 (CALLBACK* CLEARLEXFUNCPTR)(S16, S16); typedef S16 (CALLBACK* CLOSEBLOCKFUNCPTR)(S16, S16 ) ; typedef S16 (CALLBACK* CLOSELEXFUNCPTR)(S16, S16) ; typedef S16 (CALLBACK* CLOSESESSIONFUNCPTR)(S16) ; typedef S16 (CALLBACK* CREATELEXFUNCPTR)(S16, const char FAR *, S16, S16) ; typedef S16 (CALLBACK* DELBLOCKWORDFUNCPTR)(S16, S16) ; typedef S16 (CALLBACK* DELFROMLEXFUNCPTR)(S16, S16, const SpellCheck_CHAR*); typedef S16 (CALLBACK* GETBLOCKFUNCPTR)(S16, S16, SpellCheck_CHAR FAR *, S32) ; typedef S16 (CALLBACK* GETBLOCKINFOFUNCPTR)(S16, S16, S32 FAR *, S32 FAR *, S32 FAR *, S32 FAR *) ; typedef S16 (CALLBACK* GETBLOCKWORDFUNCPTR)(S16, S16, SpellCheck_CHAR FAR *, S16) ; typedef S32 (CALLBACK* GETLEXFUNCPTR)(S16, S16, SpellCheck_CHAR*, S32); typedef S16 (CALLBACK* GETLEXINFOFUNCPTR)(S16, S16, S32*, S16*, S16*, S16*); typedef U32 (CALLBACK* GETOPTIONFUNCPTR)(S16, U32) ; typedef S16 (CALLBACK* NEXTBLOCKWORDFUNCPTR)(S16, S16) ; typedef S16 (CALLBACK* OPENBLOCKFUNCPTR)(S16, SpellCheck_CHAR FAR *, S32, S32, S16) ; typedef S16 (CALLBACK* OPENLEXFUNCPTR)(S16, const char FAR *,S32) ; typedef S16 (CALLBACK* OPENSESSIONFUNCPTR)(void) ; typedef S16 (CALLBACK* REPLACEBLOCKWORDFUNCPTR)(S16, S16, const SpellCheck_CHAR FAR *) ; typedef U32 (CALLBACK* SETOPTIONFUNCPTR)(S16, U32, U32) ; typedef S16 (CALLBACK* SUGGESTFUNCPTR)(S16, const SpellCheck_CHAR FAR *, S16, SpellCheck_CHAR FAR *, S32, S16 FAR *, S16) ; typedef void (CALLBACK* VERSIONFUNCPTR)(S16 FAR *, S16 FAR *) ; // Used for popup menu #define COMMAND_ID_ADD 100 #define COMMAND_ID_IGNOREALL 101 #define COMMAND_ID_DELETE_WORD 102 #define COMMAND_ID_WORD 103 class CSpell; ///////////////////////////////////////////////////////////////////////////// // CSpellDialog dialog class CSpellDialog : public CDialog { DECLARE_DYNAMIC(CSpellDialog) // handle to the dll HINSTANCE m_hSpellLib; // dll functions ADDTOLEXFUNCPTR m_pfnAddToLex; CHECKBLOCKFUNCPTR m_pfnCheckBlock; CHECKWORDFUNCPTR m_pfnCheckWord; CLEARLEXFUNCPTR m_pfnClearLex; CLOSEBLOCKFUNCPTR m_pfnCloseBlock; CLOSELEXFUNCPTR m_pfnCloseLex; CLOSESESSIONFUNCPTR m_pfnCloseSession; CREATELEXFUNCPTR m_pfnCreateLex; DELBLOCKWORDFUNCPTR m_pfnDelBlockWord; DELFROMLEXFUNCPTR m_pfnDelFromLex; GETBLOCKFUNCPTR m_pfnGetBlock; GETBLOCKINFOFUNCPTR m_pfnGetBlockInfo; GETBLOCKWORDFUNCPTR m_pfnGetBlockWord; GETLEXFUNCPTR m_pfnGetLex; GETLEXINFOFUNCPTR m_pfnGetLexInfo; GETOPTIONFUNCPTR m_pfnGetOption; NEXTBLOCKWORDFUNCPTR m_pfnNextBlockWord; OPENBLOCKFUNCPTR m_pfnOpenBlock; OPENLEXFUNCPTR m_pfnOpenLex; OPENSESSIONFUNCPTR m_pfnOpenSession; REPLACEBLOCKWORDFUNCPTR m_pfnReplaceBlockWord; SETOPTIONFUNCPTR m_pfnSetOption; SUGGESTFUNCPTR m_pfnSuggest; VERSIONFUNCPTR m_pfnVersion; SpellCheck_CHAR m_szSuggestingForTempWord[SSCE_MAX_WORD_SZ]; // Temporary lexicon ids: short m_sTmpIgnoreLexId; short m_sTmpSuggestLexId; short m_sTmpChangeLexId; // Id of SpellCheck block to check: short m_blkId; // SpellCheck Session id: short m_sid; BOOL m_bDeleteBtn; // Is replace button set to "Delete"? // Permanent lexicon ids: short m_sPermIgnoreLexId; short m_sPermChangeLexId; short m_sPermSuggestLexId; // Permanent lexicon file names: char m_szPermChangeLexFileName[MAX_FILE_NAME]; char m_szPermIgnoreLexFileName[MAX_FILE_NAME]; char m_szPermSuggestLexFileName[MAX_FILE_NAME]; UINT m_uDefID; // Default pushbutton in Check Word Dialog BOOL m_bAUserChange; // Must be set to false anytime the replace word edit ctrl is modified by the program BOOL m_bSuggestingFor; BOOL m_bUseSugTempForProbWord; // SpellCheck_CheckBlock options: ULONG m_ulOptionsMask; // Path where lexicon files reside: char m_szUserLexPath[_MAX_PATH]; char m_szLexPath[ _MAX_PATH ]; // TRUE if suggestions are given automatically after a misspelled word is // encountered; FALSE if user must select Suggest button for suggestion: // BOOL m_bAlwaysSuggest; // Default language id used when creating lexicons: char m_byLanguage; // Current SpellCheck_Suggest search depth (used only if alwaysSuggest is FALSE: short m_sSearchDepth; CSpell* m_pSpell; RECT m_rectWnd; BOOL m_bFoundMisspelling; INT m_iError; CWnd* m_pWndIgnoreBtn; CWnd* m_pWndIgnoreAllBtn; CWnd* m_pWndReplaceBtn; CWnd* m_pWndReplaceAllBtn; CWnd* m_pWndAddToLexBtn; CWnd* m_pWndSuggestBtn; // CWnd* m_pWndCancelBtn; CWnd* m_pWndJustDoIt; CWnd* m_pWndSuggestList; CWnd* m_pWndProbLblTxt; CWnd* m_pWndProbWordTxt; CWnd* m_pWndRepWordEdit; bool m_bHasBeenInitialized; BOOL m_bAutoCheck; // Main lexicon file name(s). The main lexicon may be implemented // via several files: // char m_arrMainLexFileNames[MAX_MAIN_LEX_FILES][MAX_FILE_NAME]; UINT m_nMainLexFiles; // Main lexicon ids: short m_arrMainLexIds[MAX_MAIN_LEX_FILES]; void busy(BOOL on); INT getSuggestions(const SpellCheck_CHAR* word ); void RunChecker(); void parseFileList(const char* fileList, char fileNames[][MAX_FILE_NAME], size_t maxFileNames, UINT* nFileNames); INT openSpellCheck(); void closeSpellCheck(); int LoadSpellLib(); int CloseSpellLib(); void saveOptionMask(unsigned long mask); void SetOptions(); BOOL Init(); protected: friend class CSpellEditLexDialog; S16 my_SpellCheck_AddToLex(S16 lexId, const SpellCheck_CHAR FAR *word, const SpellCheck_CHAR FAR *otherWord); S16 my_SpellCheck_CheckBlock(S16 blkId, U32 options, SpellCheck_CHAR FAR *errWord, S16 errWordSz, SpellCheck_CHAR FAR *repWord, S16 repWordSz); S16 my_SpellCheck_ClearLex(S16 lexId); S16 my_SpellCheck_CloseBlock(S16 blkId); S16 my_SpellCheck_CloseLex(S16 lexId); S16 my_SpellCheck_CloseSession(S16 sid); S16 my_SpellCheck_CreateLex(const char FAR *fileName, S16 type, S16 lang); S16 my_SpellCheck_DelBlockWord(S16 blkId); S16 my_SpellCheck_DelFromLex(S16 lexId, const SpellCheck_CHAR FAR *word); S32 my_SpellCheck_GetBlock(S16 blkId, SpellCheck_CHAR FAR *block, S32 blkSz); S16 my_SpellCheck_GetBlockInfo(S16 blkId, S32 FAR *blkLen, S32 FAR *blkSz, S32 FAR *curPos, S32 FAR *wordCount); S16 my_SpellCheck_GetBlockWord(S16 blkId, SpellCheck_CHAR FAR *word, S16 wordSz); S32 my_SpellCheck_GetLex(S16 lexId, SpellCheck_CHAR FAR *lexBfr, S32 lexBfrSz); S16 my_SpellCheck_GetLexInfo(S16 lexId, S32 FAR *size, S16 FAR *format, S16 FAR *type, S16 FAR *lang); U32 my_SpellCheck_GetOption(U32 option); S16 my_SpellCheck_NextBlockWord(S16 blkId); S16 my_SpellCheck_OpenBlock(SpellCheck_CHAR FAR *block, S32 blkLen, S32 blkSz, S16 copyBlock); S16 my_SpellCheck_OpenLex(const char FAR *fileName,S32 memBudget); S16 my_SpellCheck_OpenSession(void); S16 my_SpellCheck_ReplaceBlockWord(S16 blkId, const SpellCheck_CHAR FAR *word); U32 my_SpellCheck_SetOption(U32 option, U32 value); S16 my_SpellCheck_Suggest(const SpellCheck_CHAR FAR *word, S16 depth, SpellCheck_CHAR FAR *suggBfr, S32 suggBfrSz, S16 FAR *scores, S16 scoreSz); void my_SpellCheck_Version(S16 FAR *major, S16 FAR *minor); // Construction public: CSpellDialog( CSpell* pSpell, CWnd* pParent = NULL ); // standard constructor virtual ~CSpellDialog(); INT GetLastError() { return m_iError; }; BOOL FoundMisspelling() { return m_bFoundMisspelling; } void SetMisspellings( BOOL b ) { m_bFoundMisspelling = b; } ULONG GetOptionsMask() { return m_ulOptionsMask; } BOOL Popup(char* pWord, POINT& point, BOOL doubledWord = FALSE, int nHideIgnoreMenu = 0); BOOL DoCoolSpell( BOOL bSilent = FALSE ); int DoModalSpell( BOOL bAutoCheck = FALSE ); void AddToLex(SpellCheck_CHAR* probWord); void IgnoreAll(SpellCheck_CHAR* probWord); bool IsDialogOpen() { return m_bHasBeenInitialized; } BOOL m_bJustQueue; S16 my_SpellCheck_CheckWord(U32 options, const SpellCheck_CHAR FAR *word, SpellCheck_CHAR FAR *replWord, S16 replWordSz); // Dialog Data //{{AFX_DATA(CSpellDialog) enum { IDD = IDD_SPELL_CHECK_BLOCK }; // NOTE: the ClassWizard will add data members here //}}AFX_DATA // Overrides // ClassWizard generated virtual function overrides //{{AFX_VIRTUAL(CSpellDialog) protected: virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV support //}}AFX_VIRTUAL // Implementation protected: // Generated message map functions //{{AFX_MSG(CSpellDialog) virtual BOOL OnInitDialog(); afx_msg void OnMove(int x, int y); afx_msg void OnChangeReplacementWord(); afx_msg void OnIgnore(); afx_msg void OnIgnoreAll(); afx_msg void OnReplaceIt(); afx_msg void OnReplaceAll(); afx_msg void OnAddToLex(); afx_msg void OnSuggest(); afx_msg void OnDblclkSuggestList(); afx_msg void OnSelchangeSuggestList(); afx_msg void OnOptions(); afx_msg void OnJustDoIt(); afx_msg void OnEditLex(); //}}AFX_MSG void EndDialog(int nResult); afx_msg LRESULT OnContextMenu(WPARAM wParam, LPARAM lParam); afx_msg long OnHelp(WPARAM wParam, LPARAM lParam); afx_msg void OnDelete(); DECLARE_MESSAGE_MAP() }; //{{AFX_INSERT_LOCATION}} // Microsoft Developer Studio will insert additional declarations immediately before the previous line. #endif // !defined(AFX_SPELLDIALOG_H__4056D7B2_08FF_11D1_9818_00805FD2F268__INCLUDED_)
[ "peter@conglomo.co.nz" ]
peter@conglomo.co.nz
b60f80c29a2246d705cbb4a5f39761fed988f425
7ad1e8409d23ef82022a28fe58242d0736109530
/leetcode/027_Remove-Element/RemoveElement.cpp
fc67152668087e8ca259318ed15e02bc0df4af8d
[ "MIT" ]
permissive
chasingegg/Online_Judge
c96900f4ab8c93bf5863776408c3d47952632b1b
8a3f4b5b207cbeda921c743a527a25bf9c7b6248
refs/heads/master
2021-05-20T17:42:17.597158
2020-12-09T09:37:40
2020-12-09T09:37:40
83,519,213
1
0
null
null
null
null
UTF-8
C++
false
false
427
cpp
#include <iostream> #include <vector> using namespace std; class Solution { public: int removeElement(vector<int>& nums, int val) { int n = nums.size(); if (n == 0) return 0; int i = 0; while (i < nums.size()) { if (nums[i] == val) { nums.erase(nums.begin() + i); } else { ++i; } } return i; } };
[ "gaoc96@qq.com" ]
gaoc96@qq.com
cba4362a77273384f0f226536843b4eb9517af85
f8b043b42b0be6159db8099e8289cd4fd671722d
/UPDATEIT.cpp
8458d19662f41335a6278b6cce29e53e59c7b0fc
[]
no_license
priyanshu-28/Spoj-Solutions
251c332f7d7292fa45af73ec01acd3349a43913a
78a2104ddc73cf315245645640242825dc92b7af
refs/heads/master
2023-03-20T05:34:55.257835
2017-04-25T13:45:22
2017-04-25T13:45:22
null
0
0
null
null
null
null
UTF-8
C++
false
false
776
cpp
#include<bits/stdc++.h> using namespace std; void BIT(vector< int > &arr,int index,int n,int val) { index=index+1; while(index<=n) { arr[index]+=val; index+=index&(-index); } } void update(vector< int > &arr,int s,int e,int n,int val) { BIT(arr,s,n,val); BIT(arr,e+1,n,-val); } int find(vector< int > &arr,int in) { in=in+1; int result=0; while(in>0) { result+=arr[in]; in-=in&(-in); } return result; } int main() { int t; scanf("%d",&t); while(t--) { int n,u; scanf("%d%d",&n,&u); vector< int > arr(n+1,0); while(u--) { int s,e,val; scanf("%d%d%d",&s,&e,&val); update(arr,s,e,n,val); } int q; scanf("%d",&q); while(q--) { int in; scanf("%d",&in); printf("%d\n",find(arr,in)); } arr.clear(); } return 0; }
[ "Vengatesh" ]
Vengatesh
822afe51fee6e1ec68ec0604b8122572ebb40ed9
21fe9ddd8ba3a3798246be0f01a56a10e07acb2e
/v8/src/arm/lithium-arm.cc
0a76150ddc4ce720e9c69bb68c319008a78776d6
[ "bzip2-1.0.6", "BSD-3-Clause" ]
permissive
yong/xruby2
5e2ed23574b8f9f790b7df2ab347acca4f651373
ecc8fa062c30cb54ef41d2ccdbe46c6d5ffaa844
refs/heads/master
2021-01-20T11:26:04.196967
2011-12-02T17:40:48
2011-12-02T17:40:48
2,893,039
0
0
null
null
null
null
UTF-8
C++
false
false
74,065
cc
// Copyright 2011 the V8 project authors. All rights reserved. // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are // met: // // * Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above // copyright notice, this list of conditions and the following // disclaimer in the documentation and/or other materials provided // with the distribution. // * Neither the name of Google Inc. nor the names of its // contributors may be used to endorse or promote products derived // from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #include "v8.h" #include "lithium-allocator-inl.h" #include "arm/lithium-arm.h" #include "arm/lithium-codegen-arm.h" namespace v8 { namespace internal { #define DEFINE_COMPILE(type) \ void L##type::CompileToNative(LCodeGen* generator) { \ generator->Do##type(this); \ } LITHIUM_CONCRETE_INSTRUCTION_LIST(DEFINE_COMPILE) #undef DEFINE_COMPILE LOsrEntry::LOsrEntry() { for (int i = 0; i < Register::kNumAllocatableRegisters; ++i) { register_spills_[i] = NULL; } for (int i = 0; i < DoubleRegister::kNumAllocatableRegisters; ++i) { double_register_spills_[i] = NULL; } } void LOsrEntry::MarkSpilledRegister(int allocation_index, LOperand* spill_operand) { ASSERT(spill_operand->IsStackSlot()); ASSERT(register_spills_[allocation_index] == NULL); register_spills_[allocation_index] = spill_operand; } #ifdef DEBUG void LInstruction::VerifyCall() { // Call instructions can use only fixed registers as temporaries and // outputs because all registers are blocked by the calling convention. // Inputs operands must use a fixed register or use-at-start policy or // a non-register policy. ASSERT(Output() == NULL || LUnallocated::cast(Output())->HasFixedPolicy() || !LUnallocated::cast(Output())->HasRegisterPolicy()); for (UseIterator it(this); !it.Done(); it.Advance()) { LUnallocated* operand = LUnallocated::cast(it.Current()); ASSERT(operand->HasFixedPolicy() || operand->IsUsedAtStart()); } for (TempIterator it(this); !it.Done(); it.Advance()) { LUnallocated* operand = LUnallocated::cast(it.Current()); ASSERT(operand->HasFixedPolicy() ||!operand->HasRegisterPolicy()); } } #endif void LOsrEntry::MarkSpilledDoubleRegister(int allocation_index, LOperand* spill_operand) { ASSERT(spill_operand->IsDoubleStackSlot()); ASSERT(double_register_spills_[allocation_index] == NULL); double_register_spills_[allocation_index] = spill_operand; } void LInstruction::PrintTo(StringStream* stream) { stream->Add("%s ", this->Mnemonic()); PrintOutputOperandTo(stream); PrintDataTo(stream); if (HasEnvironment()) { stream->Add(" "); environment()->PrintTo(stream); } if (HasPointerMap()) { stream->Add(" "); pointer_map()->PrintTo(stream); } } template<int R, int I, int T> void LTemplateInstruction<R, I, T>::PrintDataTo(StringStream* stream) { stream->Add("= "); for (int i = 0; i < inputs_.length(); i++) { if (i > 0) stream->Add(" "); inputs_[i]->PrintTo(stream); } } template<int R, int I, int T> void LTemplateInstruction<R, I, T>::PrintOutputOperandTo(StringStream* stream) { for (int i = 0; i < results_.length(); i++) { if (i > 0) stream->Add(" "); results_[i]->PrintTo(stream); } } void LLabel::PrintDataTo(StringStream* stream) { LGap::PrintDataTo(stream); LLabel* rep = replacement(); if (rep != NULL) { stream->Add(" Dead block replaced with B%d", rep->block_id()); } } bool LGap::IsRedundant() const { for (int i = 0; i < 4; i++) { if (parallel_moves_[i] != NULL && !parallel_moves_[i]->IsRedundant()) { return false; } } return true; } void LGap::PrintDataTo(StringStream* stream) { for (int i = 0; i < 4; i++) { stream->Add("("); if (parallel_moves_[i] != NULL) { parallel_moves_[i]->PrintDataTo(stream); } stream->Add(") "); } } const char* LArithmeticD::Mnemonic() const { switch (op()) { case Token::ADD: return "add-d"; case Token::SUB: return "sub-d"; case Token::MUL: return "mul-d"; case Token::DIV: return "div-d"; case Token::MOD: return "mod-d"; default: UNREACHABLE(); return NULL; } } const char* LArithmeticT::Mnemonic() const { switch (op()) { case Token::ADD: return "add-t"; case Token::SUB: return "sub-t"; case Token::MUL: return "mul-t"; case Token::MOD: return "mod-t"; case Token::DIV: return "div-t"; case Token::BIT_AND: return "bit-and-t"; case Token::BIT_OR: return "bit-or-t"; case Token::BIT_XOR: return "bit-xor-t"; case Token::SHL: return "shl-t"; case Token::SAR: return "sar-t"; case Token::SHR: return "shr-t"; default: UNREACHABLE(); return NULL; } } void LGoto::PrintDataTo(StringStream* stream) { stream->Add("B%d", block_id()); } void LBranch::PrintDataTo(StringStream* stream) { stream->Add("B%d | B%d on ", true_block_id(), false_block_id()); InputAt(0)->PrintTo(stream); } void LCmpIDAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if "); InputAt(0)->PrintTo(stream); stream->Add(" %s ", Token::String(op())); InputAt(1)->PrintTo(stream); stream->Add(" then B%d else B%d", true_block_id(), false_block_id()); } void LIsNilAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if "); InputAt(0)->PrintTo(stream); stream->Add(kind() == kStrictEquality ? " === " : " == "); stream->Add(nil() == kNullValue ? "null" : "undefined"); stream->Add(" then B%d else B%d", true_block_id(), false_block_id()); } void LIsObjectAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if is_object("); InputAt(0)->PrintTo(stream); stream->Add(") then B%d else B%d", true_block_id(), false_block_id()); } void LIsStringAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if is_string("); InputAt(0)->PrintTo(stream); stream->Add(") then B%d else B%d", true_block_id(), false_block_id()); } void LIsSmiAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if is_smi("); InputAt(0)->PrintTo(stream); stream->Add(") then B%d else B%d", true_block_id(), false_block_id()); } void LIsUndetectableAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if is_undetectable("); InputAt(0)->PrintTo(stream); stream->Add(") then B%d else B%d", true_block_id(), false_block_id()); } void LStringCompareAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if string_compare("); InputAt(0)->PrintTo(stream); InputAt(1)->PrintTo(stream); stream->Add(") then B%d else B%d", true_block_id(), false_block_id()); } void LHasInstanceTypeAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if has_instance_type("); InputAt(0)->PrintTo(stream); stream->Add(") then B%d else B%d", true_block_id(), false_block_id()); } void LHasCachedArrayIndexAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if has_cached_array_index("); InputAt(0)->PrintTo(stream); stream->Add(") then B%d else B%d", true_block_id(), false_block_id()); } void LClassOfTestAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if class_of_test("); InputAt(0)->PrintTo(stream); stream->Add(", \"%o\") then B%d else B%d", *hydrogen()->class_name(), true_block_id(), false_block_id()); } void LTypeofIsAndBranch::PrintDataTo(StringStream* stream) { stream->Add("if typeof "); InputAt(0)->PrintTo(stream); stream->Add(" == \"%s\" then B%d else B%d", *hydrogen()->type_literal()->ToCString(), true_block_id(), false_block_id()); } void LCallConstantFunction::PrintDataTo(StringStream* stream) { stream->Add("#%d / ", arity()); } void LUnaryMathOperation::PrintDataTo(StringStream* stream) { stream->Add("/%s ", hydrogen()->OpName()); InputAt(0)->PrintTo(stream); } void LLoadContextSlot::PrintDataTo(StringStream* stream) { InputAt(0)->PrintTo(stream); stream->Add("[%d]", slot_index()); } void LStoreContextSlot::PrintDataTo(StringStream* stream) { InputAt(0)->PrintTo(stream); stream->Add("[%d] <- ", slot_index()); InputAt(1)->PrintTo(stream); } void LInvokeFunction::PrintDataTo(StringStream* stream) { stream->Add("= "); InputAt(0)->PrintTo(stream); stream->Add(" #%d / ", arity()); } void LCallKeyed::PrintDataTo(StringStream* stream) { stream->Add("[r2] #%d / ", arity()); } void LCallNamed::PrintDataTo(StringStream* stream) { SmartArrayPointer<char> name_string = name()->ToCString(); stream->Add("%s #%d / ", *name_string, arity()); } void LCallGlobal::PrintDataTo(StringStream* stream) { SmartArrayPointer<char> name_string = name()->ToCString(); stream->Add("%s #%d / ", *name_string, arity()); } void LCallKnownGlobal::PrintDataTo(StringStream* stream) { stream->Add("#%d / ", arity()); } void LCallNew::PrintDataTo(StringStream* stream) { stream->Add("= "); InputAt(0)->PrintTo(stream); stream->Add(" #%d / ", arity()); } void LAccessArgumentsAt::PrintDataTo(StringStream* stream) { arguments()->PrintTo(stream); stream->Add(" length "); length()->PrintTo(stream); stream->Add(" index "); index()->PrintTo(stream); } void LStoreNamedField::PrintDataTo(StringStream* stream) { object()->PrintTo(stream); stream->Add("."); stream->Add(*String::cast(*name())->ToCString()); stream->Add(" <- "); value()->PrintTo(stream); } void LStoreNamedGeneric::PrintDataTo(StringStream* stream) { object()->PrintTo(stream); stream->Add("."); stream->Add(*String::cast(*name())->ToCString()); stream->Add(" <- "); value()->PrintTo(stream); } void LStoreKeyedFastElement::PrintDataTo(StringStream* stream) { object()->PrintTo(stream); stream->Add("["); key()->PrintTo(stream); stream->Add("] <- "); value()->PrintTo(stream); } void LStoreKeyedFastDoubleElement::PrintDataTo(StringStream* stream) { elements()->PrintTo(stream); stream->Add("["); key()->PrintTo(stream); stream->Add("] <- "); value()->PrintTo(stream); } void LStoreKeyedGeneric::PrintDataTo(StringStream* stream) { object()->PrintTo(stream); stream->Add("["); key()->PrintTo(stream); stream->Add("] <- "); value()->PrintTo(stream); } void LTransitionElementsKind::PrintDataTo(StringStream* stream) { object()->PrintTo(stream); stream->Add(" %p -> %p", *original_map(), *transitioned_map()); } LChunk::LChunk(CompilationInfo* info, HGraph* graph) : spill_slot_count_(0), info_(info), graph_(graph), instructions_(32), pointer_maps_(8), inlined_closures_(1) { } int LChunk::GetNextSpillIndex(bool is_double) { // Skip a slot if for a double-width slot. if (is_double) spill_slot_count_++; return spill_slot_count_++; } LOperand* LChunk::GetNextSpillSlot(bool is_double) { int index = GetNextSpillIndex(is_double); if (is_double) { return LDoubleStackSlot::Create(index); } else { return LStackSlot::Create(index); } } void LChunk::MarkEmptyBlocks() { HPhase phase("Mark empty blocks", this); for (int i = 0; i < graph()->blocks()->length(); ++i) { HBasicBlock* block = graph()->blocks()->at(i); int first = block->first_instruction_index(); int last = block->last_instruction_index(); LInstruction* first_instr = instructions()->at(first); LInstruction* last_instr = instructions()->at(last); LLabel* label = LLabel::cast(first_instr); if (last_instr->IsGoto()) { LGoto* goto_instr = LGoto::cast(last_instr); if (label->IsRedundant() && !label->is_loop_header()) { bool can_eliminate = true; for (int i = first + 1; i < last && can_eliminate; ++i) { LInstruction* cur = instructions()->at(i); if (cur->IsGap()) { LGap* gap = LGap::cast(cur); if (!gap->IsRedundant()) { can_eliminate = false; } } else { can_eliminate = false; } } if (can_eliminate) { label->set_replacement(GetLabel(goto_instr->block_id())); } } } } } void LChunk::AddInstruction(LInstruction* instr, HBasicBlock* block) { LInstructionGap* gap = new LInstructionGap(block); int index = -1; if (instr->IsControl()) { instructions_.Add(gap); index = instructions_.length(); instructions_.Add(instr); } else { index = instructions_.length(); instructions_.Add(instr); instructions_.Add(gap); } if (instr->HasPointerMap()) { pointer_maps_.Add(instr->pointer_map()); instr->pointer_map()->set_lithium_position(index); } } LConstantOperand* LChunk::DefineConstantOperand(HConstant* constant) { return LConstantOperand::Create(constant->id()); } int LChunk::GetParameterStackSlot(int index) const { // The receiver is at index 0, the first parameter at index 1, so we // shift all parameter indexes down by the number of parameters, and // make sure they end up negative so they are distinguishable from // spill slots. int result = index - info()->scope()->num_parameters() - 1; ASSERT(result < 0); return result; } // A parameter relative to ebp in the arguments stub. int LChunk::ParameterAt(int index) { ASSERT(-1 <= index); // -1 is the receiver. return (1 + info()->scope()->num_parameters() - index) * kPointerSize; } LGap* LChunk::GetGapAt(int index) const { return LGap::cast(instructions_[index]); } bool LChunk::IsGapAt(int index) const { return instructions_[index]->IsGap(); } int LChunk::NearestGapPos(int index) const { while (!IsGapAt(index)) index--; return index; } void LChunk::AddGapMove(int index, LOperand* from, LOperand* to) { GetGapAt(index)->GetOrCreateParallelMove(LGap::START)->AddMove(from, to); } Handle<Object> LChunk::LookupLiteral(LConstantOperand* operand) const { return HConstant::cast(graph_->LookupValue(operand->index()))->handle(); } Representation LChunk::LookupLiteralRepresentation( LConstantOperand* operand) const { return graph_->LookupValue(operand->index())->representation(); } LChunk* LChunkBuilder::Build() { ASSERT(is_unused()); chunk_ = new LChunk(info(), graph()); HPhase phase("Building chunk", chunk_); status_ = BUILDING; const ZoneList<HBasicBlock*>* blocks = graph()->blocks(); for (int i = 0; i < blocks->length(); i++) { HBasicBlock* next = NULL; if (i < blocks->length() - 1) next = blocks->at(i + 1); DoBasicBlock(blocks->at(i), next); if (is_aborted()) return NULL; } status_ = DONE; return chunk_; } void LChunkBuilder::Abort(const char* format, ...) { if (FLAG_trace_bailout) { SmartArrayPointer<char> name( info()->shared_info()->DebugName()->ToCString()); PrintF("Aborting LChunk building in @\"%s\": ", *name); va_list arguments; va_start(arguments, format); OS::VPrint(format, arguments); va_end(arguments); PrintF("\n"); } status_ = ABORTED; } LRegister* LChunkBuilder::ToOperand(Register reg) { return LRegister::Create(Register::ToAllocationIndex(reg)); } LUnallocated* LChunkBuilder::ToUnallocated(Register reg) { return new LUnallocated(LUnallocated::FIXED_REGISTER, Register::ToAllocationIndex(reg)); } LUnallocated* LChunkBuilder::ToUnallocated(DoubleRegister reg) { return new LUnallocated(LUnallocated::FIXED_DOUBLE_REGISTER, DoubleRegister::ToAllocationIndex(reg)); } LOperand* LChunkBuilder::UseFixed(HValue* value, Register fixed_register) { return Use(value, ToUnallocated(fixed_register)); } LOperand* LChunkBuilder::UseFixedDouble(HValue* value, DoubleRegister reg) { return Use(value, ToUnallocated(reg)); } LOperand* LChunkBuilder::UseRegister(HValue* value) { return Use(value, new LUnallocated(LUnallocated::MUST_HAVE_REGISTER)); } LOperand* LChunkBuilder::UseRegisterAtStart(HValue* value) { return Use(value, new LUnallocated(LUnallocated::MUST_HAVE_REGISTER, LUnallocated::USED_AT_START)); } LOperand* LChunkBuilder::UseTempRegister(HValue* value) { return Use(value, new LUnallocated(LUnallocated::WRITABLE_REGISTER)); } LOperand* LChunkBuilder::Use(HValue* value) { return Use(value, new LUnallocated(LUnallocated::NONE)); } LOperand* LChunkBuilder::UseAtStart(HValue* value) { return Use(value, new LUnallocated(LUnallocated::NONE, LUnallocated::USED_AT_START)); } LOperand* LChunkBuilder::UseOrConstant(HValue* value) { return value->IsConstant() ? chunk_->DefineConstantOperand(HConstant::cast(value)) : Use(value); } LOperand* LChunkBuilder::UseOrConstantAtStart(HValue* value) { return value->IsConstant() ? chunk_->DefineConstantOperand(HConstant::cast(value)) : UseAtStart(value); } LOperand* LChunkBuilder::UseRegisterOrConstant(HValue* value) { return value->IsConstant() ? chunk_->DefineConstantOperand(HConstant::cast(value)) : UseRegister(value); } LOperand* LChunkBuilder::UseRegisterOrConstantAtStart(HValue* value) { return value->IsConstant() ? chunk_->DefineConstantOperand(HConstant::cast(value)) : UseRegisterAtStart(value); } LOperand* LChunkBuilder::UseAny(HValue* value) { return value->IsConstant() ? chunk_->DefineConstantOperand(HConstant::cast(value)) : Use(value, new LUnallocated(LUnallocated::ANY)); } LOperand* LChunkBuilder::Use(HValue* value, LUnallocated* operand) { if (value->EmitAtUses()) { HInstruction* instr = HInstruction::cast(value); VisitInstruction(instr); } allocator_->RecordUse(value, operand); return operand; } template<int I, int T> LInstruction* LChunkBuilder::Define(LTemplateInstruction<1, I, T>* instr, LUnallocated* result) { allocator_->RecordDefinition(current_instruction_, result); instr->set_result(result); return instr; } template<int I, int T> LInstruction* LChunkBuilder::Define(LTemplateInstruction<1, I, T>* instr) { return Define(instr, new LUnallocated(LUnallocated::NONE)); } template<int I, int T> LInstruction* LChunkBuilder::DefineAsRegister( LTemplateInstruction<1, I, T>* instr) { return Define(instr, new LUnallocated(LUnallocated::MUST_HAVE_REGISTER)); } template<int I, int T> LInstruction* LChunkBuilder::DefineAsSpilled( LTemplateInstruction<1, I, T>* instr, int index) { return Define(instr, new LUnallocated(LUnallocated::FIXED_SLOT, index)); } template<int I, int T> LInstruction* LChunkBuilder::DefineSameAsFirst( LTemplateInstruction<1, I, T>* instr) { return Define(instr, new LUnallocated(LUnallocated::SAME_AS_FIRST_INPUT)); } template<int I, int T> LInstruction* LChunkBuilder::DefineFixed( LTemplateInstruction<1, I, T>* instr, Register reg) { return Define(instr, ToUnallocated(reg)); } template<int I, int T> LInstruction* LChunkBuilder::DefineFixedDouble( LTemplateInstruction<1, I, T>* instr, DoubleRegister reg) { return Define(instr, ToUnallocated(reg)); } LInstruction* LChunkBuilder::AssignEnvironment(LInstruction* instr) { HEnvironment* hydrogen_env = current_block_->last_environment(); int argument_index_accumulator = 0; instr->set_environment(CreateEnvironment(hydrogen_env, &argument_index_accumulator)); return instr; } LInstruction* LChunkBuilder::SetInstructionPendingDeoptimizationEnvironment( LInstruction* instr, int ast_id) { ASSERT(instruction_pending_deoptimization_environment_ == NULL); ASSERT(pending_deoptimization_ast_id_ == AstNode::kNoNumber); instruction_pending_deoptimization_environment_ = instr; pending_deoptimization_ast_id_ = ast_id; return instr; } void LChunkBuilder::ClearInstructionPendingDeoptimizationEnvironment() { instruction_pending_deoptimization_environment_ = NULL; pending_deoptimization_ast_id_ = AstNode::kNoNumber; } LInstruction* LChunkBuilder::MarkAsCall(LInstruction* instr, HInstruction* hinstr, CanDeoptimize can_deoptimize) { #ifdef DEBUG instr->VerifyCall(); #endif instr->MarkAsCall(); instr = AssignPointerMap(instr); if (hinstr->HasObservableSideEffects()) { ASSERT(hinstr->next()->IsSimulate()); HSimulate* sim = HSimulate::cast(hinstr->next()); instr = SetInstructionPendingDeoptimizationEnvironment( instr, sim->ast_id()); } // If instruction does not have side-effects lazy deoptimization // after the call will try to deoptimize to the point before the call. // Thus we still need to attach environment to this call even if // call sequence can not deoptimize eagerly. bool needs_environment = (can_deoptimize == CAN_DEOPTIMIZE_EAGERLY) || !hinstr->HasObservableSideEffects(); if (needs_environment && !instr->HasEnvironment()) { instr = AssignEnvironment(instr); } return instr; } LInstruction* LChunkBuilder::MarkAsSaveDoubles(LInstruction* instr) { instr->MarkAsSaveDoubles(); return instr; } LInstruction* LChunkBuilder::AssignPointerMap(LInstruction* instr) { ASSERT(!instr->HasPointerMap()); instr->set_pointer_map(new LPointerMap(position_)); return instr; } LUnallocated* LChunkBuilder::TempRegister() { LUnallocated* operand = new LUnallocated(LUnallocated::MUST_HAVE_REGISTER); allocator_->RecordTemporary(operand); return operand; } LOperand* LChunkBuilder::FixedTemp(Register reg) { LUnallocated* operand = ToUnallocated(reg); allocator_->RecordTemporary(operand); return operand; } LOperand* LChunkBuilder::FixedTemp(DoubleRegister reg) { LUnallocated* operand = ToUnallocated(reg); allocator_->RecordTemporary(operand); return operand; } LInstruction* LChunkBuilder::DoBlockEntry(HBlockEntry* instr) { return new LLabel(instr->block()); } LInstruction* LChunkBuilder::DoSoftDeoptimize(HSoftDeoptimize* instr) { return AssignEnvironment(new LDeoptimize); } LInstruction* LChunkBuilder::DoDeoptimize(HDeoptimize* instr) { return AssignEnvironment(new LDeoptimize); } LInstruction* LChunkBuilder::DoShift(Token::Value op, HBitwiseBinaryOperation* instr) { if (instr->representation().IsTagged()) { ASSERT(instr->left()->representation().IsTagged()); ASSERT(instr->right()->representation().IsTagged()); LOperand* left = UseFixed(instr->left(), r1); LOperand* right = UseFixed(instr->right(), r0); LArithmeticT* result = new LArithmeticT(op, left, right); return MarkAsCall(DefineFixed(result, r0), instr); } ASSERT(instr->representation().IsInteger32()); ASSERT(instr->left()->representation().IsInteger32()); ASSERT(instr->right()->representation().IsInteger32()); LOperand* left = UseRegisterAtStart(instr->left()); HValue* right_value = instr->right(); LOperand* right = NULL; int constant_value = 0; if (right_value->IsConstant()) { HConstant* constant = HConstant::cast(right_value); right = chunk_->DefineConstantOperand(constant); constant_value = constant->Integer32Value() & 0x1f; } else { right = UseRegisterAtStart(right_value); } // Shift operations can only deoptimize if we do a logical shift // by 0 and the result cannot be truncated to int32. bool may_deopt = (op == Token::SHR && constant_value == 0); bool does_deopt = false; if (may_deopt) { for (HUseIterator it(instr->uses()); !it.Done(); it.Advance()) { if (!it.value()->CheckFlag(HValue::kTruncatingToInt32)) { does_deopt = true; break; } } } LInstruction* result = DefineAsRegister(new LShiftI(op, left, right, does_deopt)); return does_deopt ? AssignEnvironment(result) : result; } LInstruction* LChunkBuilder::DoArithmeticD(Token::Value op, HArithmeticBinaryOperation* instr) { ASSERT(instr->representation().IsDouble()); ASSERT(instr->left()->representation().IsDouble()); ASSERT(instr->right()->representation().IsDouble()); ASSERT(op != Token::MOD); LOperand* left = UseRegisterAtStart(instr->left()); LOperand* right = UseRegisterAtStart(instr->right()); LArithmeticD* result = new LArithmeticD(op, left, right); return DefineAsRegister(result); } LInstruction* LChunkBuilder::DoArithmeticT(Token::Value op, HArithmeticBinaryOperation* instr) { ASSERT(op == Token::ADD || op == Token::DIV || op == Token::MOD || op == Token::MUL || op == Token::SUB); HValue* left = instr->left(); HValue* right = instr->right(); ASSERT(left->representation().IsTagged()); ASSERT(right->representation().IsTagged()); LOperand* left_operand = UseFixed(left, r1); LOperand* right_operand = UseFixed(right, r0); LArithmeticT* result = new LArithmeticT(op, left_operand, right_operand); return MarkAsCall(DefineFixed(result, r0), instr); } void LChunkBuilder::DoBasicBlock(HBasicBlock* block, HBasicBlock* next_block) { ASSERT(is_building()); current_block_ = block; next_block_ = next_block; if (block->IsStartBlock()) { block->UpdateEnvironment(graph_->start_environment()); argument_count_ = 0; } else if (block->predecessors()->length() == 1) { // We have a single predecessor => copy environment and outgoing // argument count from the predecessor. ASSERT(block->phis()->length() == 0); HBasicBlock* pred = block->predecessors()->at(0); HEnvironment* last_environment = pred->last_environment(); ASSERT(last_environment != NULL); // Only copy the environment, if it is later used again. if (pred->end()->SecondSuccessor() == NULL) { ASSERT(pred->end()->FirstSuccessor() == block); } else { if (pred->end()->FirstSuccessor()->block_id() > block->block_id() || pred->end()->SecondSuccessor()->block_id() > block->block_id()) { last_environment = last_environment->Copy(); } } block->UpdateEnvironment(last_environment); ASSERT(pred->argument_count() >= 0); argument_count_ = pred->argument_count(); } else { // We are at a state join => process phis. HBasicBlock* pred = block->predecessors()->at(0); // No need to copy the environment, it cannot be used later. HEnvironment* last_environment = pred->last_environment(); for (int i = 0; i < block->phis()->length(); ++i) { HPhi* phi = block->phis()->at(i); last_environment->SetValueAt(phi->merged_index(), phi); } for (int i = 0; i < block->deleted_phis()->length(); ++i) { last_environment->SetValueAt(block->deleted_phis()->at(i), graph_->GetConstantUndefined()); } block->UpdateEnvironment(last_environment); // Pick up the outgoing argument count of one of the predecessors. argument_count_ = pred->argument_count(); } HInstruction* current = block->first(); int start = chunk_->instructions()->length(); while (current != NULL && !is_aborted()) { // Code for constants in registers is generated lazily. if (!current->EmitAtUses()) { VisitInstruction(current); } current = current->next(); } int end = chunk_->instructions()->length() - 1; if (end >= start) { block->set_first_instruction_index(start); block->set_last_instruction_index(end); } block->set_argument_count(argument_count_); next_block_ = NULL; current_block_ = NULL; } void LChunkBuilder::VisitInstruction(HInstruction* current) { HInstruction* old_current = current_instruction_; current_instruction_ = current; if (current->has_position()) position_ = current->position(); LInstruction* instr = current->CompileToLithium(this); if (instr != NULL) { if (FLAG_stress_pointer_maps && !instr->HasPointerMap()) { instr = AssignPointerMap(instr); } if (FLAG_stress_environments && !instr->HasEnvironment()) { instr = AssignEnvironment(instr); } instr->set_hydrogen_value(current); chunk_->AddInstruction(instr, current_block_); } current_instruction_ = old_current; } LEnvironment* LChunkBuilder::CreateEnvironment( HEnvironment* hydrogen_env, int* argument_index_accumulator) { if (hydrogen_env == NULL) return NULL; LEnvironment* outer = CreateEnvironment(hydrogen_env->outer(), argument_index_accumulator); int ast_id = hydrogen_env->ast_id(); ASSERT(ast_id != AstNode::kNoNumber); int value_count = hydrogen_env->length(); LEnvironment* result = new LEnvironment(hydrogen_env->closure(), ast_id, hydrogen_env->parameter_count(), argument_count_, value_count, outer); for (int i = 0; i < value_count; ++i) { if (hydrogen_env->is_special_index(i)) continue; HValue* value = hydrogen_env->values()->at(i); LOperand* op = NULL; if (value->IsArgumentsObject()) { op = NULL; } else if (value->IsPushArgument()) { op = new LArgument((*argument_index_accumulator)++); } else { op = UseAny(value); } result->AddValue(op, value->representation()); } return result; } LInstruction* LChunkBuilder::DoGoto(HGoto* instr) { return new LGoto(instr->FirstSuccessor()->block_id()); } LInstruction* LChunkBuilder::DoBranch(HBranch* instr) { HValue* v = instr->value(); if (v->EmitAtUses()) { HBasicBlock* successor = HConstant::cast(v)->ToBoolean() ? instr->FirstSuccessor() : instr->SecondSuccessor(); return new LGoto(successor->block_id()); } return AssignEnvironment(new LBranch(UseRegister(v))); } LInstruction* LChunkBuilder::DoCompareMap(HCompareMap* instr) { ASSERT(instr->value()->representation().IsTagged()); LOperand* value = UseRegisterAtStart(instr->value()); LOperand* temp = TempRegister(); return new LCmpMapAndBranch(value, temp); } LInstruction* LChunkBuilder::DoArgumentsLength(HArgumentsLength* length) { return DefineAsRegister(new LArgumentsLength(UseRegister(length->value()))); } LInstruction* LChunkBuilder::DoArgumentsElements(HArgumentsElements* elems) { return DefineAsRegister(new LArgumentsElements); } LInstruction* LChunkBuilder::DoInstanceOf(HInstanceOf* instr) { LInstanceOf* result = new LInstanceOf(UseFixed(instr->left(), r0), UseFixed(instr->right(), r1)); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoInstanceOfKnownGlobal( HInstanceOfKnownGlobal* instr) { LInstanceOfKnownGlobal* result = new LInstanceOfKnownGlobal(UseFixed(instr->left(), r0), FixedTemp(r4)); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoApplyArguments(HApplyArguments* instr) { LOperand* function = UseFixed(instr->function(), r1); LOperand* receiver = UseFixed(instr->receiver(), r0); LOperand* length = UseFixed(instr->length(), r2); LOperand* elements = UseFixed(instr->elements(), r3); LApplyArguments* result = new LApplyArguments(function, receiver, length, elements); return MarkAsCall(DefineFixed(result, r0), instr, CAN_DEOPTIMIZE_EAGERLY); } LInstruction* LChunkBuilder::DoPushArgument(HPushArgument* instr) { ++argument_count_; LOperand* argument = Use(instr->argument()); return new LPushArgument(argument); } LInstruction* LChunkBuilder::DoThisFunction(HThisFunction* instr) { return instr->HasNoUses() ? NULL : DefineAsRegister(new LThisFunction); } LInstruction* LChunkBuilder::DoContext(HContext* instr) { return instr->HasNoUses() ? NULL : DefineAsRegister(new LContext); } LInstruction* LChunkBuilder::DoOuterContext(HOuterContext* instr) { LOperand* context = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LOuterContext(context)); } LInstruction* LChunkBuilder::DoGlobalObject(HGlobalObject* instr) { LOperand* context = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LGlobalObject(context)); } LInstruction* LChunkBuilder::DoGlobalReceiver(HGlobalReceiver* instr) { LOperand* global_object = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LGlobalReceiver(global_object)); } LInstruction* LChunkBuilder::DoCallConstantFunction( HCallConstantFunction* instr) { argument_count_ -= instr->argument_count(); return MarkAsCall(DefineFixed(new LCallConstantFunction, r0), instr); } LInstruction* LChunkBuilder::DoInvokeFunction(HInvokeFunction* instr) { LOperand* function = UseFixed(instr->function(), r1); argument_count_ -= instr->argument_count(); LInvokeFunction* result = new LInvokeFunction(function); return MarkAsCall(DefineFixed(result, r0), instr, CANNOT_DEOPTIMIZE_EAGERLY); } LInstruction* LChunkBuilder::DoUnaryMathOperation(HUnaryMathOperation* instr) { BuiltinFunctionId op = instr->op(); if (op == kMathLog || op == kMathSin || op == kMathCos) { LOperand* input = UseFixedDouble(instr->value(), d2); LUnaryMathOperation* result = new LUnaryMathOperation(input, NULL); return MarkAsCall(DefineFixedDouble(result, d2), instr); } else { LOperand* input = UseRegisterAtStart(instr->value()); LOperand* temp = (op == kMathFloor) ? TempRegister() : NULL; LUnaryMathOperation* result = new LUnaryMathOperation(input, temp); switch (op) { case kMathAbs: return AssignEnvironment(AssignPointerMap(DefineAsRegister(result))); case kMathFloor: return AssignEnvironment(AssignPointerMap(DefineAsRegister(result))); case kMathSqrt: return DefineAsRegister(result); case kMathRound: return AssignEnvironment(DefineAsRegister(result)); case kMathPowHalf: return DefineAsRegister(result); default: UNREACHABLE(); return NULL; } } } LInstruction* LChunkBuilder::DoCallKeyed(HCallKeyed* instr) { ASSERT(instr->key()->representation().IsTagged()); argument_count_ -= instr->argument_count(); LOperand* key = UseFixed(instr->key(), r2); return MarkAsCall(DefineFixed(new LCallKeyed(key), r0), instr); } LInstruction* LChunkBuilder::DoCallNamed(HCallNamed* instr) { argument_count_ -= instr->argument_count(); return MarkAsCall(DefineFixed(new LCallNamed, r0), instr); } LInstruction* LChunkBuilder::DoCallGlobal(HCallGlobal* instr) { argument_count_ -= instr->argument_count(); return MarkAsCall(DefineFixed(new LCallGlobal, r0), instr); } LInstruction* LChunkBuilder::DoCallKnownGlobal(HCallKnownGlobal* instr) { argument_count_ -= instr->argument_count(); return MarkAsCall(DefineFixed(new LCallKnownGlobal, r0), instr); } LInstruction* LChunkBuilder::DoCallNew(HCallNew* instr) { LOperand* constructor = UseFixed(instr->constructor(), r1); argument_count_ -= instr->argument_count(); LCallNew* result = new LCallNew(constructor); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoCallFunction(HCallFunction* instr) { LOperand* function = UseFixed(instr->function(), r1); argument_count_ -= instr->argument_count(); return MarkAsCall(DefineFixed(new LCallFunction(function), r0), instr); } LInstruction* LChunkBuilder::DoCallRuntime(HCallRuntime* instr) { argument_count_ -= instr->argument_count(); return MarkAsCall(DefineFixed(new LCallRuntime, r0), instr); } LInstruction* LChunkBuilder::DoShr(HShr* instr) { return DoShift(Token::SHR, instr); } LInstruction* LChunkBuilder::DoSar(HSar* instr) { return DoShift(Token::SAR, instr); } LInstruction* LChunkBuilder::DoShl(HShl* instr) { return DoShift(Token::SHL, instr); } LInstruction* LChunkBuilder::DoBitwise(HBitwise* instr) { if (instr->representation().IsInteger32()) { ASSERT(instr->left()->representation().IsInteger32()); ASSERT(instr->right()->representation().IsInteger32()); LOperand* left = UseRegisterAtStart(instr->LeastConstantOperand()); LOperand* right = UseOrConstantAtStart(instr->MostConstantOperand()); return DefineAsRegister(new LBitI(left, right)); } else { ASSERT(instr->representation().IsTagged()); ASSERT(instr->left()->representation().IsTagged()); ASSERT(instr->right()->representation().IsTagged()); LOperand* left = UseFixed(instr->left(), r1); LOperand* right = UseFixed(instr->right(), r0); LArithmeticT* result = new LArithmeticT(instr->op(), left, right); return MarkAsCall(DefineFixed(result, r0), instr); } } LInstruction* LChunkBuilder::DoBitNot(HBitNot* instr) { ASSERT(instr->value()->representation().IsInteger32()); ASSERT(instr->representation().IsInteger32()); return DefineAsRegister(new LBitNotI(UseRegisterAtStart(instr->value()))); } LInstruction* LChunkBuilder::DoDiv(HDiv* instr) { if (instr->representation().IsDouble()) { return DoArithmeticD(Token::DIV, instr); } else if (instr->representation().IsInteger32()) { // TODO(1042) The fixed register allocation // is needed because we call TypeRecordingBinaryOpStub from // the generated code, which requires registers r0 // and r1 to be used. We should remove that // when we provide a native implementation. LOperand* dividend = UseFixed(instr->left(), r0); LOperand* divisor = UseFixed(instr->right(), r1); return AssignEnvironment(AssignPointerMap( DefineFixed(new LDivI(dividend, divisor), r0))); } else { return DoArithmeticT(Token::DIV, instr); } } LInstruction* LChunkBuilder::DoMod(HMod* instr) { if (instr->representation().IsInteger32()) { ASSERT(instr->left()->representation().IsInteger32()); ASSERT(instr->right()->representation().IsInteger32()); LModI* mod; if (instr->HasPowerOf2Divisor()) { ASSERT(!instr->CheckFlag(HValue::kCanBeDivByZero)); LOperand* value = UseRegisterAtStart(instr->left()); mod = new LModI(value, UseOrConstant(instr->right())); } else { LOperand* dividend = UseRegister(instr->left()); LOperand* divisor = UseRegister(instr->right()); mod = new LModI(dividend, divisor, TempRegister(), FixedTemp(d10), FixedTemp(d11)); } if (instr->CheckFlag(HValue::kBailoutOnMinusZero) || instr->CheckFlag(HValue::kCanBeDivByZero)) { return AssignEnvironment(DefineAsRegister(mod)); } else { return DefineAsRegister(mod); } } else if (instr->representation().IsTagged()) { return DoArithmeticT(Token::MOD, instr); } else { ASSERT(instr->representation().IsDouble()); // We call a C function for double modulo. It can't trigger a GC. // We need to use fixed result register for the call. // TODO(fschneider): Allow any register as input registers. LOperand* left = UseFixedDouble(instr->left(), d1); LOperand* right = UseFixedDouble(instr->right(), d2); LArithmeticD* result = new LArithmeticD(Token::MOD, left, right); return MarkAsCall(DefineFixedDouble(result, d1), instr); } } LInstruction* LChunkBuilder::DoMul(HMul* instr) { if (instr->representation().IsInteger32()) { ASSERT(instr->left()->representation().IsInteger32()); ASSERT(instr->right()->representation().IsInteger32()); LOperand* left; LOperand* right = UseOrConstant(instr->MostConstantOperand()); LOperand* temp = NULL; if (instr->CheckFlag(HValue::kBailoutOnMinusZero) && (instr->CheckFlag(HValue::kCanOverflow) || !right->IsConstantOperand())) { left = UseRegister(instr->LeastConstantOperand()); temp = TempRegister(); } else { left = UseRegisterAtStart(instr->LeastConstantOperand()); } return AssignEnvironment(DefineAsRegister(new LMulI(left, right, temp))); } else if (instr->representation().IsDouble()) { return DoArithmeticD(Token::MUL, instr); } else { return DoArithmeticT(Token::MUL, instr); } } LInstruction* LChunkBuilder::DoSub(HSub* instr) { if (instr->representation().IsInteger32()) { ASSERT(instr->left()->representation().IsInteger32()); ASSERT(instr->right()->representation().IsInteger32()); LOperand* left = UseRegisterAtStart(instr->left()); LOperand* right = UseOrConstantAtStart(instr->right()); LSubI* sub = new LSubI(left, right); LInstruction* result = DefineAsRegister(sub); if (instr->CheckFlag(HValue::kCanOverflow)) { result = AssignEnvironment(result); } return result; } else if (instr->representation().IsDouble()) { return DoArithmeticD(Token::SUB, instr); } else { return DoArithmeticT(Token::SUB, instr); } } LInstruction* LChunkBuilder::DoAdd(HAdd* instr) { if (instr->representation().IsInteger32()) { ASSERT(instr->left()->representation().IsInteger32()); ASSERT(instr->right()->representation().IsInteger32()); LOperand* left = UseRegisterAtStart(instr->LeastConstantOperand()); LOperand* right = UseOrConstantAtStart(instr->MostConstantOperand()); LAddI* add = new LAddI(left, right); LInstruction* result = DefineAsRegister(add); if (instr->CheckFlag(HValue::kCanOverflow)) { result = AssignEnvironment(result); } return result; } else if (instr->representation().IsDouble()) { return DoArithmeticD(Token::ADD, instr); } else { ASSERT(instr->representation().IsTagged()); return DoArithmeticT(Token::ADD, instr); } } LInstruction* LChunkBuilder::DoPower(HPower* instr) { ASSERT(instr->representation().IsDouble()); // We call a C function for double power. It can't trigger a GC. // We need to use fixed result register for the call. Representation exponent_type = instr->right()->representation(); ASSERT(instr->left()->representation().IsDouble()); LOperand* left = UseFixedDouble(instr->left(), d1); LOperand* right = exponent_type.IsDouble() ? UseFixedDouble(instr->right(), d2) : UseFixed(instr->right(), r0); LPower* result = new LPower(left, right); return MarkAsCall(DefineFixedDouble(result, d3), instr, CAN_DEOPTIMIZE_EAGERLY); } LInstruction* LChunkBuilder::DoCompareGeneric(HCompareGeneric* instr) { ASSERT(instr->left()->representation().IsTagged()); ASSERT(instr->right()->representation().IsTagged()); LOperand* left = UseFixed(instr->left(), r1); LOperand* right = UseFixed(instr->right(), r0); LCmpT* result = new LCmpT(left, right); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoCompareIDAndBranch( HCompareIDAndBranch* instr) { Representation r = instr->GetInputRepresentation(); if (r.IsInteger32()) { ASSERT(instr->left()->representation().IsInteger32()); ASSERT(instr->right()->representation().IsInteger32()); LOperand* left = UseRegisterOrConstantAtStart(instr->left()); LOperand* right = UseRegisterOrConstantAtStart(instr->right()); return new LCmpIDAndBranch(left, right); } else { ASSERT(r.IsDouble()); ASSERT(instr->left()->representation().IsDouble()); ASSERT(instr->right()->representation().IsDouble()); LOperand* left = UseRegisterAtStart(instr->left()); LOperand* right = UseRegisterAtStart(instr->right()); return new LCmpIDAndBranch(left, right); } } LInstruction* LChunkBuilder::DoCompareObjectEqAndBranch( HCompareObjectEqAndBranch* instr) { LOperand* left = UseRegisterAtStart(instr->left()); LOperand* right = UseRegisterAtStart(instr->right()); return new LCmpObjectEqAndBranch(left, right); } LInstruction* LChunkBuilder::DoCompareConstantEqAndBranch( HCompareConstantEqAndBranch* instr) { return new LCmpConstantEqAndBranch(UseRegisterAtStart(instr->value())); } LInstruction* LChunkBuilder::DoIsNilAndBranch(HIsNilAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); return new LIsNilAndBranch(UseRegisterAtStart(instr->value())); } LInstruction* LChunkBuilder::DoIsObjectAndBranch(HIsObjectAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); LOperand* temp = TempRegister(); return new LIsObjectAndBranch(UseRegisterAtStart(instr->value()), temp); } LInstruction* LChunkBuilder::DoIsStringAndBranch(HIsStringAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); LOperand* temp = TempRegister(); return new LIsStringAndBranch(UseRegisterAtStart(instr->value()), temp); } LInstruction* LChunkBuilder::DoIsSmiAndBranch(HIsSmiAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); return new LIsSmiAndBranch(Use(instr->value())); } LInstruction* LChunkBuilder::DoIsUndetectableAndBranch( HIsUndetectableAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); return new LIsUndetectableAndBranch(UseRegisterAtStart(instr->value()), TempRegister()); } LInstruction* LChunkBuilder::DoStringCompareAndBranch( HStringCompareAndBranch* instr) { ASSERT(instr->left()->representation().IsTagged()); ASSERT(instr->right()->representation().IsTagged()); LOperand* left = UseFixed(instr->left(), r1); LOperand* right = UseFixed(instr->right(), r0); LStringCompareAndBranch* result = new LStringCompareAndBranch(left, right); return MarkAsCall(result, instr); } LInstruction* LChunkBuilder::DoHasInstanceTypeAndBranch( HHasInstanceTypeAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); return new LHasInstanceTypeAndBranch(UseRegisterAtStart(instr->value())); } LInstruction* LChunkBuilder::DoGetCachedArrayIndex( HGetCachedArrayIndex* instr) { ASSERT(instr->value()->representation().IsTagged()); LOperand* value = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LGetCachedArrayIndex(value)); } LInstruction* LChunkBuilder::DoHasCachedArrayIndexAndBranch( HHasCachedArrayIndexAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); return new LHasCachedArrayIndexAndBranch( UseRegisterAtStart(instr->value())); } LInstruction* LChunkBuilder::DoClassOfTestAndBranch( HClassOfTestAndBranch* instr) { ASSERT(instr->value()->representation().IsTagged()); return new LClassOfTestAndBranch(UseTempRegister(instr->value()), TempRegister()); } LInstruction* LChunkBuilder::DoJSArrayLength(HJSArrayLength* instr) { LOperand* array = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LJSArrayLength(array)); } LInstruction* LChunkBuilder::DoFixedArrayBaseLength( HFixedArrayBaseLength* instr) { LOperand* array = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LFixedArrayBaseLength(array)); } LInstruction* LChunkBuilder::DoElementsKind(HElementsKind* instr) { LOperand* object = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LElementsKind(object)); } LInstruction* LChunkBuilder::DoValueOf(HValueOf* instr) { LOperand* object = UseRegister(instr->value()); LValueOf* result = new LValueOf(object, TempRegister()); return AssignEnvironment(DefineAsRegister(result)); } LInstruction* LChunkBuilder::DoBoundsCheck(HBoundsCheck* instr) { return AssignEnvironment(new LBoundsCheck(UseRegisterAtStart(instr->index()), UseRegister(instr->length()))); } LInstruction* LChunkBuilder::DoAbnormalExit(HAbnormalExit* instr) { // The control instruction marking the end of a block that completed // abruptly (e.g., threw an exception). There is nothing specific to do. return NULL; } LInstruction* LChunkBuilder::DoThrow(HThrow* instr) { LOperand* value = UseFixed(instr->value(), r0); return MarkAsCall(new LThrow(value), instr); } LInstruction* LChunkBuilder::DoUseConst(HUseConst* instr) { return NULL; } LInstruction* LChunkBuilder::DoForceRepresentation(HForceRepresentation* bad) { // All HForceRepresentation instructions should be eliminated in the // representation change phase of Hydrogen. UNREACHABLE(); return NULL; } LInstruction* LChunkBuilder::DoChange(HChange* instr) { Representation from = instr->from(); Representation to = instr->to(); if (from.IsTagged()) { if (to.IsDouble()) { LOperand* value = UseRegister(instr->value()); LNumberUntagD* res = new LNumberUntagD(value); return AssignEnvironment(DefineAsRegister(res)); } else { ASSERT(to.IsInteger32()); LOperand* value = UseRegister(instr->value()); bool needs_check = !instr->value()->type().IsSmi(); LInstruction* res = NULL; if (!needs_check) { res = DefineSameAsFirst(new LSmiUntag(value, needs_check)); } else { LOperand* temp1 = TempRegister(); LOperand* temp2 = instr->CanTruncateToInt32() ? TempRegister() : NULL; LOperand* temp3 = instr->CanTruncateToInt32() ? FixedTemp(d11) : NULL; res = DefineSameAsFirst(new LTaggedToI(value, temp1, temp2, temp3)); res = AssignEnvironment(res); } return res; } } else if (from.IsDouble()) { if (to.IsTagged()) { LOperand* value = UseRegister(instr->value()); LOperand* temp1 = TempRegister(); LOperand* temp2 = TempRegister(); // Make sure that the temp and result_temp registers are // different. LUnallocated* result_temp = TempRegister(); LNumberTagD* result = new LNumberTagD(value, temp1, temp2); Define(result, result_temp); return AssignPointerMap(result); } else { ASSERT(to.IsInteger32()); LOperand* value = UseRegister(instr->value()); LDoubleToI* res = new LDoubleToI(value, TempRegister(), instr->CanTruncateToInt32() ? TempRegister() : NULL); return AssignEnvironment(DefineAsRegister(res)); } } else if (from.IsInteger32()) { if (to.IsTagged()) { HValue* val = instr->value(); LOperand* value = UseRegister(val); if (val->HasRange() && val->range()->IsInSmiRange()) { return DefineSameAsFirst(new LSmiTag(value)); } else { LNumberTagI* result = new LNumberTagI(value); return AssignEnvironment(AssignPointerMap(DefineSameAsFirst(result))); } } else { ASSERT(to.IsDouble()); LOperand* value = Use(instr->value()); return DefineAsRegister(new LInteger32ToDouble(value)); } } UNREACHABLE(); return NULL; } LInstruction* LChunkBuilder::DoCheckNonSmi(HCheckNonSmi* instr) { LOperand* value = UseRegisterAtStart(instr->value()); return AssignEnvironment(new LCheckNonSmi(value)); } LInstruction* LChunkBuilder::DoCheckInstanceType(HCheckInstanceType* instr) { LOperand* value = UseRegisterAtStart(instr->value()); LInstruction* result = new LCheckInstanceType(value); return AssignEnvironment(result); } LInstruction* LChunkBuilder::DoCheckPrototypeMaps(HCheckPrototypeMaps* instr) { LOperand* temp1 = TempRegister(); LOperand* temp2 = TempRegister(); LInstruction* result = new LCheckPrototypeMaps(temp1, temp2); return AssignEnvironment(result); } LInstruction* LChunkBuilder::DoCheckSmi(HCheckSmi* instr) { LOperand* value = UseRegisterAtStart(instr->value()); return AssignEnvironment(new LCheckSmi(value)); } LInstruction* LChunkBuilder::DoCheckFunction(HCheckFunction* instr) { LOperand* value = UseRegisterAtStart(instr->value()); return AssignEnvironment(new LCheckFunction(value)); } LInstruction* LChunkBuilder::DoCheckMap(HCheckMap* instr) { LOperand* value = UseRegisterAtStart(instr->value()); LInstruction* result = new LCheckMap(value); return AssignEnvironment(result); } LInstruction* LChunkBuilder::DoClampToUint8(HClampToUint8* instr) { HValue* value = instr->value(); Representation input_rep = value->representation(); LOperand* reg = UseRegister(value); if (input_rep.IsDouble()) { return DefineAsRegister(new LClampDToUint8(reg, FixedTemp(d11))); } else if (input_rep.IsInteger32()) { return DefineAsRegister(new LClampIToUint8(reg)); } else { ASSERT(input_rep.IsTagged()); // Register allocator doesn't (yet) support allocation of double // temps. Reserve d1 explicitly. LClampTToUint8* result = new LClampTToUint8(reg, FixedTemp(d11)); return AssignEnvironment(DefineAsRegister(result)); } } LInstruction* LChunkBuilder::DoToInt32(HToInt32* instr) { HValue* value = instr->value(); Representation input_rep = value->representation(); LOperand* reg = UseRegister(value); if (input_rep.IsDouble()) { LOperand* temp1 = TempRegister(); LOperand* temp2 = TempRegister(); LDoubleToI* res = new LDoubleToI(reg, temp1, temp2); return AssignEnvironment(DefineAsRegister(res)); } else if (input_rep.IsInteger32()) { // Canonicalization should already have removed the hydrogen instruction in // this case, since it is a noop. UNREACHABLE(); return NULL; } else { ASSERT(input_rep.IsTagged()); LOperand* temp1 = TempRegister(); LOperand* temp2 = TempRegister(); LOperand* temp3 = FixedTemp(d11); LTaggedToI* res = new LTaggedToI(reg, temp1, temp2, temp3); return AssignEnvironment(DefineSameAsFirst(res)); } } LInstruction* LChunkBuilder::DoReturn(HReturn* instr) { return new LReturn(UseFixed(instr->value(), r0)); } LInstruction* LChunkBuilder::DoConstant(HConstant* instr) { Representation r = instr->representation(); if (r.IsInteger32()) { return DefineAsRegister(new LConstantI); } else if (r.IsDouble()) { return DefineAsRegister(new LConstantD); } else if (r.IsTagged()) { return DefineAsRegister(new LConstantT); } else { UNREACHABLE(); return NULL; } } LInstruction* LChunkBuilder::DoLoadGlobalCell(HLoadGlobalCell* instr) { LLoadGlobalCell* result = new LLoadGlobalCell; return instr->RequiresHoleCheck() ? AssignEnvironment(DefineAsRegister(result)) : DefineAsRegister(result); } LInstruction* LChunkBuilder::DoLoadGlobalGeneric(HLoadGlobalGeneric* instr) { LOperand* global_object = UseFixed(instr->global_object(), r0); LLoadGlobalGeneric* result = new LLoadGlobalGeneric(global_object); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoStoreGlobalCell(HStoreGlobalCell* instr) { LOperand* temp = TempRegister(); LOperand* value = UseTempRegister(instr->value()); LInstruction* result = new LStoreGlobalCell(value, temp); if (instr->RequiresHoleCheck()) result = AssignEnvironment(result); return result; } LInstruction* LChunkBuilder::DoStoreGlobalGeneric(HStoreGlobalGeneric* instr) { LOperand* global_object = UseFixed(instr->global_object(), r1); LOperand* value = UseFixed(instr->value(), r0); LStoreGlobalGeneric* result = new LStoreGlobalGeneric(global_object, value); return MarkAsCall(result, instr); } LInstruction* LChunkBuilder::DoLoadContextSlot(HLoadContextSlot* instr) { LOperand* context = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LLoadContextSlot(context)); } LInstruction* LChunkBuilder::DoStoreContextSlot(HStoreContextSlot* instr) { LOperand* context; LOperand* value; if (instr->NeedsWriteBarrier()) { context = UseTempRegister(instr->context()); value = UseTempRegister(instr->value()); } else { context = UseRegister(instr->context()); value = UseRegister(instr->value()); } return new LStoreContextSlot(context, value); } LInstruction* LChunkBuilder::DoLoadNamedField(HLoadNamedField* instr) { return DefineAsRegister( new LLoadNamedField(UseRegisterAtStart(instr->object()))); } LInstruction* LChunkBuilder::DoLoadNamedFieldPolymorphic( HLoadNamedFieldPolymorphic* instr) { ASSERT(instr->representation().IsTagged()); if (instr->need_generic()) { LOperand* obj = UseFixed(instr->object(), r0); LLoadNamedFieldPolymorphic* result = new LLoadNamedFieldPolymorphic(obj); return MarkAsCall(DefineFixed(result, r0), instr); } else { LOperand* obj = UseRegisterAtStart(instr->object()); LLoadNamedFieldPolymorphic* result = new LLoadNamedFieldPolymorphic(obj); return AssignEnvironment(DefineAsRegister(result)); } } LInstruction* LChunkBuilder::DoLoadNamedGeneric(HLoadNamedGeneric* instr) { LOperand* object = UseFixed(instr->object(), r0); LInstruction* result = DefineFixed(new LLoadNamedGeneric(object), r0); return MarkAsCall(result, instr); } LInstruction* LChunkBuilder::DoLoadFunctionPrototype( HLoadFunctionPrototype* instr) { return AssignEnvironment(DefineAsRegister( new LLoadFunctionPrototype(UseRegister(instr->function())))); } LInstruction* LChunkBuilder::DoLoadElements(HLoadElements* instr) { LOperand* input = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LLoadElements(input)); } LInstruction* LChunkBuilder::DoLoadExternalArrayPointer( HLoadExternalArrayPointer* instr) { LOperand* input = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LLoadExternalArrayPointer(input)); } LInstruction* LChunkBuilder::DoLoadKeyedFastElement( HLoadKeyedFastElement* instr) { ASSERT(instr->representation().IsTagged()); ASSERT(instr->key()->representation().IsInteger32()); LOperand* obj = UseRegisterAtStart(instr->object()); LOperand* key = UseRegisterAtStart(instr->key()); LLoadKeyedFastElement* result = new LLoadKeyedFastElement(obj, key); return AssignEnvironment(DefineAsRegister(result)); } LInstruction* LChunkBuilder::DoLoadKeyedFastDoubleElement( HLoadKeyedFastDoubleElement* instr) { ASSERT(instr->representation().IsDouble()); ASSERT(instr->key()->representation().IsInteger32()); LOperand* elements = UseTempRegister(instr->elements()); LOperand* key = UseRegisterOrConstantAtStart(instr->key()); LLoadKeyedFastDoubleElement* result = new LLoadKeyedFastDoubleElement(elements, key); return AssignEnvironment(DefineAsRegister(result)); } LInstruction* LChunkBuilder::DoLoadKeyedSpecializedArrayElement( HLoadKeyedSpecializedArrayElement* instr) { ElementsKind elements_kind = instr->elements_kind(); Representation representation(instr->representation()); ASSERT( (representation.IsInteger32() && (elements_kind != EXTERNAL_FLOAT_ELEMENTS) && (elements_kind != EXTERNAL_DOUBLE_ELEMENTS)) || (representation.IsDouble() && ((elements_kind == EXTERNAL_FLOAT_ELEMENTS) || (elements_kind == EXTERNAL_DOUBLE_ELEMENTS)))); ASSERT(instr->key()->representation().IsInteger32()); LOperand* external_pointer = UseRegister(instr->external_pointer()); LOperand* key = UseRegisterOrConstant(instr->key()); LLoadKeyedSpecializedArrayElement* result = new LLoadKeyedSpecializedArrayElement(external_pointer, key); LInstruction* load_instr = DefineAsRegister(result); // An unsigned int array load might overflow and cause a deopt, make sure it // has an environment. return (elements_kind == EXTERNAL_UNSIGNED_INT_ELEMENTS) ? AssignEnvironment(load_instr) : load_instr; } LInstruction* LChunkBuilder::DoLoadKeyedGeneric(HLoadKeyedGeneric* instr) { LOperand* object = UseFixed(instr->object(), r1); LOperand* key = UseFixed(instr->key(), r0); LInstruction* result = DefineFixed(new LLoadKeyedGeneric(object, key), r0); return MarkAsCall(result, instr); } LInstruction* LChunkBuilder::DoStoreKeyedFastElement( HStoreKeyedFastElement* instr) { bool needs_write_barrier = instr->NeedsWriteBarrier(); ASSERT(instr->value()->representation().IsTagged()); ASSERT(instr->object()->representation().IsTagged()); ASSERT(instr->key()->representation().IsInteger32()); LOperand* obj = UseTempRegister(instr->object()); LOperand* val = needs_write_barrier ? UseTempRegister(instr->value()) : UseRegisterAtStart(instr->value()); LOperand* key = needs_write_barrier ? UseTempRegister(instr->key()) : UseRegisterOrConstantAtStart(instr->key()); return AssignEnvironment(new LStoreKeyedFastElement(obj, key, val)); } LInstruction* LChunkBuilder::DoStoreKeyedFastDoubleElement( HStoreKeyedFastDoubleElement* instr) { ASSERT(instr->value()->representation().IsDouble()); ASSERT(instr->elements()->representation().IsTagged()); ASSERT(instr->key()->representation().IsInteger32()); LOperand* elements = UseRegisterAtStart(instr->elements()); LOperand* val = UseTempRegister(instr->value()); LOperand* key = UseRegisterOrConstantAtStart(instr->key()); return new LStoreKeyedFastDoubleElement(elements, key, val); } LInstruction* LChunkBuilder::DoStoreKeyedSpecializedArrayElement( HStoreKeyedSpecializedArrayElement* instr) { Representation representation(instr->value()->representation()); ElementsKind elements_kind = instr->elements_kind(); ASSERT( (representation.IsInteger32() && (elements_kind != EXTERNAL_FLOAT_ELEMENTS) && (elements_kind != EXTERNAL_DOUBLE_ELEMENTS)) || (representation.IsDouble() && ((elements_kind == EXTERNAL_FLOAT_ELEMENTS) || (elements_kind == EXTERNAL_DOUBLE_ELEMENTS)))); ASSERT(instr->external_pointer()->representation().IsExternal()); ASSERT(instr->key()->representation().IsInteger32()); LOperand* external_pointer = UseRegister(instr->external_pointer()); bool val_is_temp_register = elements_kind == EXTERNAL_PIXEL_ELEMENTS || elements_kind == EXTERNAL_FLOAT_ELEMENTS; LOperand* val = val_is_temp_register ? UseTempRegister(instr->value()) : UseRegister(instr->value()); LOperand* key = UseRegisterOrConstant(instr->key()); return new LStoreKeyedSpecializedArrayElement(external_pointer, key, val); } LInstruction* LChunkBuilder::DoStoreKeyedGeneric(HStoreKeyedGeneric* instr) { LOperand* obj = UseFixed(instr->object(), r2); LOperand* key = UseFixed(instr->key(), r1); LOperand* val = UseFixed(instr->value(), r0); ASSERT(instr->object()->representation().IsTagged()); ASSERT(instr->key()->representation().IsTagged()); ASSERT(instr->value()->representation().IsTagged()); return MarkAsCall(new LStoreKeyedGeneric(obj, key, val), instr); } LInstruction* LChunkBuilder::DoTransitionElementsKind( HTransitionElementsKind* instr) { if (instr->original_map()->elements_kind() == FAST_SMI_ONLY_ELEMENTS && instr->transitioned_map()->elements_kind() == FAST_ELEMENTS) { LOperand* object = UseRegister(instr->object()); LOperand* new_map_reg = TempRegister(); LTransitionElementsKind* result = new LTransitionElementsKind(object, new_map_reg, NULL); return DefineSameAsFirst(result); } else { LOperand* object = UseFixed(instr->object(), r0); LOperand* fixed_object_reg = FixedTemp(r2); LOperand* new_map_reg = FixedTemp(r3); LTransitionElementsKind* result = new LTransitionElementsKind(object, new_map_reg, fixed_object_reg); return MarkAsCall(DefineFixed(result, r0), instr); } } LInstruction* LChunkBuilder::DoStoreNamedField(HStoreNamedField* instr) { bool needs_write_barrier = instr->NeedsWriteBarrier(); LOperand* obj = needs_write_barrier ? UseTempRegister(instr->object()) : UseRegisterAtStart(instr->object()); LOperand* val = needs_write_barrier ? UseTempRegister(instr->value()) : UseRegister(instr->value()); return new LStoreNamedField(obj, val); } LInstruction* LChunkBuilder::DoStoreNamedGeneric(HStoreNamedGeneric* instr) { LOperand* obj = UseFixed(instr->object(), r1); LOperand* val = UseFixed(instr->value(), r0); LInstruction* result = new LStoreNamedGeneric(obj, val); return MarkAsCall(result, instr); } LInstruction* LChunkBuilder::DoStringAdd(HStringAdd* instr) { LOperand* left = UseRegisterAtStart(instr->left()); LOperand* right = UseRegisterAtStart(instr->right()); return MarkAsCall(DefineFixed(new LStringAdd(left, right), r0), instr); } LInstruction* LChunkBuilder::DoStringCharCodeAt(HStringCharCodeAt* instr) { LOperand* string = UseTempRegister(instr->string()); LOperand* index = UseTempRegister(instr->index()); LStringCharCodeAt* result = new LStringCharCodeAt(string, index); return AssignEnvironment(AssignPointerMap(DefineAsRegister(result))); } LInstruction* LChunkBuilder::DoStringCharFromCode(HStringCharFromCode* instr) { LOperand* char_code = UseRegister(instr->value()); LStringCharFromCode* result = new LStringCharFromCode(char_code); return AssignPointerMap(DefineAsRegister(result)); } LInstruction* LChunkBuilder::DoStringLength(HStringLength* instr) { LOperand* string = UseRegisterAtStart(instr->value()); return DefineAsRegister(new LStringLength(string)); } LInstruction* LChunkBuilder::DoArrayLiteral(HArrayLiteral* instr) { return MarkAsCall(DefineFixed(new LArrayLiteral, r0), instr); } LInstruction* LChunkBuilder::DoObjectLiteralFast(HObjectLiteralFast* instr) { return MarkAsCall(DefineFixed(new LObjectLiteralFast, r0), instr); } LInstruction* LChunkBuilder::DoObjectLiteralGeneric( HObjectLiteralGeneric* instr) { return MarkAsCall(DefineFixed(new LObjectLiteralGeneric, r0), instr); } LInstruction* LChunkBuilder::DoRegExpLiteral(HRegExpLiteral* instr) { return MarkAsCall(DefineFixed(new LRegExpLiteral, r0), instr); } LInstruction* LChunkBuilder::DoFunctionLiteral(HFunctionLiteral* instr) { return MarkAsCall(DefineFixed(new LFunctionLiteral, r0), instr); } LInstruction* LChunkBuilder::DoDeleteProperty(HDeleteProperty* instr) { LOperand* object = UseFixed(instr->object(), r0); LOperand* key = UseFixed(instr->key(), r1); LDeleteProperty* result = new LDeleteProperty(object, key); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoOsrEntry(HOsrEntry* instr) { allocator_->MarkAsOsrEntry(); current_block_->last_environment()->set_ast_id(instr->ast_id()); return AssignEnvironment(new LOsrEntry); } LInstruction* LChunkBuilder::DoParameter(HParameter* instr) { int spill_index = chunk()->GetParameterStackSlot(instr->index()); return DefineAsSpilled(new LParameter, spill_index); } LInstruction* LChunkBuilder::DoUnknownOSRValue(HUnknownOSRValue* instr) { int spill_index = chunk()->GetNextSpillIndex(false); // Not double-width. if (spill_index > LUnallocated::kMaxFixedIndex) { Abort("Too many spill slots needed for OSR"); spill_index = 0; } return DefineAsSpilled(new LUnknownOSRValue, spill_index); } LInstruction* LChunkBuilder::DoCallStub(HCallStub* instr) { argument_count_ -= instr->argument_count(); return MarkAsCall(DefineFixed(new LCallStub, r0), instr); } LInstruction* LChunkBuilder::DoArgumentsObject(HArgumentsObject* instr) { // There are no real uses of the arguments object. // arguments.length and element access are supported directly on // stack arguments, and any real arguments object use causes a bailout. // So this value is never used. return NULL; } LInstruction* LChunkBuilder::DoAccessArgumentsAt(HAccessArgumentsAt* instr) { LOperand* arguments = UseRegister(instr->arguments()); LOperand* length = UseTempRegister(instr->length()); LOperand* index = UseRegister(instr->index()); LAccessArgumentsAt* result = new LAccessArgumentsAt(arguments, length, index); return AssignEnvironment(DefineAsRegister(result)); } LInstruction* LChunkBuilder::DoToFastProperties(HToFastProperties* instr) { LOperand* object = UseFixed(instr->value(), r0); LToFastProperties* result = new LToFastProperties(object); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoTypeof(HTypeof* instr) { LTypeof* result = new LTypeof(UseFixed(instr->value(), r0)); return MarkAsCall(DefineFixed(result, r0), instr); } LInstruction* LChunkBuilder::DoTypeofIsAndBranch(HTypeofIsAndBranch* instr) { return new LTypeofIsAndBranch(UseTempRegister(instr->value())); } LInstruction* LChunkBuilder::DoIsConstructCallAndBranch( HIsConstructCallAndBranch* instr) { return new LIsConstructCallAndBranch(TempRegister()); } LInstruction* LChunkBuilder::DoSimulate(HSimulate* instr) { HEnvironment* env = current_block_->last_environment(); ASSERT(env != NULL); env->set_ast_id(instr->ast_id()); env->Drop(instr->pop_count()); for (int i = 0; i < instr->values()->length(); ++i) { HValue* value = instr->values()->at(i); if (instr->HasAssignedIndexAt(i)) { env->Bind(instr->GetAssignedIndexAt(i), value); } else { env->Push(value); } } // If there is an instruction pending deoptimization environment create a // lazy bailout instruction to capture the environment. if (pending_deoptimization_ast_id_ == instr->ast_id()) { LInstruction* result = new LLazyBailout; result = AssignEnvironment(result); instruction_pending_deoptimization_environment_-> set_deoptimization_environment(result->environment()); ClearInstructionPendingDeoptimizationEnvironment(); return result; } return NULL; } LInstruction* LChunkBuilder::DoStackCheck(HStackCheck* instr) { if (instr->is_function_entry()) { return MarkAsCall(new LStackCheck, instr); } else { ASSERT(instr->is_backwards_branch()); return AssignEnvironment(AssignPointerMap(new LStackCheck)); } } LInstruction* LChunkBuilder::DoEnterInlined(HEnterInlined* instr) { HEnvironment* outer = current_block_->last_environment(); HConstant* undefined = graph()->GetConstantUndefined(); HEnvironment* inner = outer->CopyForInlining(instr->closure(), instr->function(), undefined, instr->call_kind()); current_block_->UpdateEnvironment(inner); chunk_->AddInlinedClosure(instr->closure()); return NULL; } LInstruction* LChunkBuilder::DoLeaveInlined(HLeaveInlined* instr) { HEnvironment* outer = current_block_->last_environment()->outer(); current_block_->UpdateEnvironment(outer); return NULL; } LInstruction* LChunkBuilder::DoIn(HIn* instr) { LOperand* key = UseRegisterAtStart(instr->key()); LOperand* object = UseRegisterAtStart(instr->object()); LIn* result = new LIn(key, object); return MarkAsCall(DefineFixed(result, r0), instr); } } } // namespace v8::internal
[ "yong@intridea.com" ]
yong@intridea.com
9e3520371ca50ddecd704337797928644f2fe705
45cca9d2f309faeb94ded9f5e5adfc45d3d70d3f
/heap/main.cpp
88eb23e01ac6d3e0ee8b4cf37b3be23559a2dc23
[]
no_license
Temp1ar/ReliableHeap
495acd6064803a1e7b51a8f6d95fb6481262c98e
b3125d309b8c1e03721c0ffa1c6a9c0b81b723db
refs/heads/master
2021-01-01T19:24:30.423854
2012-05-22T12:40:01
2012-05-22T12:40:01
null
0
0
null
null
null
null
UTF-8
C++
false
false
7,071
cpp
#include <iostream> #include <cstdlib> #include <list> #include <cassert> #include <functional> template<class T, class Comparator = std::less<T>> class Heap { class Node { public: Node(T value, Node* parent = 0, Node* left = 0, Node* right = 0) : value_(value) , parent_(parent) , left_(left) , right_(right) {} Node(const Node& other) : value_(other.value_) , parent_(other.parent_) , left_(other.left_) , right_(other.right_) {} void swapWithChild(Node* other) { // Partying hard with pointers... assert(other != 0); Node* rootParent = parent_; Node* rootLeft = left_; Node* rootRight = right_; parent_ = other; if (right_ == other) { if (left_) { left_->parent_ = other; } left_ = other->left_; right_ = other->right_; other->left_ = rootLeft; other->right_ = this; } else if (left_ == other) { if (right_) { right_->parent_ = other; } left_ = other->left_; right_ = other->right_; other->left_ = this; other->right_ = rootRight; } else { return; } other->parent_ = rootParent; if (rootParent) { if (rootParent->left_ == this) { rootParent->left_ = other; } else { rootParent->right_ = other; } } if (left_) { left_->parent_ = this; } if (right_) { right_->parent_ = this; } } T value_; Node* left_; Node* right_; Node* parent_; }; public: Heap() : root_(0) , bottomRight_(0) , size_(0) {} Heap(const Heap& h) : root_(0) , bottomRight_(0) , size_(0) { if (h.size_ == 0) { return; } deepCopy(root_, h.root_, 0, h.bottomRight_); } Heap& operator=(const Heap& h) { if (this != &h) { Heap(h).swap(*this); } return *this; } ~Heap() { while(size_ != 0) { swapAndDeleteLast(); } } size_t size() { return size_; } void swap(Heap& h) { std::swap(root_, h.root_); std::swap(bottomRight_, h.bottomRight_); std::swap(size_, h.size_); } void push(T const& t) { Node* newNode = new Node(t); if (root_ == 0) { root_ = bottomRight_ = newNode; ++size_; } else { newNode->parent_ = bottomRight_; if (bottomRight_->left_ == 0) { bottomRight_->left_ = newNode; ++size_; try { // sieve can throw comparator exceptions sieve(bottomRight_); } catch(const std::exception&) { // no swaps yet, rolling back bottomRight_->left_ = 0; --size_; delete newNode; } } else { bottomRight_->right_ = newNode; ++size_; try { // sieve can throw comparator exceptions sieve(bottomRight_); bottomRight_ = findBottomRight(); } catch(const std::exception&) { // no swaps yet, rolling back bottomRight_->right_ = 0; --size_; delete newNode; } } } } const T& top() const { return root_->value_; } void pop() { Node* rootBackup = new Node(*root_); Node* lastParent; Node* last = getLast(); if(last->parent_) { lastParent = last->parent_; } swapAndDeleteLast(); if(root_ == 0) { return; } try { sieve(root_); delete rootBackup; } catch(const std::exception&) { //bottomRight_ = bottomRightBackup; last = root_; if (lastParent->left_ == 0) { lastParent->left_ = last; } else { lastParent->right_ = last; } last->left_ = 0; last->right_ = 0; last->parent_ = lastParent; root_ = rootBackup; root_->left_->parent_ = root_; root_->right_->parent_= root_; ++size_; } } private: Node* root_; Node* bottomRight_; size_t size_; void swapAndDeleteLast() { if (size_ == 1) { delete root_; root_ = 0; bottomRight_ = 0; --size_; return; } Node* last = getLast(); assert(last->right_ == 0); assert(last->left_ == 0); if (last->parent_->right_ == last) { last->parent_->right_ = 0; } else { last->parent_->left_ = 0; } if (root_->left_) root_->left_->parent_ = last; if (root_->right_) root_->right_->parent_ = last; last->left_ = root_->left_; last->right_ = root_->right_; last->parent_ = 0; delete root_; root_ = last; --size_; if (bottomRight_ == last) { bottomRight_ = getLast()->parent_; } } void sieve(Node* root) { Node* minimum = root; if (root->left_) { minimum = root->left_; } Comparator comp = Comparator(); if (root->right_) { if (comp(root->right_->value_, minimum->value_)) { minimum = root->right_; } } //if(minimum->value_ == 8 && root->value_ == 14) // throw std::exception(); if (comp(minimum->value_, root->value_)) { swapNodes(root, minimum); try { if (minimum->parent_) { sieve(minimum->parent_); } if (minimum->left_) { sieve(minimum->left_); } if (minimum->right_) { sieve(minimum->right_); } } catch(const std::exception& e) { swapNodes(minimum, root); throw e; } } } void swapNodes( Node* root, Node* minimum ) { root->swapWithChild(minimum); if (root == root_) { root_ = minimum; } if (root == bottomRight_) { bottomRight_ = minimum; } else if (minimum == bottomRight_) { bottomRight_ = root; } } Node* getLast() const { size_t value = size_; std::list<char> bits; while (value != 0) { bits.push_front(value % 2); value /= 2; } Node* answer = root_; std::list<char>::iterator it = ++bits.begin(); for (; it != bits.end(); ++it) { if (*it) { answer = answer->right_; } else { answer = answer->left_; } } return answer; } Node* findBottomRight() const { Node* root = bottomRight_; // if size_+1 is power of two if (((size_+1) & ((size_ + 1) - 1)) == 0) { root = root_; while (root->left_ != 0) { root = root->left_; } } else { while (root->parent_->right_ == root) { root = root->parent_; } root = root->parent_; root = root->right_; while (root->left_) { root = root->left_; } } return root; } void deepCopy(Node*& p, Node* h, Node* parent, Node* bottomRight) { p = new Node(h->value_, parent); if (bottomRight == h) { bottomRight_ = p; } ++size_; if (h->left_) { deepCopy(p->left_, h->left_, p, bottomRight); } if (h->right_) { deepCopy(p->right_, h->right_, p, bottomRight); } } }; int main () { //_CrtSetDbgFlag(_CRTDBG_LEAK_CHECK_DF | _CrtSetDbgFlag(0)); Heap<int> h; for (int i = 1; i < 15; ++i) { h.push(i); } h.pop(); //h.pop(); while (h.size() > 0) { std::cout << h.top() << " "; h.pop(); } Heap<int> h2(h); Heap<int> h3; h3 = h2; while (h3.size() > 0) { std::cout << h3.top() << " "; h3.pop(); } return 0; }
[ "alexey.korovin@spbau.se" ]
alexey.korovin@spbau.se
fad19bcb8bd37e9b9f31d5e6e14bec32b1e38662
a86542fa6fcabff33a9c052a18467acd3edc5fed
/server_CV.cpp
19bc01856aa98edcdb63fe077c890431788ea001
[]
no_license
srhodes9115/OpenCV
1075c9693e55ea3781de695108b0de2e88a54569
b44680e8f04bf377f9d09ff8e9b8936486b9b1a1
refs/heads/master
2021-01-19T08:45:18.759299
2017-04-08T23:17:15
2017-04-08T23:17:15
87,669,860
0
0
null
null
null
null
UTF-8
C++
false
false
5,026
cpp
/* THIS PROGRAM OPENS THE WEBCAM USING OPENCV, ALLOWS USER TO DRAG A LINE USING MOUSE */ #include <iostream> #include "opencv2/highgui/highgui.hpp" #include "opencv2/opencv.hpp" #include <stdio.h> #include <sys/socket.h> #include <arpa/inet.h> #include <sys/ioctl.h> #include <net/if.h> #include <unistd.h> #include <string.h> using namespace std; using namespace cv; char key; bool clicked=false; Mat img,imgGray; //ADDED Point P1(0,0); Point P2(0,0); //const char* winName="Original"; /*This function places the x and y coordinates of a mouse click into point variables */ void onMouse( int event, int x, int y, int f, void* ){ switch(event){ case CV_EVENT_LBUTTONDOWN : //one mouse click shows up as a dot clicked=true; P1.x=x; P1.y=y; P2.x=x; P2.y=y; break; case CV_EVENT_LBUTTONUP : //when the user releases the mouse, the second point is recorded P2.x=x; P2.y=y; clicked=false; break; case CV_EVENT_MOUSEMOVE : //as the mouse moves, the second point is recorded; making a "drag and drop" system if(clicked){ P2.x=x; P2.y=y; } break; default : break; } } int main(int argc,char** argv) { //NETWORKING STUFF: socket, bind, listen int localSocket; int remoteSocket; int port = 4097; struct sockaddr_in localAddr,remoteAddr; int addrLen = sizeof(struct sockaddr_in); if ( (argc > 1) && (strcmp(argv[1],"-h") == 0) ) { std::cerr << "usage: ./cv_video_srv [port] [capture device]\n" << "port : socket port (4097 default)\n" << "capture device : (0 default)\n" << std::endl; exit(1); } if (argc == 2) port = atoi(argv[1]); localSocket = socket(AF_INET , SOCK_STREAM , 0); if (localSocket == -1){ perror("socket() call failed!!"); } localAddr.sin_family = AF_INET; localAddr.sin_addr.s_addr = INADDR_ANY; localAddr.sin_port = htons( port ); if( bind(localSocket,(struct sockaddr *)&localAddr , sizeof(localAddr)) < 0) { perror("Can't bind() socket"); exit(1); } //Listening listen(localSocket , 1); std::cout << "Waiting for connections...\n" << "Server Port:" << port << std::endl; //accept connection from an incoming client remoteSocket = accept(localSocket, (struct sockaddr *)&remoteAddr, (socklen_t*)&addrLen); if (remoteSocket < 0) { perror("accept failed!"); exit(1); } std::cout << "Connection accepted" << std::endl; //OPENCV CODE int capDev = 0; if (argc == 3) capDev = atoi(argv[2]); img = Mat::zeros(480, 640, CV_8UC1); //make it continuous if (!img.isContinuous()) { img = img.clone(); } int imgSize = img.total() * img.elemSize(); int bytes = 0; int key; //make img continuos if ( ! img.isContinuous() ) { img = img.clone(); imgGray = img.clone(); } std::cout << "Image Size:" << imgSize << std::endl; //creates a window for the camera cvNamedWindow("Camera_Output", 1); //apparently this command captures any camera linked to system *MUST EXPERIMENT* CvCapture* capture = cvCaptureFromCAM(CV_CAP_ANY); //Create infinte loop for live streaming while(1){ IplImage* frame = cvQueryFrame(capture); //Create image frames from capture img =frame; //namedWindow(winName, WINDOW_NORMAL); //creates window to figure out where to place the line //imshow(winName, img); //int imgSize = img.total() * img.elemSize(); setMouseCallback("Camera_Output",onMouse,0); //Runs the mouse callback function, records the points for the line line(img, P1, P2, Scalar(0,255,255), 5, 8, 0); //Physically draws the line over the image cvShowImage("Camera_Output", frame); //Show image frames on created window key = cvWaitKey(10); //captures Keyboard stroke if (char(key) == 27){ break; //If you hit ESC key loop will break while in the original frame window } cvtColor(img, imgGray,CV_BGR2GRAY); //CV_BRG2GRAY if ((bytes = send(remoteSocket,imgGray.data,imgSize,0)) <0) { std::cerr << "bytes = " <<bytes <<std::endl; break; } } close(remoteSocket); cvReleaseCapture(&capture); //Stops the webcam cvDestroyWindow("Camera_Output"); //closes streaming window return 0; }
[ "shannon.rhodes@espn.com" ]
shannon.rhodes@espn.com
023dd853e4af0ef2a6ac8836148815b8e433bb5e
cf8ddfc720bf6451c4ef4fa01684327431db1919
/SDK/ARKSurvivalEvolved_DinoColorSet_Dunkleosteus_Ocean_classes.hpp
b51f51867b90259392cb5f99cba9f0eb7d543c3e
[ "MIT" ]
permissive
git-Charlie/ARK-SDK
75337684b11e7b9f668da1f15e8054052a3b600f
c38ca9925309516b2093ad8c3a70ed9489e1d573
refs/heads/master
2023-06-20T06:30:33.550123
2021-07-11T13:41:45
2021-07-11T13:41:45
null
0
0
null
null
null
null
UTF-8
C++
false
false
861
hpp
#pragma once // ARKSurvivalEvolved (329.9) SDK #ifdef _MSC_VER #pragma pack(push, 0x8) #endif #include "ARKSurvivalEvolved_DinoColorSet_Dunkleosteus_Ocean_structs.hpp" namespace sdk { //--------------------------------------------------------------------------- //Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass DinoColorSet_Dunkleosteus_Ocean.DinoColorSet_Dunkleosteus_Ocean_C // 0x0000 (0x0268 - 0x0268) class UDinoColorSet_Dunkleosteus_Ocean_C : public UPrimalColorSet { public: static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass DinoColorSet_Dunkleosteus_Ocean.DinoColorSet_Dunkleosteus_Ocean_C"); return ptr; } void ExecuteUbergraph_DinoColorSet_Dunkleosteus_Ocean(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "sergey.2bite@gmail.com" ]
sergey.2bite@gmail.com
bac8fb9afc8f143eee22974701acbf1aebf5b6e7
2aae847f4b9d9a9663ea74bc555bed68af42f4fc
/CLabel.h
ac8d9766313106abd8c182bc6d26bdb103579364
[]
no_license
ggaglianone/Console-Line-Editor
25e5f7085585f6fde0ff9b88111e81cbe858fd68
5c6e6f23df1f4b562b2bdf03f20883b02b9e82ff
refs/heads/master
2020-12-25T18:23:26.747945
2014-09-14T03:59:16
2014-09-14T03:59:16
null
0
0
null
null
null
null
UTF-8
C++
false
false
416
h
#ifndef _GG_CLABEL_H_ #define _GG_CLABEL_H_ #include "cfield.h" namespace cio{ class CLabel : public CField { void allocateAndCopy(const char*); int fieldLenght; public: CLabel(const char* str, int row, int col, int len = -1); CLabel(int row, int col, int len); CLabel(const CLabel& clb); ~CLabel(); void draw(int bordered = C_NO_FRAME); int edit(); bool editable() const; void set(const void* str); }; } #endif
[ "ggaglianone@myseneca.ca" ]
ggaglianone@myseneca.ca
28df7a92c68ad94d72e71c0e680a84928dd635ac
1854c32b4021107a96a2e2ca7ab9c8988647f4df
/jni/DiagnoseBase/source/SendFrame.cpp
a404e0a815dea703118cb388d2a4f0d41c395cc7
[]
no_license
dgtal/Diagnose
9d5eaffd6211193c0aab57afc4e3cbb3fe8d3683
4c05655c60716f973878fc6fd9c1f855a2e2a2d6
refs/heads/master
2021-01-13T08:57:53.939906
2015-12-16T03:23:08
2015-12-16T03:23:08
null
0
0
null
null
null
null
GB18030
C++
false
false
11,009
cpp
/****************************************************************************** Copyright (c) 2005, AUTOBOSS Inc. All rights reserved. 文件名称:SendFrame.cpp 文档标识:007汽车诊断平台详细设计说明书(诊断分册) 摘 要:汽车通信命令类。 历史记录: ---------------------------------------------------------------------------- 时 间 作者 版本号 操 作 内 容 ---------------------------------------------------------------------------- 2005.01.12 zhangsh 1.0 创建此类。 ******************************************************************************/ #include "SendFrame.h" #include "Database.h" #include "assert.h" //#include "EcuCommException.h" #define NOCMDINLIB -1 #define CMDLIBERROR -2 // 静态成员变量声明 int CSendFrame::m_iDefaultReceiveFrameNumber = 1; CSendFrame::CSendFrame(void) { } CSendFrame::~CSendFrame(void) { } /****************************************************************** 功 能: 赋值 参数说明: const CSendFrame& SendFrame 发送帧 返 回 值: 无 说 明: 无 ******************************************************************/ void CSendFrame::operator = (CSendFrame SendFrame) { m_SendFrame.clear(); if(SendFrame.m_SendFrame.empty()) { return; } vector<COneSendFrame>::iterator vIter; for(vIter = SendFrame.m_SendFrame.begin(); vIter != SendFrame.m_SendFrame.end(); vIter++) { m_SendFrame.push_back(*vIter); } } /****************************************************************** 功 能: 赋值 参数说明: const vector<CBinary>& binCmd 从命令库读出的命令, 返 回 值: 无 说 明: 参数中偶数位置为命令,奇数位置为接收帧数量 ******************************************************************/ void CSendFrame::operator = (vector<CBinary>& binCmd) { m_SendFrame.clear(); if (binCmd.empty()) { return; } COneSendFrame oneSendFrame; if (1 == binCmd.size()) // 只有一条命令且回复帧数缺省 { oneSendFrame.m_binSendCmd = binCmd[0]; oneSendFrame.m_iReceiveFrameNumber = m_iDefaultReceiveFrameNumber; m_SendFrame.push_back(oneSendFrame); } else { vector<CBinary>::size_type vIter; for (vIter = 0; vIter < binCmd.size(); vIter += 2) { oneSendFrame.m_binSendCmd = binCmd[vIter]; oneSendFrame.m_iReceiveFrameNumber = (unsigned char)(binCmd[vIter+1])[0]; m_SendFrame.push_back(oneSendFrame); } } } /****************************************************************** 功 能: 加入新发送帧数据 参数说明: const vector<CBinary>& binCmd 从命令库读出的命令 返 回 值: 无 说 明: 参数中偶数位置为命令,奇数位置为接收帧数量 ******************************************************************/ void CSendFrame::operator += (vector<CBinary>& binCmd) { if (binCmd.empty()) { return; } COneSendFrame oneSendFrame; if(1 == binCmd.size()) //只有一条命令且回复帧数缺省 { oneSendFrame.m_binSendCmd = binCmd[0]; oneSendFrame.m_iReceiveFrameNumber = m_iDefaultReceiveFrameNumber; m_SendFrame.push_back(oneSendFrame); } else { vector<CBinary>::size_type vIter; for (vIter = 0; vIter < binCmd.size(); vIter += 2) { oneSendFrame.m_binSendCmd = binCmd[vIter]; oneSendFrame.m_iReceiveFrameNumber = (unsigned char)(binCmd[vIter+1])[0]; m_SendFrame.push_back(oneSendFrame); } } } /****************************************************************** 功 能: 赋值 参数说明: const vector<CBinary>& binCmd 从命令库读出的命令, 返 回 值: 无 说 明: 参数中偶数位置为命令,奇数位置为接收帧数量 ******************************************************************/ void CSendFrame::operator = (const CBinary binData) { m_SendFrame.clear(); COneSendFrame oneSendFrame; oneSendFrame.m_binSendCmd = binData; oneSendFrame.m_iReceiveFrameNumber = m_iDefaultReceiveFrameNumber; m_SendFrame.push_back(oneSendFrame); } /****************************************************************** 功 能: 加入新发送帧数据 参数说明: const vector<CBinary>& binCmd 从命令库读出的命令 返 回 值: 无 说 明: 参数中偶数位置为命令,奇数位置为接收帧数量 ******************************************************************/ void CSendFrame::operator += (CBinary binData) { COneSendFrame oneSendFrame; oneSendFrame.m_binSendCmd = binData; oneSendFrame.m_iReceiveFrameNumber = m_iDefaultReceiveFrameNumber; m_SendFrame.push_back(oneSendFrame); } /****************************************************************** 功 能: 加入新发送帧数据 参数说明: const vector<CBinary>& binCmd 从命令库读出的命令 返 回 值: 无 说 明: 无 ******************************************************************/ void CSendFrame::operator += (CSendFrame& SendFrame) { if(SendFrame.m_SendFrame.empty()) { return; } vector<COneSendFrame>::iterator vIter; for(vIter = SendFrame.m_SendFrame.begin(); vIter != SendFrame.m_SendFrame.end(); vIter++) { m_SendFrame.push_back(*vIter); } } /****************************************************************** 功 能: 加入新发送帧数据 参数说明: COneSendFrame& oneSendFrame某一发送命令包 返 回 值: 无 说 明: 无 ******************************************************************/ void CSendFrame::operator += (COneSendFrame& oneSendFrame) { if(oneSendFrame.m_binSendCmd.GetSize() < 1) { return; } m_SendFrame.push_back(oneSendFrame); } /****************************************************************** 功 能:取得一个发送帧 参数说明:发送帧序号 返 回 值:一个发送帧 说 明:无 ******************************************************************/ CSendFrame::COneSendFrame CSendFrame::operator [] (short nIndex) { return m_SendFrame[nIndex]; } /****************************************************************** 功 能: 设置缺省接收帧帧数 参数说明: short iDefaultReceiveFrame 缺省接收帧帧数,缺省值为1 返 回 值: 前次设置缺省接收帧帧数 说 明: 无 ******************************************************************/ short CSendFrame::SetDefaultReceiveFrameNumber (short iDefaultReceiveFrame) { short preDefaultReceiveFrameNuber = m_iDefaultReceiveFrameNumber; m_iDefaultReceiveFrameNumber = iDefaultReceiveFrame; return preDefaultReceiveFrameNuber; } /****************************************************************** 功 能: 加入命令库ID对应的发送帧 参数说明: CBinary idCmd 命令库ID 返 回 值: 成功否 说 明: 无 ******************************************************************/ bool CSendFrame::AddFromCmdLib(CBinary idCmd) { vector<CBinary> vBinCmd; CDatabase dbCmd; if(!dbCmd.Open(CDatabase::DB_COMMAND)) return false; vBinCmd = dbCmd.SearchId(idCmd); dbCmd.Close(); if (vBinCmd.empty()) { return false; } COneSendFrame oneSendFrame; if(vBinCmd.size() == 1) //只有一条命令且回复帧数缺省 { oneSendFrame.m_binSendCmd = vBinCmd[0]; oneSendFrame.m_iReceiveFrameNumber = m_iDefaultReceiveFrameNumber; m_SendFrame.push_back(oneSendFrame); } else { // 如同一个ID中包含多个命令时不能省略: ECU回应的数据帧数 assert( vBinCmd.size()%2 == 0 ); vector<CBinary>::iterator vIter; for (vIter = vBinCmd.begin(); vIter != vBinCmd.end(); vIter += 2) { oneSendFrame.m_binSendCmd = *vIter; oneSendFrame.m_iReceiveFrameNumber = (unsigned char)(vIter+1)->GetAt(0); m_SendFrame.push_back(oneSendFrame); } } return true; } /****************************************************************** 功 能: 追加发送帧 参数说明: const CSendFrame& SendFrame 发送帧 返 回 值: 加入的数量 说 明: 无 ******************************************************************/ short CSendFrame::AddSendFrame(CSendFrame& SendFrame) { if(SendFrame.m_SendFrame.empty()) { return 0; } short nAddSize = 0; vector<COneSendFrame>::iterator vIter; for(vIter = SendFrame.m_SendFrame.begin(); vIter != SendFrame.m_SendFrame.end(); vIter++, nAddSize++) { m_SendFrame.push_back(*vIter); } return nAddSize; } /****************************************************************** 功 能: 清空发送帧 参数说明: 无 返 回 值: 无 说 明: 无 ******************************************************************/ void CSendFrame::Clear (void) { m_SendFrame.clear(); } /****************************************************************** 功 能: 取得发送帧数量 参数说明: 无 返 回 值: 发送帧数量 说 明: 无 ******************************************************************/ short CSendFrame::GetFrameNumber (void) { short iFrameNumber = m_SendFrame.size(); return iFrameNumber; } /****************************************************************** 功 能: 得到发送帧的返回帧数 参数说明: 无 返 回 值: 发送帧的返回帧数 说 明: 无 ******************************************************************/ short CSendFrame::GetAllReceiveFrameNumber(void) { short recvFrameNum = 0; vector<COneSendFrame>::iterator iSendFrame; for(iSendFrame = m_SendFrame.begin(); iSendFrame != m_SendFrame.end(); iSendFrame++) { recvFrameNum += iSendFrame->m_iReceiveFrameNumber; } return recvFrameNum; } /****************************************************************** 功 能: 得到发送帧中单帧的返回帧数 参数说明: int iOrder发送帧中单帧的顺序号 返 回 值: 发送帧中单帧的返回帧数 说 明: 无 ******************************************************************/ short CSendFrame::GetOneReceiveFrameNumber(int iOrder) { return m_SendFrame[iOrder].m_iReceiveFrameNumber; } /************************************************************************************** 功 能: 将发送帧命令内容按“[命令长度+内容+回复长度]...”的格式输出到指定的缓冲区 参数说明: 无 返 回 值: 缓冲区填充长度 说 明: 无 **************************************************************************************/ int CSendFrame::PutCmdDataToBuffer(unsigned char* dataBuf, int bufLength) { if (m_SendFrame.size() == 0) { return 0; } int dataLength = 0; vector<COneSendFrame>::iterator vIter; for (vIter = m_SendFrame.begin(); vIter < m_SendFrame.end(); vIter++) { CBinary cmdBin = vIter->m_binSendCmd; dataBuf[dataLength] = (unsigned char)cmdBin.GetSize(); dataLength++; char* pbuf = (char*)cmdBin.GetBuffer(); memcpy(dataBuf+dataLength, pbuf, cmdBin.GetSize()); dataLength += cmdBin.GetSize(); dataBuf[dataLength] = (unsigned char)vIter->m_iReceiveFrameNumber; dataLength++; } return dataLength; }
[ "1695981713@qq.com" ]
1695981713@qq.com
a50dbb6ccff1c95783588ad5379ac51ebb03bf6c
120a3dee111731efdd4d5c546d0922101452e41b
/v8/src/isolate.cc
e20cd1a6ef4169598d8f47a4b93097c8d15d4eb9
[ "BSD-3-Clause", "SunPro", "bzip2-1.0.6" ]
permissive
wenber/soure-think
f4ab32971fddf372da252afa25e28c7b768e0b08
667b9e4016690a8032217ceca513b21893722c82
refs/heads/master
2020-04-12T06:21:06.252671
2016-12-13T06:06:58
2016-12-13T06:06:58
58,983,053
0
0
null
null
null
null
UTF-8
C++
false
false
106,498
cc
// Copyright 2012 the V8 project authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "src/isolate.h" #include <stdlib.h> #include <fstream> // NOLINT(readability/streams) #include <sstream> #include "src/ast/ast.h" #include "src/ast/scopeinfo.h" #include "src/base/platform/platform.h" #include "src/base/sys-info.h" #include "src/base/utils/random-number-generator.h" #include "src/basic-block-profiler.h" #include "src/bootstrapper.h" #include "src/codegen.h" #include "src/compilation-cache.h" #include "src/compilation-statistics.h" #include "src/crankshaft/hydrogen.h" #include "src/debug/debug.h" #include "src/deoptimizer.h" #include "src/external-reference-table.h" #include "src/frames-inl.h" #include "src/ic/stub-cache.h" #include "src/interpreter/interpreter.h" #include "src/isolate-inl.h" #include "src/libsampler/sampler.h" #include "src/log.h" #include "src/messages.h" #include "src/profiler/cpu-profiler.h" #include "src/prototype.h" #include "src/regexp/regexp-stack.h" #include "src/runtime-profiler.h" #include "src/simulator.h" #include "src/snapshot/deserializer.h" #include "src/v8.h" #include "src/version.h" #include "src/vm-state-inl.h" #include "src/wasm/wasm-module.h" namespace v8 { namespace internal { base::Atomic32 ThreadId::highest_thread_id_ = 0; int ThreadId::AllocateThreadId() { int new_id = base::NoBarrier_AtomicIncrement(&highest_thread_id_, 1); return new_id; } int ThreadId::GetCurrentThreadId() { int thread_id = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_); if (thread_id == 0) { thread_id = AllocateThreadId(); base::Thread::SetThreadLocalInt(Isolate::thread_id_key_, thread_id); } return thread_id; } ThreadLocalTop::ThreadLocalTop() { InitializeInternal(); } void ThreadLocalTop::InitializeInternal() { c_entry_fp_ = 0; c_function_ = 0; handler_ = 0; #ifdef USE_SIMULATOR simulator_ = NULL; #endif js_entry_sp_ = NULL; external_callback_scope_ = NULL; current_vm_state_ = EXTERNAL; try_catch_handler_ = NULL; context_ = NULL; thread_id_ = ThreadId::Invalid(); external_caught_exception_ = false; failed_access_check_callback_ = NULL; save_context_ = NULL; promise_on_stack_ = NULL; // These members are re-initialized later after deserialization // is complete. pending_exception_ = NULL; rethrowing_message_ = false; pending_message_obj_ = NULL; scheduled_exception_ = NULL; } void ThreadLocalTop::Initialize() { InitializeInternal(); #ifdef USE_SIMULATOR simulator_ = Simulator::current(isolate_); #endif thread_id_ = ThreadId::Current(); } void ThreadLocalTop::Free() { // Match unmatched PopPromise calls. while (promise_on_stack_) isolate_->PopPromise(); } base::Thread::LocalStorageKey Isolate::isolate_key_; base::Thread::LocalStorageKey Isolate::thread_id_key_; base::Thread::LocalStorageKey Isolate::per_isolate_thread_data_key_; base::LazyMutex Isolate::thread_data_table_mutex_ = LAZY_MUTEX_INITIALIZER; Isolate::ThreadDataTable* Isolate::thread_data_table_ = NULL; base::Atomic32 Isolate::isolate_counter_ = 0; #if DEBUG base::Atomic32 Isolate::isolate_key_created_ = 0; #endif Isolate::PerIsolateThreadData* Isolate::FindOrAllocatePerThreadDataForThisThread() { ThreadId thread_id = ThreadId::Current(); PerIsolateThreadData* per_thread = NULL; { base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer()); per_thread = thread_data_table_->Lookup(this, thread_id); if (per_thread == NULL) { per_thread = new PerIsolateThreadData(this, thread_id); thread_data_table_->Insert(per_thread); } DCHECK(thread_data_table_->Lookup(this, thread_id) == per_thread); } return per_thread; } void Isolate::DiscardPerThreadDataForThisThread() { int thread_id_int = base::Thread::GetThreadLocalInt(Isolate::thread_id_key_); if (thread_id_int) { ThreadId thread_id = ThreadId(thread_id_int); DCHECK(!thread_manager_->mutex_owner_.Equals(thread_id)); base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer()); PerIsolateThreadData* per_thread = thread_data_table_->Lookup(this, thread_id); if (per_thread) { DCHECK(!per_thread->thread_state_); thread_data_table_->Remove(per_thread); } } } Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThisThread() { ThreadId thread_id = ThreadId::Current(); return FindPerThreadDataForThread(thread_id); } Isolate::PerIsolateThreadData* Isolate::FindPerThreadDataForThread( ThreadId thread_id) { PerIsolateThreadData* per_thread = NULL; { base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer()); per_thread = thread_data_table_->Lookup(this, thread_id); } return per_thread; } void Isolate::InitializeOncePerProcess() { base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer()); CHECK(thread_data_table_ == NULL); isolate_key_ = base::Thread::CreateThreadLocalKey(); #if DEBUG base::NoBarrier_Store(&isolate_key_created_, 1); #endif thread_id_key_ = base::Thread::CreateThreadLocalKey(); per_isolate_thread_data_key_ = base::Thread::CreateThreadLocalKey(); thread_data_table_ = new Isolate::ThreadDataTable(); } Address Isolate::get_address_from_id(Isolate::AddressId id) { return isolate_addresses_[id]; } char* Isolate::Iterate(ObjectVisitor* v, char* thread_storage) { ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(thread_storage); Iterate(v, thread); return thread_storage + sizeof(ThreadLocalTop); } void Isolate::IterateThread(ThreadVisitor* v, char* t) { ThreadLocalTop* thread = reinterpret_cast<ThreadLocalTop*>(t); v->VisitThread(this, thread); } void Isolate::Iterate(ObjectVisitor* v, ThreadLocalTop* thread) { // Visit the roots from the top for a given thread. v->VisitPointer(&thread->pending_exception_); v->VisitPointer(&(thread->pending_message_obj_)); v->VisitPointer(bit_cast<Object**>(&(thread->context_))); v->VisitPointer(&thread->scheduled_exception_); for (v8::TryCatch* block = thread->try_catch_handler(); block != NULL; block = block->next_) { v->VisitPointer(bit_cast<Object**>(&(block->exception_))); v->VisitPointer(bit_cast<Object**>(&(block->message_obj_))); } // Iterate over pointers on native execution stack. for (StackFrameIterator it(this, thread); !it.done(); it.Advance()) { it.frame()->Iterate(v); } } void Isolate::Iterate(ObjectVisitor* v) { ThreadLocalTop* current_t = thread_local_top(); Iterate(v, current_t); } void Isolate::IterateDeferredHandles(ObjectVisitor* visitor) { for (DeferredHandles* deferred = deferred_handles_head_; deferred != NULL; deferred = deferred->next_) { deferred->Iterate(visitor); } } #ifdef DEBUG bool Isolate::IsDeferredHandle(Object** handle) { // Each DeferredHandles instance keeps the handles to one job in the // concurrent recompilation queue, containing a list of blocks. Each block // contains kHandleBlockSize handles except for the first block, which may // not be fully filled. // We iterate through all the blocks to see whether the argument handle // belongs to one of the blocks. If so, it is deferred. for (DeferredHandles* deferred = deferred_handles_head_; deferred != NULL; deferred = deferred->next_) { List<Object**>* blocks = &deferred->blocks_; for (int i = 0; i < blocks->length(); i++) { Object** block_limit = (i == 0) ? deferred->first_block_limit_ : blocks->at(i) + kHandleBlockSize; if (blocks->at(i) <= handle && handle < block_limit) return true; } } return false; } #endif // DEBUG void Isolate::RegisterTryCatchHandler(v8::TryCatch* that) { thread_local_top()->set_try_catch_handler(that); } void Isolate::UnregisterTryCatchHandler(v8::TryCatch* that) { DCHECK(thread_local_top()->try_catch_handler() == that); thread_local_top()->set_try_catch_handler(that->next_); } Handle<String> Isolate::StackTraceString() { if (stack_trace_nesting_level_ == 0) { stack_trace_nesting_level_++; HeapStringAllocator allocator; StringStream::ClearMentionedObjectCache(this); StringStream accumulator(&allocator); incomplete_message_ = &accumulator; PrintStack(&accumulator); Handle<String> stack_trace = accumulator.ToString(this); incomplete_message_ = NULL; stack_trace_nesting_level_ = 0; return stack_trace; } else if (stack_trace_nesting_level_ == 1) { stack_trace_nesting_level_++; base::OS::PrintError( "\n\nAttempt to print stack while printing stack (double fault)\n"); base::OS::PrintError( "If you are lucky you may find a partial stack dump on stdout.\n\n"); incomplete_message_->OutputToStdOut(); return factory()->empty_string(); } else { base::OS::Abort(); // Unreachable return factory()->empty_string(); } } void Isolate::PushStackTraceAndDie(unsigned int magic, void* ptr1, void* ptr2, unsigned int magic2) { const int kMaxStackTraceSize = 32 * KB; Handle<String> trace = StackTraceString(); uint8_t buffer[kMaxStackTraceSize]; int length = Min(kMaxStackTraceSize - 1, trace->length()); String::WriteToFlat(*trace, buffer, 0, length); buffer[length] = '\0'; // TODO(dcarney): convert buffer to utf8? base::OS::PrintError("Stacktrace (%x-%x) %p %p: %s\n", magic, magic2, ptr1, ptr2, reinterpret_cast<char*>(buffer)); base::OS::Abort(); } static Handle<FixedArray> MaybeGrow(Isolate* isolate, Handle<FixedArray> elements, int cur_position, int new_size) { if (new_size > elements->length()) { int new_capacity = JSObject::NewElementsCapacity(elements->length()); Handle<FixedArray> new_elements = isolate->factory()->NewFixedArrayWithHoles(new_capacity); for (int i = 0; i < cur_position; i++) { new_elements->set(i, elements->get(i)); } elements = new_elements; } DCHECK(new_size <= elements->length()); return elements; } class StackTraceHelper { public: StackTraceHelper(Isolate* isolate, Handle<Object> caller) : isolate_(isolate), caller_(caller) { // If the caller parameter is a function we skip frames until we're // under it before starting to collect. seen_caller_ = !caller->IsJSFunction(); encountered_strict_function_ = false; sloppy_frames_ = 0; } // The stack trace API should not expose receivers and function // objects on frames deeper than the top-most one with a strict mode // function. The number of sloppy frames is stored as first element in // the result array. void CountSloppyFrames(JSFunction* fun) { if (!encountered_strict_function_) { if (is_strict(fun->shared()->language_mode())) { encountered_strict_function_ = true; } else { sloppy_frames_++; } } } // Determines whether the given stack frame should be displayed in a stack // trace. bool IsVisibleInStackTrace(JSFunction* fun) { return IsAfterCaller(fun) && IsNotInNativeScript(fun) && IsInSameSecurityContext(fun); } int sloppy_frames() const { return sloppy_frames_; } private: // The caller is the error constructor that asked // for the stack trace to be collected. The first time a construct // call to this function is encountered it is skipped. The seen_caller // in/out parameter is used to remember if the caller has been seen // yet. bool IsAfterCaller(JSFunction* fun) { if ((fun == *caller_) && !(seen_caller_)) { seen_caller_ = true; return false; } // Skip all frames until we've seen the caller. if (!seen_caller_) return false; return true; } bool IsNotInNativeScript(JSFunction* fun) { // Functions defined in native scripts are not visible unless directly // exposed, in which case the native flag is set. // The --builtins-in-stack-traces command line flag allows including // internal call sites in the stack trace for debugging purposes. if (!FLAG_builtins_in_stack_traces && fun->shared()->IsBuiltin()) { return fun->shared()->native(); } return true; } bool IsInSameSecurityContext(JSFunction* fun) { return isolate_->context()->HasSameSecurityTokenAs(fun->context()); } Isolate* isolate_; Handle<Object> caller_; bool seen_caller_; int sloppy_frames_; bool encountered_strict_function_; }; Handle<Object> Isolate::CaptureSimpleStackTrace(Handle<JSReceiver> error_object, Handle<Object> caller) { // Get stack trace limit. Handle<JSObject> error = error_function(); Handle<String> stackTraceLimit = factory()->InternalizeUtf8String("stackTraceLimit"); DCHECK(!stackTraceLimit.is_null()); Handle<Object> stack_trace_limit = JSReceiver::GetDataProperty(error, stackTraceLimit); if (!stack_trace_limit->IsNumber()) return factory()->undefined_value(); int limit = FastD2IChecked(stack_trace_limit->Number()); limit = Max(limit, 0); // Ensure that limit is not negative. int initial_size = Min(limit, 10); Handle<FixedArray> elements = factory()->NewFixedArrayWithHoles(initial_size * 4 + 1); StackTraceHelper helper(this, caller); // First element is reserved to store the number of sloppy frames. int cursor = 1; int frames_seen = 0; for (StackFrameIterator iter(this); !iter.done() && frames_seen < limit; iter.Advance()) { StackFrame* frame = iter.frame(); switch (frame->type()) { case StackFrame::JAVA_SCRIPT: case StackFrame::OPTIMIZED: case StackFrame::INTERPRETED: case StackFrame::BUILTIN: { JavaScriptFrame* js_frame = JavaScriptFrame::cast(frame); // Set initial size to the maximum inlining level + 1 for the outermost // function. List<FrameSummary> frames(FLAG_max_inlining_levels + 1); js_frame->Summarize(&frames); for (int i = frames.length() - 1; i >= 0; i--) { Handle<JSFunction> fun = frames[i].function(); // Filter out internal frames that we do not want to show. if (!helper.IsVisibleInStackTrace(*fun)) continue; helper.CountSloppyFrames(*fun); Handle<Object> recv = frames[i].receiver(); Handle<AbstractCode> abstract_code = frames[i].abstract_code(); if (frame->type() == StackFrame::BUILTIN) { // Help CallSite::IsConstructor correctly detect hand-written // construct stubs. Code* code = Code::cast(*abstract_code); if (code->is_construct_stub()) { recv = handle(heap()->call_site_constructor_symbol(), this); } } Handle<Smi> offset(Smi::FromInt(frames[i].code_offset()), this); elements = MaybeGrow(this, elements, cursor, cursor + 4); elements->set(cursor++, *recv); elements->set(cursor++, *fun); elements->set(cursor++, *abstract_code); elements->set(cursor++, *offset); frames_seen++; } } break; case StackFrame::BUILTIN_EXIT: { BuiltinExitFrame* exit_frame = BuiltinExitFrame::cast(frame); Handle<JSFunction> fun = handle(exit_frame->function(), this); // Filter out internal frames that we do not want to show. if (!helper.IsVisibleInStackTrace(*fun)) continue; helper.CountSloppyFrames(*fun); Handle<Code> code = handle(exit_frame->LookupCode(), this); int offset = static_cast<int>(exit_frame->pc() - code->instruction_start()); // In order to help CallSite::IsConstructor detect builtin constructors, // we reuse the receiver field to pass along a special symbol. Handle<Object> recv; if (exit_frame->IsConstructor()) { recv = handle(heap()->call_site_constructor_symbol(), this); } else { recv = handle(exit_frame->receiver(), this); } elements = MaybeGrow(this, elements, cursor, cursor + 4); elements->set(cursor++, *recv); elements->set(cursor++, *fun); elements->set(cursor++, *code); elements->set(cursor++, Smi::FromInt(offset)); frames_seen++; } break; case StackFrame::WASM: { WasmFrame* wasm_frame = WasmFrame::cast(frame); Code* code = wasm_frame->unchecked_code(); Handle<AbstractCode> abstract_code = Handle<AbstractCode>(AbstractCode::cast(code)); int offset = static_cast<int>(wasm_frame->pc() - code->instruction_start()); elements = MaybeGrow(this, elements, cursor, cursor + 4); elements->set(cursor++, wasm_frame->wasm_obj()); elements->set(cursor++, Smi::FromInt(wasm_frame->function_index())); elements->set(cursor++, *abstract_code); elements->set(cursor++, Smi::FromInt(offset)); frames_seen++; } break; default: break; } } elements->set(0, Smi::FromInt(helper.sloppy_frames())); elements->Shrink(cursor); Handle<JSArray> result = factory()->NewJSArrayWithElements(elements); result->set_length(Smi::FromInt(cursor)); // TODO(yangguo): Queue this structured stack trace for preprocessing on GC. return result; } MaybeHandle<JSReceiver> Isolate::CaptureAndSetDetailedStackTrace( Handle<JSReceiver> error_object) { if (capture_stack_trace_for_uncaught_exceptions_) { // Capture stack trace for a detailed exception message. Handle<Name> key = factory()->detailed_stack_trace_symbol(); Handle<JSArray> stack_trace = CaptureCurrentStackTrace( stack_trace_for_uncaught_exceptions_frame_limit_, stack_trace_for_uncaught_exceptions_options_); RETURN_ON_EXCEPTION( this, JSReceiver::SetProperty(error_object, key, stack_trace, STRICT), JSReceiver); } return error_object; } MaybeHandle<JSReceiver> Isolate::CaptureAndSetSimpleStackTrace( Handle<JSReceiver> error_object, Handle<Object> caller) { // Capture stack trace for simple stack trace string formatting. Handle<Name> key = factory()->stack_trace_symbol(); Handle<Object> stack_trace = CaptureSimpleStackTrace(error_object, caller); RETURN_ON_EXCEPTION( this, JSReceiver::SetProperty(error_object, key, stack_trace, STRICT), JSReceiver); return error_object; } Handle<JSArray> Isolate::GetDetailedStackTrace(Handle<JSObject> error_object) { Handle<Name> key_detailed = factory()->detailed_stack_trace_symbol(); Handle<Object> stack_trace = JSReceiver::GetDataProperty(error_object, key_detailed); if (stack_trace->IsJSArray()) return Handle<JSArray>::cast(stack_trace); return Handle<JSArray>(); } class CaptureStackTraceHelper { public: CaptureStackTraceHelper(Isolate* isolate, StackTrace::StackTraceOptions options) : isolate_(isolate) { if (options & StackTrace::kColumnOffset) { column_key_ = factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("column")); } if (options & StackTrace::kLineNumber) { line_key_ = factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("lineNumber")); } if (options & StackTrace::kScriptId) { script_id_key_ = factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptId")); } if (options & StackTrace::kScriptName) { script_name_key_ = factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("scriptName")); } if (options & StackTrace::kScriptNameOrSourceURL) { script_name_or_source_url_key_ = factory()->InternalizeOneByteString( STATIC_CHAR_VECTOR("scriptNameOrSourceURL")); } if (options & StackTrace::kFunctionName) { function_key_ = factory()->InternalizeOneByteString( STATIC_CHAR_VECTOR("functionName")); } if (options & StackTrace::kIsEval) { eval_key_ = factory()->InternalizeOneByteString(STATIC_CHAR_VECTOR("isEval")); } if (options & StackTrace::kIsConstructor) { constructor_key_ = factory()->InternalizeOneByteString( STATIC_CHAR_VECTOR("isConstructor")); } } Handle<JSObject> NewStackFrameObject(FrameSummary& summ) { int position = summ.abstract_code()->SourcePosition(summ.code_offset()); return NewStackFrameObject(summ.function(), position, summ.is_constructor()); } Handle<JSObject> NewStackFrameObject(Handle<JSFunction> fun, int position, bool is_constructor) { Handle<JSObject> stack_frame = factory()->NewJSObject(isolate_->object_function()); Handle<Script> script(Script::cast(fun->shared()->script())); if (!line_key_.is_null()) { Script::PositionInfo info; bool valid_pos = script->GetPositionInfo(position, &info, Script::WITH_OFFSET); if (!column_key_.is_null() && valid_pos) { JSObject::AddProperty(stack_frame, column_key_, handle(Smi::FromInt(info.column + 1), isolate_), NONE); } JSObject::AddProperty(stack_frame, line_key_, handle(Smi::FromInt(info.line + 1), isolate_), NONE); } if (!script_id_key_.is_null()) { JSObject::AddProperty(stack_frame, script_id_key_, handle(Smi::FromInt(script->id()), isolate_), NONE); } if (!script_name_key_.is_null()) { JSObject::AddProperty(stack_frame, script_name_key_, handle(script->name(), isolate_), NONE); } if (!script_name_or_source_url_key_.is_null()) { Handle<Object> result = Script::GetNameOrSourceURL(script); JSObject::AddProperty(stack_frame, script_name_or_source_url_key_, result, NONE); } if (!eval_key_.is_null()) { Handle<Object> is_eval = factory()->ToBoolean( script->compilation_type() == Script::COMPILATION_TYPE_EVAL); JSObject::AddProperty(stack_frame, eval_key_, is_eval, NONE); } if (!function_key_.is_null()) { Handle<Object> fun_name = JSFunction::GetDebugName(fun); JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE); } if (!constructor_key_.is_null()) { Handle<Object> is_constructor_obj = factory()->ToBoolean(is_constructor); JSObject::AddProperty(stack_frame, constructor_key_, is_constructor_obj, NONE); } return stack_frame; } Handle<JSObject> NewStackFrameObject(BuiltinExitFrame* frame) { Handle<JSObject> stack_frame = factory()->NewJSObject(isolate_->object_function()); Handle<JSFunction> fun = handle(frame->function(), isolate_); if (!function_key_.is_null()) { Handle<Object> fun_name = JSFunction::GetDebugName(fun); JSObject::AddProperty(stack_frame, function_key_, fun_name, NONE); } // We don't have a script and hence cannot set line and col positions. DCHECK(!fun->shared()->script()->IsScript()); return stack_frame; } Handle<JSObject> NewStackFrameObject(WasmFrame* frame) { Handle<JSObject> stack_frame = factory()->NewJSObject(isolate_->object_function()); if (!function_key_.is_null()) { Handle<String> name = wasm::GetWasmFunctionName( isolate_, handle(frame->wasm_obj(), isolate_), frame->function_index()); JSObject::AddProperty(stack_frame, function_key_, name, NONE); } // Encode the function index as line number. if (!line_key_.is_null()) { JSObject::AddProperty( stack_frame, line_key_, isolate_->factory()->NewNumberFromInt(frame->function_index()), NONE); } // Encode the byte offset as column. if (!column_key_.is_null()) { Code* code = frame->LookupCode(); int offset = static_cast<int>(frame->pc() - code->instruction_start()); int position = AbstractCode::cast(code)->SourcePosition(offset); // Make position 1-based. if (position >= 0) ++position; JSObject::AddProperty(stack_frame, column_key_, isolate_->factory()->NewNumberFromInt(position), NONE); } if (!script_id_key_.is_null()) { int script_id = frame->script()->id(); JSObject::AddProperty(stack_frame, script_id_key_, handle(Smi::FromInt(script_id), isolate_), NONE); } return stack_frame; } private: inline Factory* factory() { return isolate_->factory(); } Isolate* isolate_; Handle<String> column_key_; Handle<String> line_key_; Handle<String> script_id_key_; Handle<String> script_name_key_; Handle<String> script_name_or_source_url_key_; Handle<String> function_key_; Handle<String> eval_key_; Handle<String> constructor_key_; }; int PositionFromStackTrace(Handle<FixedArray> elements, int index) { DisallowHeapAllocation no_gc; Object* maybe_code = elements->get(index + 2); if (maybe_code->IsSmi()) { return Smi::cast(maybe_code)->value(); } else { AbstractCode* abstract_code = AbstractCode::cast(maybe_code); int code_offset = Smi::cast(elements->get(index + 3))->value(); return abstract_code->SourcePosition(code_offset); } } Handle<JSArray> Isolate::CaptureCurrentStackTrace( int frame_limit, StackTrace::StackTraceOptions options) { CaptureStackTraceHelper helper(this, options); // Ensure no negative values. int limit = Max(frame_limit, 0); Handle<JSArray> stack_trace = factory()->NewJSArray(frame_limit); Handle<FixedArray> stack_trace_elems( FixedArray::cast(stack_trace->elements()), this); int frames_seen = 0; for (StackTraceFrameIterator it(this); !it.done() && (frames_seen < limit); it.Advance()) { StandardFrame* frame = it.frame(); if (frame->is_java_script()) { // Set initial size to the maximum inlining level + 1 for the outermost // function. List<FrameSummary> frames(FLAG_max_inlining_levels + 1); JavaScriptFrame::cast(frame)->Summarize(&frames); for (int i = frames.length() - 1; i >= 0 && frames_seen < limit; i--) { Handle<JSFunction> fun = frames[i].function(); // Filter frames from other security contexts. if (!(options & StackTrace::kExposeFramesAcrossSecurityOrigins) && !this->context()->HasSameSecurityTokenAs(fun->context())) continue; Handle<JSObject> new_frame_obj = helper.NewStackFrameObject(frames[i]); stack_trace_elems->set(frames_seen, *new_frame_obj); frames_seen++; } } else { DCHECK(frame->is_wasm()); WasmFrame* wasm_frame = WasmFrame::cast(frame); Handle<JSObject> new_frame_obj = helper.NewStackFrameObject(wasm_frame); stack_trace_elems->set(frames_seen, *new_frame_obj); frames_seen++; } } stack_trace->set_length(Smi::FromInt(frames_seen)); return stack_trace; } void Isolate::PrintStack(FILE* out, PrintStackMode mode) { if (stack_trace_nesting_level_ == 0) { stack_trace_nesting_level_++; StringStream::ClearMentionedObjectCache(this); HeapStringAllocator allocator; StringStream accumulator(&allocator); incomplete_message_ = &accumulator; PrintStack(&accumulator, mode); accumulator.OutputToFile(out); InitializeLoggingAndCounters(); accumulator.Log(this); incomplete_message_ = NULL; stack_trace_nesting_level_ = 0; } else if (stack_trace_nesting_level_ == 1) { stack_trace_nesting_level_++; base::OS::PrintError( "\n\nAttempt to print stack while printing stack (double fault)\n"); base::OS::PrintError( "If you are lucky you may find a partial stack dump on stdout.\n\n"); incomplete_message_->OutputToFile(out); } } static void PrintFrames(Isolate* isolate, StringStream* accumulator, StackFrame::PrintMode mode) { StackFrameIterator it(isolate); for (int i = 0; !it.done(); it.Advance()) { it.frame()->Print(accumulator, mode, i++); } } void Isolate::PrintStack(StringStream* accumulator, PrintStackMode mode) { // The MentionedObjectCache is not GC-proof at the moment. DisallowHeapAllocation no_gc; HandleScope scope(this); DCHECK(accumulator->IsMentionedObjectCacheClear(this)); // Avoid printing anything if there are no frames. if (c_entry_fp(thread_local_top()) == 0) return; accumulator->Add( "\n==== JS stack trace =========================================\n\n"); PrintFrames(this, accumulator, StackFrame::OVERVIEW); if (mode == kPrintStackVerbose) { accumulator->Add( "\n==== Details ================================================\n\n"); PrintFrames(this, accumulator, StackFrame::DETAILS); accumulator->PrintMentionedObjectCache(this); } accumulator->Add("=====================\n\n"); } void Isolate::SetFailedAccessCheckCallback( v8::FailedAccessCheckCallback callback) { thread_local_top()->failed_access_check_callback_ = callback; } void Isolate::ReportFailedAccessCheck(Handle<JSObject> receiver) { if (!thread_local_top()->failed_access_check_callback_) { return ScheduleThrow(*factory()->NewTypeError(MessageTemplate::kNoAccess)); } DCHECK(receiver->IsAccessCheckNeeded()); DCHECK(context()); // Get the data object from access check info. HandleScope scope(this); Handle<Object> data; { DisallowHeapAllocation no_gc; AccessCheckInfo* access_check_info = AccessCheckInfo::Get(this, receiver); if (!access_check_info) { AllowHeapAllocation doesnt_matter_anymore; return ScheduleThrow( *factory()->NewTypeError(MessageTemplate::kNoAccess)); } data = handle(access_check_info->data(), this); } // Leaving JavaScript. VMState<EXTERNAL> state(this); thread_local_top()->failed_access_check_callback_( v8::Utils::ToLocal(receiver), v8::ACCESS_HAS, v8::Utils::ToLocal(data)); } bool Isolate::MayAccess(Handle<Context> accessing_context, Handle<JSObject> receiver) { DCHECK(receiver->IsJSGlobalProxy() || receiver->IsAccessCheckNeeded()); // Check for compatibility between the security tokens in the // current lexical context and the accessed object. // During bootstrapping, callback functions are not enabled yet. if (bootstrapper()->IsActive()) return true; { DisallowHeapAllocation no_gc; if (receiver->IsJSGlobalProxy()) { Object* receiver_context = JSGlobalProxy::cast(*receiver)->native_context(); if (!receiver_context->IsContext()) return false; // Get the native context of current top context. // avoid using Isolate::native_context() because it uses Handle. Context* native_context = accessing_context->global_object()->native_context(); if (receiver_context == native_context) return true; if (Context::cast(receiver_context)->security_token() == native_context->security_token()) return true; } } HandleScope scope(this); Handle<Object> data; v8::AccessCheckCallback callback = nullptr; { DisallowHeapAllocation no_gc; AccessCheckInfo* access_check_info = AccessCheckInfo::Get(this, receiver); if (!access_check_info) return false; Object* fun_obj = access_check_info->callback(); callback = v8::ToCData<v8::AccessCheckCallback>(fun_obj); data = handle(access_check_info->data(), this); } LOG(this, ApiSecurityCheck()); { // Leaving JavaScript. VMState<EXTERNAL> state(this); return callback(v8::Utils::ToLocal(accessing_context), v8::Utils::ToLocal(receiver), v8::Utils::ToLocal(data)); } } Object* Isolate::StackOverflow() { HandleScope scope(this); // At this point we cannot create an Error object using its javascript // constructor. Instead, we copy the pre-constructed boilerplate and // attach the stack trace as a hidden property. Handle<Object> exception; if (bootstrapper()->IsActive()) { // There is no boilerplate to use during bootstrapping. exception = factory()->NewStringFromAsciiChecked( MessageTemplate::TemplateString(MessageTemplate::kStackOverflow)); } else { Handle<JSObject> boilerplate = stack_overflow_boilerplate(); Handle<JSObject> copy = factory()->CopyJSObject(boilerplate); CaptureAndSetSimpleStackTrace(copy, factory()->undefined_value()); exception = copy; } Throw(*exception, nullptr); #ifdef VERIFY_HEAP if (FLAG_verify_heap && FLAG_stress_compaction) { heap()->CollectAllGarbage(Heap::kNoGCFlags, "trigger compaction"); } #endif // VERIFY_HEAP return heap()->exception(); } Object* Isolate::TerminateExecution() { return Throw(heap_.termination_exception(), nullptr); } void Isolate::CancelTerminateExecution() { if (try_catch_handler()) { try_catch_handler()->has_terminated_ = false; } if (has_pending_exception() && pending_exception() == heap_.termination_exception()) { thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); } if (has_scheduled_exception() && scheduled_exception() == heap_.termination_exception()) { thread_local_top()->external_caught_exception_ = false; clear_scheduled_exception(); } } void Isolate::RequestInterrupt(InterruptCallback callback, void* data) { ExecutionAccess access(this); api_interrupts_queue_.push(InterruptEntry(callback, data)); stack_guard()->RequestApiInterrupt(); } void Isolate::InvokeApiInterruptCallbacks() { // Note: callback below should be called outside of execution access lock. while (true) { InterruptEntry entry; { ExecutionAccess access(this); if (api_interrupts_queue_.empty()) return; entry = api_interrupts_queue_.front(); api_interrupts_queue_.pop(); } VMState<EXTERNAL> state(this); HandleScope handle_scope(this); entry.first(reinterpret_cast<v8::Isolate*>(this), entry.second); } } void ReportBootstrappingException(Handle<Object> exception, MessageLocation* location) { base::OS::PrintError("Exception thrown during bootstrapping\n"); if (location == NULL || location->script().is_null()) return; // We are bootstrapping and caught an error where the location is set // and we have a script for the location. // In this case we could have an extension (or an internal error // somewhere) and we print out the line number at which the error occured // to the console for easier debugging. int line_number = location->script()->GetLineNumber(location->start_pos()) + 1; if (exception->IsString() && location->script()->name()->IsString()) { base::OS::PrintError( "Extension or internal compilation error: %s in %s at line %d.\n", String::cast(*exception)->ToCString().get(), String::cast(location->script()->name())->ToCString().get(), line_number); } else if (location->script()->name()->IsString()) { base::OS::PrintError( "Extension or internal compilation error in %s at line %d.\n", String::cast(location->script()->name())->ToCString().get(), line_number); } else if (exception->IsString()) { base::OS::PrintError("Extension or internal compilation error: %s.\n", String::cast(*exception)->ToCString().get()); } else { base::OS::PrintError("Extension or internal compilation error.\n"); } #ifdef OBJECT_PRINT // Since comments and empty lines have been stripped from the source of // builtins, print the actual source here so that line numbers match. if (location->script()->source()->IsString()) { Handle<String> src(String::cast(location->script()->source())); PrintF("Failing script:"); int len = src->length(); if (len == 0) { PrintF(" <not available>\n"); } else { PrintF("\n"); int line_number = 1; PrintF("%5d: ", line_number); for (int i = 0; i < len; i++) { uint16_t character = src->Get(i); PrintF("%c", character); if (character == '\n' && i < len - 2) { PrintF("%5d: ", ++line_number); } } PrintF("\n"); } } #endif } Object* Isolate::Throw(Object* exception, MessageLocation* location) { DCHECK(!has_pending_exception()); HandleScope scope(this); Handle<Object> exception_handle(exception, this); // Determine whether a message needs to be created for the given exception // depending on the following criteria: // 1) External v8::TryCatch missing: Always create a message because any // JavaScript handler for a finally-block might re-throw to top-level. // 2) External v8::TryCatch exists: Only create a message if the handler // captures messages or is verbose (which reports despite the catch). // 3) ReThrow from v8::TryCatch: The message from a previous throw still // exists and we preserve it instead of creating a new message. bool requires_message = try_catch_handler() == nullptr || try_catch_handler()->is_verbose_ || try_catch_handler()->capture_message_; bool rethrowing_message = thread_local_top()->rethrowing_message_; thread_local_top()->rethrowing_message_ = false; // Notify debugger of exception. if (is_catchable_by_javascript(exception)) { debug()->OnThrow(exception_handle); } // Generate the message if required. if (requires_message && !rethrowing_message) { MessageLocation computed_location; // If no location was specified we try to use a computed one instead. if (location == NULL && ComputeLocation(&computed_location)) { location = &computed_location; } if (bootstrapper()->IsActive()) { // It's not safe to try to make message objects or collect stack traces // while the bootstrapper is active since the infrastructure may not have // been properly initialized. ReportBootstrappingException(exception_handle, location); } else { Handle<Object> message_obj = CreateMessage(exception_handle, location); thread_local_top()->pending_message_obj_ = *message_obj; // For any exception not caught by JavaScript, even when an external // handler is present: // If the abort-on-uncaught-exception flag is specified, and if the // embedder didn't specify a custom uncaught exception callback, // or if the custom callback determined that V8 should abort, then // abort. if (FLAG_abort_on_uncaught_exception && PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT && (!abort_on_uncaught_exception_callback_ || abort_on_uncaught_exception_callback_( reinterpret_cast<v8::Isolate*>(this)))) { // Prevent endless recursion. FLAG_abort_on_uncaught_exception = false; // This flag is intended for use by JavaScript developers, so // print a user-friendly stack trace (not an internal one). PrintF(stderr, "%s\n\nFROM\n", MessageHandler::GetLocalizedMessage(this, message_obj).get()); PrintCurrentStackTrace(stderr); base::OS::Abort(); } } } // Set the exception being thrown. set_pending_exception(*exception_handle); return heap()->exception(); } Object* Isolate::ReThrow(Object* exception) { DCHECK(!has_pending_exception()); // Set the exception being re-thrown. set_pending_exception(exception); return heap()->exception(); } Object* Isolate::UnwindAndFindHandler() { Object* exception = pending_exception(); Code* code = nullptr; Context* context = nullptr; intptr_t offset = 0; Address handler_sp = nullptr; Address handler_fp = nullptr; // Special handling of termination exceptions, uncatchable by JavaScript code, // we unwind the handlers until the top ENTRY handler is found. bool catchable_by_js = is_catchable_by_javascript(exception); // Compute handler and stack unwinding information by performing a full walk // over the stack and dispatching according to the frame type. for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) { StackFrame* frame = iter.frame(); // For JSEntryStub frames we always have a handler. if (frame->is_entry() || frame->is_entry_construct()) { StackHandler* handler = frame->top_handler(); // Restore the next handler. thread_local_top()->handler_ = handler->next()->address(); // Gather information from the handler. code = frame->LookupCode(); handler_sp = handler->address() + StackHandlerConstants::kSize; offset = Smi::cast(code->handler_table()->get(0))->value(); break; } // For optimized frames we perform a lookup in the handler table. if (frame->is_optimized() && catchable_by_js) { OptimizedFrame* js_frame = static_cast<OptimizedFrame*>(frame); int stack_slots = 0; // Will contain stack slot count of frame. offset = js_frame->LookupExceptionHandlerInTable(&stack_slots, nullptr); if (offset >= 0) { // Compute the stack pointer from the frame pointer. This ensures that // argument slots on the stack are dropped as returning would. Address return_sp = frame->fp() + StandardFrameConstants::kFixedFrameSizeAboveFp - stack_slots * kPointerSize; // Gather information from the frame. code = frame->LookupCode(); if (code->marked_for_deoptimization()) { // If the target code is lazy deoptimized, we jump to the original // return address, but we make a note that we are throwing, so that // the deoptimizer can do the right thing. offset = static_cast<int>(frame->pc() - code->entry()); set_deoptimizer_lazy_throw(true); } handler_sp = return_sp; handler_fp = frame->fp(); break; } } // For interpreted frame we perform a range lookup in the handler table. if (frame->is_interpreted() && catchable_by_js) { InterpretedFrame* js_frame = static_cast<InterpretedFrame*>(frame); int context_reg = 0; // Will contain register index holding context. offset = js_frame->LookupExceptionHandlerInTable(&context_reg, nullptr); if (offset >= 0) { // Patch the bytecode offset in the interpreted frame to reflect the // position of the exception handler. The special builtin below will // take care of continuing to dispatch at that position. Also restore // the correct context for the handler from the interpreter register. context = Context::cast(js_frame->ReadInterpreterRegister(context_reg)); js_frame->PatchBytecodeOffset(static_cast<int>(offset)); offset = 0; // Gather information from the frame. code = *builtins()->InterpreterEnterBytecodeDispatch(); handler_sp = frame->sp(); handler_fp = frame->fp(); break; } } // For JavaScript frames we perform a range lookup in the handler table. if (frame->is_java_script() && catchable_by_js) { JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame); int stack_depth = 0; // Will contain operand stack depth of handler. offset = js_frame->LookupExceptionHandlerInTable(&stack_depth, nullptr); if (offset >= 0) { // Compute the stack pointer from the frame pointer. This ensures that // operand stack slots are dropped for nested statements. Also restore // correct context for the handler which is pushed within the try-block. Address return_sp = frame->fp() - StandardFrameConstants::kFixedFrameSizeFromFp - stack_depth * kPointerSize; STATIC_ASSERT(TryBlockConstant::kElementCount == 1); context = Context::cast(Memory::Object_at(return_sp - kPointerSize)); // Gather information from the frame. code = frame->LookupCode(); handler_sp = return_sp; handler_fp = frame->fp(); break; } } RemoveMaterializedObjectsOnUnwind(frame); } // Handler must exist. CHECK(code != nullptr); // Store information to be consumed by the CEntryStub. thread_local_top()->pending_handler_context_ = context; thread_local_top()->pending_handler_code_ = code; thread_local_top()->pending_handler_offset_ = offset; thread_local_top()->pending_handler_fp_ = handler_fp; thread_local_top()->pending_handler_sp_ = handler_sp; // Return and clear pending exception. clear_pending_exception(); return exception; } Isolate::CatchType Isolate::PredictExceptionCatcher() { Address external_handler = thread_local_top()->try_catch_handler_address(); Address entry_handler = Isolate::handler(thread_local_top()); if (IsExternalHandlerOnTop(nullptr)) return CAUGHT_BY_EXTERNAL; // Search for an exception handler by performing a full walk over the stack. for (StackFrameIterator iter(this); !iter.done(); iter.Advance()) { StackFrame* frame = iter.frame(); // For JSEntryStub frames we update the JS_ENTRY handler. if (frame->is_entry() || frame->is_entry_construct()) { entry_handler = frame->top_handler()->next()->address(); } // For JavaScript frames we perform a lookup in the handler table. if (frame->is_java_script()) { JavaScriptFrame* js_frame = static_cast<JavaScriptFrame*>(frame); HandlerTable::CatchPrediction prediction; if (js_frame->LookupExceptionHandlerInTable(nullptr, &prediction) > 0) { // We are conservative with our prediction: try-finally is considered // to always rethrow, to meet the expectation of the debugger. if (prediction == HandlerTable::CAUGHT) return CAUGHT_BY_JAVASCRIPT; } } // The exception has been externally caught if and only if there is an // external handler which is on top of the top-most JS_ENTRY handler. if (external_handler != nullptr && !try_catch_handler()->is_verbose_) { if (entry_handler == nullptr || entry_handler > external_handler) { return CAUGHT_BY_EXTERNAL; } } } // Handler not found. return NOT_CAUGHT; } void Isolate::RemoveMaterializedObjectsOnUnwind(StackFrame* frame) { if (frame->is_optimized()) { bool removed = materialized_object_store_->Remove(frame->fp()); USE(removed); // If there were any materialized objects, the code should be // marked for deopt. DCHECK(!removed || frame->LookupCode()->marked_for_deoptimization()); } } Object* Isolate::ThrowIllegalOperation() { if (FLAG_stack_trace_on_illegal) PrintStack(stdout); return Throw(heap()->illegal_access_string()); } void Isolate::ScheduleThrow(Object* exception) { // When scheduling a throw we first throw the exception to get the // error reporting if it is uncaught before rescheduling it. Throw(exception); PropagatePendingExceptionToExternalTryCatch(); if (has_pending_exception()) { thread_local_top()->scheduled_exception_ = pending_exception(); thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); } } void Isolate::RestorePendingMessageFromTryCatch(v8::TryCatch* handler) { DCHECK(handler == try_catch_handler()); DCHECK(handler->HasCaught()); DCHECK(handler->rethrow_); DCHECK(handler->capture_message_); Object* message = reinterpret_cast<Object*>(handler->message_obj_); DCHECK(message->IsJSMessageObject() || message->IsTheHole(this)); thread_local_top()->pending_message_obj_ = message; } void Isolate::CancelScheduledExceptionFromTryCatch(v8::TryCatch* handler) { DCHECK(has_scheduled_exception()); if (scheduled_exception() == handler->exception_) { DCHECK(scheduled_exception() != heap()->termination_exception()); clear_scheduled_exception(); } } Object* Isolate::PromoteScheduledException() { Object* thrown = scheduled_exception(); clear_scheduled_exception(); // Re-throw the exception to avoid getting repeated error reporting. return ReThrow(thrown); } void Isolate::PrintCurrentStackTrace(FILE* out) { StackTraceFrameIterator it(this); while (!it.done()) { HandleScope scope(this); // Find code position if recorded in relocation info. StandardFrame* frame = it.frame(); AbstractCode* abstract_code; int code_offset; if (frame->is_interpreted()) { InterpretedFrame* iframe = reinterpret_cast<InterpretedFrame*>(frame); abstract_code = AbstractCode::cast(iframe->GetBytecodeArray()); code_offset = iframe->GetBytecodeOffset(); } else { DCHECK(frame->is_java_script() || frame->is_wasm()); Code* code = frame->LookupCode(); abstract_code = AbstractCode::cast(code); code_offset = static_cast<int>(frame->pc() - code->instruction_start()); } int pos = abstract_code->SourcePosition(code_offset); JavaScriptFrame* js_frame = JavaScriptFrame::cast(frame); Handle<Object> pos_obj(Smi::FromInt(pos), this); // Fetch function and receiver. Handle<JSFunction> fun(js_frame->function()); Handle<Object> recv(js_frame->receiver(), this); // Advance to the next JavaScript frame and determine if the // current frame is the top-level frame. it.Advance(); Handle<Object> is_top_level = factory()->ToBoolean(it.done()); // Generate and print stack trace line. Handle<String> line = Execution::GetStackTraceLine(recv, fun, pos_obj, is_top_level); if (line->length() > 0) { line->PrintOn(out); PrintF(out, "\n"); } } } bool Isolate::ComputeLocation(MessageLocation* target) { StackTraceFrameIterator it(this); if (it.done()) return false; StandardFrame* frame = it.frame(); // TODO(clemensh): handle wasm frames if (!frame->is_java_script()) return false; JSFunction* fun = JavaScriptFrame::cast(frame)->function(); Object* script = fun->shared()->script(); if (!script->IsScript() || (Script::cast(script)->source()->IsUndefined(this))) { return false; } Handle<Script> casted_script(Script::cast(script)); // Compute the location from the function and the relocation info of the // baseline code. For optimized code this will use the deoptimization // information to get canonical location information. List<FrameSummary> frames(FLAG_max_inlining_levels + 1); JavaScriptFrame::cast(frame)->Summarize(&frames); FrameSummary& summary = frames.last(); int pos = summary.abstract_code()->SourcePosition(summary.code_offset()); *target = MessageLocation(casted_script, pos, pos + 1, handle(fun)); return true; } bool Isolate::ComputeLocationFromException(MessageLocation* target, Handle<Object> exception) { if (!exception->IsJSObject()) return false; Handle<Name> start_pos_symbol = factory()->error_start_pos_symbol(); Handle<Object> start_pos = JSReceiver::GetDataProperty( Handle<JSObject>::cast(exception), start_pos_symbol); if (!start_pos->IsSmi()) return false; int start_pos_value = Handle<Smi>::cast(start_pos)->value(); Handle<Name> end_pos_symbol = factory()->error_end_pos_symbol(); Handle<Object> end_pos = JSReceiver::GetDataProperty( Handle<JSObject>::cast(exception), end_pos_symbol); if (!end_pos->IsSmi()) return false; int end_pos_value = Handle<Smi>::cast(end_pos)->value(); Handle<Name> script_symbol = factory()->error_script_symbol(); Handle<Object> script = JSReceiver::GetDataProperty( Handle<JSObject>::cast(exception), script_symbol); if (!script->IsScript()) return false; Handle<Script> cast_script(Script::cast(*script)); *target = MessageLocation(cast_script, start_pos_value, end_pos_value); return true; } bool Isolate::ComputeLocationFromStackTrace(MessageLocation* target, Handle<Object> exception) { if (!exception->IsJSObject()) return false; Handle<Name> key = factory()->stack_trace_symbol(); Handle<Object> property = JSReceiver::GetDataProperty(Handle<JSObject>::cast(exception), key); if (!property->IsJSArray()) return false; Handle<JSArray> simple_stack_trace = Handle<JSArray>::cast(property); Handle<FixedArray> elements(FixedArray::cast(simple_stack_trace->elements())); int elements_limit = Smi::cast(simple_stack_trace->length())->value(); for (int i = 1; i < elements_limit; i += 4) { Handle<Object> fun_obj = handle(elements->get(i + 1), this); if (fun_obj->IsSmi()) { // TODO(clemensh): handle wasm frames return false; } Handle<JSFunction> fun = Handle<JSFunction>::cast(fun_obj); if (!fun->shared()->IsSubjectToDebugging()) continue; Object* script = fun->shared()->script(); if (script->IsScript() && !(Script::cast(script)->source()->IsUndefined(this))) { int pos = PositionFromStackTrace(elements, i); Handle<Script> casted_script(Script::cast(script)); *target = MessageLocation(casted_script, pos, pos + 1); return true; } } return false; } Handle<JSMessageObject> Isolate::CreateMessage(Handle<Object> exception, MessageLocation* location) { Handle<JSArray> stack_trace_object; if (capture_stack_trace_for_uncaught_exceptions_) { if (exception->IsJSError()) { // We fetch the stack trace that corresponds to this error object. // If the lookup fails, the exception is probably not a valid Error // object. In that case, we fall through and capture the stack trace // at this throw site. stack_trace_object = GetDetailedStackTrace(Handle<JSObject>::cast(exception)); } if (stack_trace_object.is_null()) { // Not an error object, we capture stack and location at throw site. stack_trace_object = CaptureCurrentStackTrace( stack_trace_for_uncaught_exceptions_frame_limit_, stack_trace_for_uncaught_exceptions_options_); } } MessageLocation computed_location; if (location == NULL && (ComputeLocationFromException(&computed_location, exception) || ComputeLocationFromStackTrace(&computed_location, exception) || ComputeLocation(&computed_location))) { location = &computed_location; } return MessageHandler::MakeMessageObject( this, MessageTemplate::kUncaughtException, location, exception, stack_trace_object); } bool Isolate::IsJavaScriptHandlerOnTop(Object* exception) { DCHECK_NE(heap()->the_hole_value(), exception); // For uncatchable exceptions, the JavaScript handler cannot be on top. if (!is_catchable_by_javascript(exception)) return false; // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist. Address entry_handler = Isolate::handler(thread_local_top()); if (entry_handler == nullptr) return false; // Get the address of the external handler so we can compare the address to // determine which one is closer to the top of the stack. Address external_handler = thread_local_top()->try_catch_handler_address(); if (external_handler == nullptr) return true; // The exception has been externally caught if and only if there is an // external handler which is on top of the top-most JS_ENTRY handler. // // Note, that finally clauses would re-throw an exception unless it's aborted // by jumps in control flow (like return, break, etc.) and we'll have another // chance to set proper v8::TryCatch later. return (entry_handler < external_handler); } bool Isolate::IsExternalHandlerOnTop(Object* exception) { DCHECK_NE(heap()->the_hole_value(), exception); // Get the address of the external handler so we can compare the address to // determine which one is closer to the top of the stack. Address external_handler = thread_local_top()->try_catch_handler_address(); if (external_handler == nullptr) return false; // For uncatchable exceptions, the external handler is always on top. if (!is_catchable_by_javascript(exception)) return true; // Get the top-most JS_ENTRY handler, cannot be on top if it doesn't exist. Address entry_handler = Isolate::handler(thread_local_top()); if (entry_handler == nullptr) return true; // The exception has been externally caught if and only if there is an // external handler which is on top of the top-most JS_ENTRY handler. // // Note, that finally clauses would re-throw an exception unless it's aborted // by jumps in control flow (like return, break, etc.) and we'll have another // chance to set proper v8::TryCatch later. return (entry_handler > external_handler); } void Isolate::ReportPendingMessages() { Object* exception = pending_exception(); // Try to propagate the exception to an external v8::TryCatch handler. If // propagation was unsuccessful, then we will get another chance at reporting // the pending message if the exception is re-thrown. bool has_been_propagated = PropagatePendingExceptionToExternalTryCatch(); if (!has_been_propagated) return; // Clear the pending message object early to avoid endless recursion. Object* message_obj = thread_local_top_.pending_message_obj_; clear_pending_message(); // For uncatchable exceptions we do nothing. If needed, the exception and the // message have already been propagated to v8::TryCatch. if (!is_catchable_by_javascript(exception)) return; // Determine whether the message needs to be reported to all message handlers // depending on whether and external v8::TryCatch or an internal JavaScript // handler is on top. bool should_report_exception; if (IsExternalHandlerOnTop(exception)) { // Only report the exception if the external handler is verbose. should_report_exception = try_catch_handler()->is_verbose_; } else { // Report the exception if it isn't caught by JavaScript code. should_report_exception = !IsJavaScriptHandlerOnTop(exception); } // Actually report the pending message to all message handlers. if (!message_obj->IsTheHole(this) && should_report_exception) { HandleScope scope(this); Handle<JSMessageObject> message(JSMessageObject::cast(message_obj)); Handle<JSValue> script_wrapper(JSValue::cast(message->script())); Handle<Script> script(Script::cast(script_wrapper->value())); int start_pos = message->start_position(); int end_pos = message->end_position(); MessageLocation location(script, start_pos, end_pos); MessageHandler::ReportMessage(this, &location, message); } } MessageLocation Isolate::GetMessageLocation() { DCHECK(has_pending_exception()); if (thread_local_top_.pending_exception_ != heap()->termination_exception() && !thread_local_top_.pending_message_obj_->IsTheHole(this)) { Handle<JSMessageObject> message_obj( JSMessageObject::cast(thread_local_top_.pending_message_obj_)); Handle<JSValue> script_wrapper(JSValue::cast(message_obj->script())); Handle<Script> script(Script::cast(script_wrapper->value())); int start_pos = message_obj->start_position(); int end_pos = message_obj->end_position(); return MessageLocation(script, start_pos, end_pos); } return MessageLocation(); } bool Isolate::OptionalRescheduleException(bool is_bottom_call) { DCHECK(has_pending_exception()); PropagatePendingExceptionToExternalTryCatch(); bool is_termination_exception = pending_exception() == heap_.termination_exception(); // Do not reschedule the exception if this is the bottom call. bool clear_exception = is_bottom_call; if (is_termination_exception) { if (is_bottom_call) { thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); return false; } } else if (thread_local_top()->external_caught_exception_) { // If the exception is externally caught, clear it if there are no // JavaScript frames on the way to the C++ frame that has the // external handler. DCHECK(thread_local_top()->try_catch_handler_address() != NULL); Address external_handler_address = thread_local_top()->try_catch_handler_address(); JavaScriptFrameIterator it(this); if (it.done() || (it.frame()->sp() > external_handler_address)) { clear_exception = true; } } // Clear the exception if needed. if (clear_exception) { thread_local_top()->external_caught_exception_ = false; clear_pending_exception(); return false; } // Reschedule the exception. thread_local_top()->scheduled_exception_ = pending_exception(); clear_pending_exception(); return true; } void Isolate::PushPromise(Handle<JSObject> promise, Handle<JSFunction> function) { ThreadLocalTop* tltop = thread_local_top(); PromiseOnStack* prev = tltop->promise_on_stack_; Handle<JSObject> global_promise = Handle<JSObject>::cast(global_handles()->Create(*promise)); Handle<JSFunction> global_function = Handle<JSFunction>::cast(global_handles()->Create(*function)); tltop->promise_on_stack_ = new PromiseOnStack(global_function, global_promise, prev); } void Isolate::PopPromise() { ThreadLocalTop* tltop = thread_local_top(); if (tltop->promise_on_stack_ == NULL) return; PromiseOnStack* prev = tltop->promise_on_stack_->prev(); Handle<Object> global_function = tltop->promise_on_stack_->function(); Handle<Object> global_promise = tltop->promise_on_stack_->promise(); delete tltop->promise_on_stack_; tltop->promise_on_stack_ = prev; global_handles()->Destroy(global_function.location()); global_handles()->Destroy(global_promise.location()); } Handle<Object> Isolate::GetPromiseOnStackOnThrow() { Handle<Object> undefined = factory()->undefined_value(); ThreadLocalTop* tltop = thread_local_top(); if (tltop->promise_on_stack_ == NULL) return undefined; Handle<JSFunction> promise_function = tltop->promise_on_stack_->function(); // Find the top-most try-catch or try-finally handler. if (PredictExceptionCatcher() != CAUGHT_BY_JAVASCRIPT) return undefined; for (JavaScriptFrameIterator it(this); !it.done(); it.Advance()) { JavaScriptFrame* frame = it.frame(); if (frame->LookupExceptionHandlerInTable(nullptr, nullptr) > 0) { // Throwing inside a Promise only leads to a reject if not caught by an // inner try-catch or try-finally. if (frame->function() == *promise_function) { return tltop->promise_on_stack_->promise(); } return undefined; } } return undefined; } void Isolate::SetCaptureStackTraceForUncaughtExceptions( bool capture, int frame_limit, StackTrace::StackTraceOptions options) { capture_stack_trace_for_uncaught_exceptions_ = capture; stack_trace_for_uncaught_exceptions_frame_limit_ = frame_limit; stack_trace_for_uncaught_exceptions_options_ = options; } void Isolate::SetAbortOnUncaughtExceptionCallback( v8::Isolate::AbortOnUncaughtExceptionCallback callback) { abort_on_uncaught_exception_callback_ = callback; } Handle<Context> Isolate::native_context() { return handle(context()->native_context()); } Handle<Context> Isolate::GetCallingNativeContext() { JavaScriptFrameIterator it(this); if (debug_->in_debug_scope()) { while (!it.done()) { JavaScriptFrame* frame = it.frame(); Context* context = Context::cast(frame->context()); if (context->native_context() == *debug_->debug_context()) { it.Advance(); } else { break; } } } if (it.done()) return Handle<Context>::null(); JavaScriptFrame* frame = it.frame(); Context* context = Context::cast(frame->context()); return Handle<Context>(context->native_context()); } char* Isolate::ArchiveThread(char* to) { MemCopy(to, reinterpret_cast<char*>(thread_local_top()), sizeof(ThreadLocalTop)); InitializeThreadLocal(); clear_pending_exception(); clear_pending_message(); clear_scheduled_exception(); return to + sizeof(ThreadLocalTop); } char* Isolate::RestoreThread(char* from) { MemCopy(reinterpret_cast<char*>(thread_local_top()), from, sizeof(ThreadLocalTop)); // This might be just paranoia, but it seems to be needed in case a // thread_local_top_ is restored on a separate OS thread. #ifdef USE_SIMULATOR thread_local_top()->simulator_ = Simulator::current(this); #endif DCHECK(context() == NULL || context()->IsContext()); return from + sizeof(ThreadLocalTop); } Isolate::ThreadDataTable::ThreadDataTable() : list_(NULL) { } Isolate::ThreadDataTable::~ThreadDataTable() { // TODO(svenpanne) The assertion below would fire if an embedder does not // cleanly dispose all Isolates before disposing v8, so we are conservative // and leave it out for now. // DCHECK_NULL(list_); } Isolate::PerIsolateThreadData::~PerIsolateThreadData() { #if defined(USE_SIMULATOR) delete simulator_; #endif } Isolate::PerIsolateThreadData* Isolate::ThreadDataTable::Lookup(Isolate* isolate, ThreadId thread_id) { for (PerIsolateThreadData* data = list_; data != NULL; data = data->next_) { if (data->Matches(isolate, thread_id)) return data; } return NULL; } void Isolate::ThreadDataTable::Insert(Isolate::PerIsolateThreadData* data) { if (list_ != NULL) list_->prev_ = data; data->next_ = list_; list_ = data; } void Isolate::ThreadDataTable::Remove(PerIsolateThreadData* data) { if (list_ == data) list_ = data->next_; if (data->next_ != NULL) data->next_->prev_ = data->prev_; if (data->prev_ != NULL) data->prev_->next_ = data->next_; delete data; } void Isolate::ThreadDataTable::RemoveAllThreads(Isolate* isolate) { PerIsolateThreadData* data = list_; while (data != NULL) { PerIsolateThreadData* next = data->next_; if (data->isolate() == isolate) Remove(data); data = next; } } #ifdef DEBUG #define TRACE_ISOLATE(tag) \ do { \ if (FLAG_trace_isolates) { \ PrintF("Isolate %p (id %d)" #tag "\n", \ reinterpret_cast<void*>(this), id()); \ } \ } while (false) #else #define TRACE_ISOLATE(tag) #endif Isolate::Isolate(bool enable_serializer) : embedder_data_(), entry_stack_(NULL), stack_trace_nesting_level_(0), incomplete_message_(NULL), bootstrapper_(NULL), runtime_profiler_(NULL), compilation_cache_(NULL), counters_(NULL), logger_(NULL), stats_table_(NULL), load_stub_cache_(NULL), store_stub_cache_(NULL), code_aging_helper_(NULL), deoptimizer_data_(NULL), deoptimizer_lazy_throw_(false), materialized_object_store_(NULL), capture_stack_trace_for_uncaught_exceptions_(false), stack_trace_for_uncaught_exceptions_frame_limit_(0), stack_trace_for_uncaught_exceptions_options_(StackTrace::kOverview), keyed_lookup_cache_(NULL), context_slot_cache_(NULL), descriptor_lookup_cache_(NULL), handle_scope_implementer_(NULL), unicode_cache_(NULL), runtime_zone_(&allocator_), interface_descriptor_zone_(&allocator_), inner_pointer_to_code_cache_(NULL), global_handles_(NULL), eternal_handles_(NULL), thread_manager_(NULL), has_installed_extensions_(false), regexp_stack_(NULL), date_cache_(NULL), call_descriptor_data_(NULL), // TODO(bmeurer) Initialized lazily because it depends on flags; can // be fixed once the default isolate cleanup is done. random_number_generator_(NULL), rail_mode_(PERFORMANCE_ANIMATION), serializer_enabled_(enable_serializer), has_fatal_error_(false), initialized_from_snapshot_(false), is_tail_call_elimination_enabled_(true), cpu_profiler_(NULL), heap_profiler_(NULL), code_event_dispatcher_(new CodeEventDispatcher()), function_entry_hook_(NULL), deferred_handles_head_(NULL), optimizing_compile_dispatcher_(NULL), stress_deopt_count_(0), virtual_handler_register_(NULL), virtual_slot_register_(NULL), next_optimization_id_(0), js_calls_from_api_counter_(0), #if TRACE_MAPS next_unique_sfi_id_(0), #endif is_running_microtasks_(false), use_counter_callback_(NULL), basic_block_profiler_(NULL), cancelable_task_manager_(new CancelableTaskManager()), abort_on_uncaught_exception_callback_(NULL) { { base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer()); CHECK(thread_data_table_); } id_ = base::NoBarrier_AtomicIncrement(&isolate_counter_, 1); TRACE_ISOLATE(constructor); memset(isolate_addresses_, 0, sizeof(isolate_addresses_[0]) * (kIsolateAddressCount + 1)); heap_.isolate_ = this; stack_guard_.isolate_ = this; // ThreadManager is initialized early to support locking an isolate // before it is entered. thread_manager_ = new ThreadManager(); thread_manager_->isolate_ = this; #ifdef DEBUG // heap_histograms_ initializes itself. memset(&js_spill_information_, 0, sizeof(js_spill_information_)); #endif handle_scope_data_.Initialize(); #define ISOLATE_INIT_EXECUTE(type, name, initial_value) \ name##_ = (initial_value); ISOLATE_INIT_LIST(ISOLATE_INIT_EXECUTE) #undef ISOLATE_INIT_EXECUTE #define ISOLATE_INIT_ARRAY_EXECUTE(type, name, length) \ memset(name##_, 0, sizeof(type) * length); ISOLATE_INIT_ARRAY_LIST(ISOLATE_INIT_ARRAY_EXECUTE) #undef ISOLATE_INIT_ARRAY_EXECUTE InitializeLoggingAndCounters(); debug_ = new Debug(this); init_memcopy_functions(this); } void Isolate::TearDown() { TRACE_ISOLATE(tear_down); // Temporarily set this isolate as current so that various parts of // the isolate can access it in their destructors without having a // direct pointer. We don't use Enter/Exit here to avoid // initializing the thread data. PerIsolateThreadData* saved_data = CurrentPerIsolateThreadData(); DCHECK(base::NoBarrier_Load(&isolate_key_created_) == 1); Isolate* saved_isolate = reinterpret_cast<Isolate*>(base::Thread::GetThreadLocal(isolate_key_)); SetIsolateThreadLocals(this, NULL); Deinit(); { base::LockGuard<base::Mutex> lock_guard(thread_data_table_mutex_.Pointer()); thread_data_table_->RemoveAllThreads(this); } delete this; // Restore the previous current isolate. SetIsolateThreadLocals(saved_isolate, saved_data); } void Isolate::GlobalTearDown() { delete thread_data_table_; thread_data_table_ = NULL; } void Isolate::ClearSerializerData() { delete external_reference_table_; external_reference_table_ = NULL; delete external_reference_map_; external_reference_map_ = NULL; } void Isolate::Deinit() { TRACE_ISOLATE(deinit); debug()->Unload(); FreeThreadResources(); if (concurrent_recompilation_enabled()) { optimizing_compile_dispatcher_->Stop(); delete optimizing_compile_dispatcher_; optimizing_compile_dispatcher_ = NULL; } if (heap_.mark_compact_collector()->sweeping_in_progress()) { heap_.mark_compact_collector()->EnsureSweepingCompleted(); } DumpAndResetCompilationStats(); if (FLAG_print_deopt_stress) { PrintF(stdout, "=== Stress deopt counter: %u\n", stress_deopt_count_); } if (cpu_profiler_) { cpu_profiler_->DeleteAllProfiles(); } // We must stop the logger before we tear down other components. sampler::Sampler* sampler = logger_->sampler(); if (sampler && sampler->IsActive()) sampler->Stop(); delete deoptimizer_data_; deoptimizer_data_ = NULL; builtins_.TearDown(); bootstrapper_->TearDown(); if (runtime_profiler_ != NULL) { delete runtime_profiler_; runtime_profiler_ = NULL; } delete basic_block_profiler_; basic_block_profiler_ = NULL; delete heap_profiler_; heap_profiler_ = NULL; heap_.TearDown(); logger_->TearDown(); delete interpreter_; interpreter_ = NULL; cancelable_task_manager()->CancelAndWait(); delete cpu_profiler_; cpu_profiler_ = NULL; code_event_dispatcher_.reset(); delete root_index_map_; root_index_map_ = NULL; ClearSerializerData(); } void Isolate::SetIsolateThreadLocals(Isolate* isolate, PerIsolateThreadData* data) { base::Thread::SetThreadLocal(isolate_key_, isolate); base::Thread::SetThreadLocal(per_isolate_thread_data_key_, data); } Isolate::~Isolate() { TRACE_ISOLATE(destructor); // Has to be called while counters_ are still alive runtime_zone_.DeleteKeptSegment(); // The entry stack must be empty when we get here. DCHECK(entry_stack_ == NULL || entry_stack_->previous_item == NULL); delete entry_stack_; entry_stack_ = NULL; delete unicode_cache_; unicode_cache_ = NULL; delete date_cache_; date_cache_ = NULL; delete[] call_descriptor_data_; call_descriptor_data_ = NULL; delete regexp_stack_; regexp_stack_ = NULL; delete descriptor_lookup_cache_; descriptor_lookup_cache_ = NULL; delete context_slot_cache_; context_slot_cache_ = NULL; delete keyed_lookup_cache_; keyed_lookup_cache_ = NULL; delete load_stub_cache_; load_stub_cache_ = NULL; delete store_stub_cache_; store_stub_cache_ = NULL; delete code_aging_helper_; code_aging_helper_ = NULL; delete stats_table_; stats_table_ = NULL; delete materialized_object_store_; materialized_object_store_ = NULL; delete logger_; logger_ = NULL; delete counters_; counters_ = NULL; delete handle_scope_implementer_; handle_scope_implementer_ = NULL; delete code_tracer(); set_code_tracer(NULL); delete compilation_cache_; compilation_cache_ = NULL; delete bootstrapper_; bootstrapper_ = NULL; delete inner_pointer_to_code_cache_; inner_pointer_to_code_cache_ = NULL; delete thread_manager_; thread_manager_ = NULL; delete global_handles_; global_handles_ = NULL; delete eternal_handles_; eternal_handles_ = NULL; delete string_stream_debug_object_cache_; string_stream_debug_object_cache_ = NULL; delete random_number_generator_; random_number_generator_ = NULL; delete debug_; debug_ = NULL; delete cancelable_task_manager_; cancelable_task_manager_ = nullptr; #if USE_SIMULATOR Simulator::TearDown(simulator_i_cache_, simulator_redirection_); simulator_i_cache_ = nullptr; simulator_redirection_ = nullptr; #endif } void Isolate::InitializeThreadLocal() { thread_local_top_.isolate_ = this; thread_local_top_.Initialize(); } bool Isolate::PropagatePendingExceptionToExternalTryCatch() { Object* exception = pending_exception(); if (IsJavaScriptHandlerOnTop(exception)) { thread_local_top_.external_caught_exception_ = false; return false; } if (!IsExternalHandlerOnTop(exception)) { thread_local_top_.external_caught_exception_ = false; return true; } thread_local_top_.external_caught_exception_ = true; if (!is_catchable_by_javascript(exception)) { try_catch_handler()->can_continue_ = false; try_catch_handler()->has_terminated_ = true; try_catch_handler()->exception_ = heap()->null_value(); } else { v8::TryCatch* handler = try_catch_handler(); DCHECK(thread_local_top_.pending_message_obj_->IsJSMessageObject() || thread_local_top_.pending_message_obj_->IsTheHole(this)); handler->can_continue_ = true; handler->has_terminated_ = false; handler->exception_ = pending_exception(); // Propagate to the external try-catch only if we got an actual message. if (thread_local_top_.pending_message_obj_->IsTheHole(this)) return true; handler->message_obj_ = thread_local_top_.pending_message_obj_; } return true; } void Isolate::InitializeLoggingAndCounters() { if (logger_ == NULL) { logger_ = new Logger(this); } if (counters_ == NULL) { counters_ = new Counters(this); } } bool Isolate::Init(Deserializer* des) { TRACE_ISOLATE(init); stress_deopt_count_ = FLAG_deopt_every_n_times; has_fatal_error_ = false; if (function_entry_hook() != NULL) { // When function entry hooking is in effect, we have to create the code // stubs from scratch to get entry hooks, rather than loading the previously // generated stubs from disk. // If this assert fires, the initialization path has regressed. DCHECK(des == NULL); } // The initialization process does not handle memory exhaustion. AlwaysAllocateScope always_allocate(this); // Safe after setting Heap::isolate_, and initializing StackGuard heap_.SetStackLimits(); #define ASSIGN_ELEMENT(CamelName, hacker_name) \ isolate_addresses_[Isolate::k##CamelName##Address] = \ reinterpret_cast<Address>(hacker_name##_address()); FOR_EACH_ISOLATE_ADDRESS_NAME(ASSIGN_ELEMENT) #undef ASSIGN_ELEMENT compilation_cache_ = new CompilationCache(this); keyed_lookup_cache_ = new KeyedLookupCache(); context_slot_cache_ = new ContextSlotCache(); descriptor_lookup_cache_ = new DescriptorLookupCache(); unicode_cache_ = new UnicodeCache(); inner_pointer_to_code_cache_ = new InnerPointerToCodeCache(this); global_handles_ = new GlobalHandles(this); eternal_handles_ = new EternalHandles(); bootstrapper_ = new Bootstrapper(this); handle_scope_implementer_ = new HandleScopeImplementer(this); load_stub_cache_ = new StubCache(this, Code::LOAD_IC); store_stub_cache_ = new StubCache(this, Code::STORE_IC); materialized_object_store_ = new MaterializedObjectStore(this); regexp_stack_ = new RegExpStack(); regexp_stack_->isolate_ = this; date_cache_ = new DateCache(); call_descriptor_data_ = new CallInterfaceDescriptorData[CallDescriptors::NUMBER_OF_DESCRIPTORS]; cpu_profiler_ = new CpuProfiler(this); heap_profiler_ = new HeapProfiler(heap()); interpreter_ = new interpreter::Interpreter(this); // Enable logging before setting up the heap logger_->SetUp(this); // Initialize other runtime facilities #if defined(USE_SIMULATOR) #if V8_TARGET_ARCH_ARM || V8_TARGET_ARCH_ARM64 || V8_TARGET_ARCH_MIPS || \ V8_TARGET_ARCH_MIPS64 || V8_TARGET_ARCH_PPC || V8_TARGET_ARCH_S390 Simulator::Initialize(this); #endif #endif code_aging_helper_ = new CodeAgingHelper(this); { // NOLINT // Ensure that the thread has a valid stack guard. The v8::Locker object // will ensure this too, but we don't have to use lockers if we are only // using one thread. ExecutionAccess lock(this); stack_guard_.InitThread(lock); } // SetUp the object heap. DCHECK(!heap_.HasBeenSetUp()); if (!heap_.SetUp()) { V8::FatalProcessOutOfMemory("heap setup"); return false; } deoptimizer_data_ = new DeoptimizerData(heap()->memory_allocator()); const bool create_heap_objects = (des == NULL); if (create_heap_objects && !heap_.CreateHeapObjects()) { V8::FatalProcessOutOfMemory("heap object creation"); return false; } if (create_heap_objects) { // Terminate the partial snapshot cache so we can iterate. partial_snapshot_cache_.Add(heap_.undefined_value()); } InitializeThreadLocal(); bootstrapper_->Initialize(create_heap_objects); builtins_.SetUp(this, create_heap_objects); if (FLAG_log_internal_timer_events) { set_event_logger(Logger::DefaultEventLoggerSentinel); } if (FLAG_trace_hydrogen || FLAG_trace_hydrogen_stubs || FLAG_trace_turbo || FLAG_trace_turbo_graph) { PrintF("Concurrent recompilation has been disabled for tracing.\n"); } else if (OptimizingCompileDispatcher::Enabled()) { optimizing_compile_dispatcher_ = new OptimizingCompileDispatcher(this); } // Initialize runtime profiler before deserialization, because collections may // occur, clearing/updating ICs. runtime_profiler_ = new RuntimeProfiler(this); // If we are deserializing, read the state into the now-empty heap. if (!create_heap_objects) { des->Deserialize(this); } load_stub_cache_->Initialize(); store_stub_cache_->Initialize(); if (FLAG_ignition || serializer_enabled()) { interpreter_->Initialize(); } // Finish initialization of ThreadLocal after deserialization is done. clear_pending_exception(); clear_pending_message(); clear_scheduled_exception(); // Deserializing may put strange things in the root array's copy of the // stack guard. heap_.SetStackLimits(); // Quiet the heap NaN if needed on target platform. if (!create_heap_objects) Assembler::QuietNaN(heap_.nan_value()); if (FLAG_trace_turbo) { // Create an empty file. std::ofstream(GetTurboCfgFileName().c_str(), std::ios_base::trunc); } CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, embedder_data_)), Internals::kIsolateEmbedderDataOffset); CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.roots_)), Internals::kIsolateRootsOffset); CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.external_memory_)), Internals::kExternalMemoryOffset); CHECK_EQ(static_cast<int>(OFFSET_OF(Isolate, heap_.external_memory_limit_)), Internals::kExternalMemoryLimitOffset); time_millis_at_init_ = heap_.MonotonicallyIncreasingTimeInMs(); heap_.NotifyDeserializationComplete(); if (!create_heap_objects) { // Now that the heap is consistent, it's OK to generate the code for the // deopt entry table that might have been referred to by optimized code in // the snapshot. HandleScope scope(this); Deoptimizer::EnsureCodeForDeoptimizationEntry( this, Deoptimizer::LAZY, ExternalReferenceTable::kDeoptTableSerializeEntryCount - 1); } if (!serializer_enabled()) { // Ensure that all stubs which need to be generated ahead of time, but // cannot be serialized into the snapshot have been generated. HandleScope scope(this); CodeStub::GenerateFPStubs(this); StoreBufferOverflowStub::GenerateFixedRegStubsAheadOfTime(this); StubFailureTrampolineStub::GenerateAheadOfTime(this); } initialized_from_snapshot_ = (des != NULL); if (!FLAG_inline_new) heap_.DisableInlineAllocation(); return true; } // Initialized lazily to allow early // v8::V8::SetAddHistogramSampleFunction calls. StatsTable* Isolate::stats_table() { if (stats_table_ == NULL) { stats_table_ = new StatsTable; } return stats_table_; } void Isolate::Enter() { Isolate* current_isolate = NULL; PerIsolateThreadData* current_data = CurrentPerIsolateThreadData(); if (current_data != NULL) { current_isolate = current_data->isolate_; DCHECK(current_isolate != NULL); if (current_isolate == this) { DCHECK(Current() == this); DCHECK(entry_stack_ != NULL); DCHECK(entry_stack_->previous_thread_data == NULL || entry_stack_->previous_thread_data->thread_id().Equals( ThreadId::Current())); // Same thread re-enters the isolate, no need to re-init anything. entry_stack_->entry_count++; return; } } PerIsolateThreadData* data = FindOrAllocatePerThreadDataForThisThread(); DCHECK(data != NULL); DCHECK(data->isolate_ == this); EntryStackItem* item = new EntryStackItem(current_data, current_isolate, entry_stack_); entry_stack_ = item; SetIsolateThreadLocals(this, data); // In case it's the first time some thread enters the isolate. set_thread_id(data->thread_id()); } void Isolate::Exit() { DCHECK(entry_stack_ != NULL); DCHECK(entry_stack_->previous_thread_data == NULL || entry_stack_->previous_thread_data->thread_id().Equals( ThreadId::Current())); if (--entry_stack_->entry_count > 0) return; DCHECK(CurrentPerIsolateThreadData() != NULL); DCHECK(CurrentPerIsolateThreadData()->isolate_ == this); // Pop the stack. EntryStackItem* item = entry_stack_; entry_stack_ = item->previous_item; PerIsolateThreadData* previous_thread_data = item->previous_thread_data; Isolate* previous_isolate = item->previous_isolate; delete item; // Reinit the current thread for the isolate it was running before this one. SetIsolateThreadLocals(previous_isolate, previous_thread_data); } void Isolate::LinkDeferredHandles(DeferredHandles* deferred) { deferred->next_ = deferred_handles_head_; if (deferred_handles_head_ != NULL) { deferred_handles_head_->previous_ = deferred; } deferred_handles_head_ = deferred; } void Isolate::UnlinkDeferredHandles(DeferredHandles* deferred) { #ifdef DEBUG // In debug mode assert that the linked list is well-formed. DeferredHandles* deferred_iterator = deferred; while (deferred_iterator->previous_ != NULL) { deferred_iterator = deferred_iterator->previous_; } DCHECK(deferred_handles_head_ == deferred_iterator); #endif if (deferred_handles_head_ == deferred) { deferred_handles_head_ = deferred_handles_head_->next_; } if (deferred->next_ != NULL) { deferred->next_->previous_ = deferred->previous_; } if (deferred->previous_ != NULL) { deferred->previous_->next_ = deferred->next_; } } void Isolate::DumpAndResetCompilationStats() { if (turbo_statistics() != nullptr) { DCHECK(FLAG_turbo_stats || FLAG_turbo_stats_nvp); OFStream os(stdout); if (FLAG_turbo_stats) { AsPrintableStatistics ps = {*turbo_statistics(), false}; os << ps << std::endl; } if (FLAG_turbo_stats_nvp) { AsPrintableStatistics ps = {*turbo_statistics(), true}; os << ps << std::endl; } } if (hstatistics() != nullptr) hstatistics()->Print(); delete turbo_statistics_; turbo_statistics_ = nullptr; delete hstatistics_; hstatistics_ = nullptr; if (FLAG_runtime_call_stats) { OFStream os(stdout); counters()->runtime_call_stats()->Print(os); counters()->runtime_call_stats()->Reset(); } } HStatistics* Isolate::GetHStatistics() { if (hstatistics() == NULL) set_hstatistics(new HStatistics()); return hstatistics(); } CompilationStatistics* Isolate::GetTurboStatistics() { if (turbo_statistics() == NULL) set_turbo_statistics(new CompilationStatistics()); return turbo_statistics(); } HTracer* Isolate::GetHTracer() { if (htracer() == NULL) set_htracer(new HTracer(id())); return htracer(); } CodeTracer* Isolate::GetCodeTracer() { if (code_tracer() == NULL) set_code_tracer(new CodeTracer(id())); return code_tracer(); } Map* Isolate::get_initial_js_array_map(ElementsKind kind) { if (IsFastElementsKind(kind)) { DisallowHeapAllocation no_gc; Object* const initial_js_array_map = context()->native_context()->get(Context::ArrayMapIndex(kind)); if (!initial_js_array_map->IsUndefined(this)) { return Map::cast(initial_js_array_map); } } return nullptr; } bool Isolate::use_crankshaft() const { return FLAG_crankshaft && !serializer_enabled_ && CpuFeatures::SupportsCrankshaft(); } bool Isolate::IsArrayOrObjectPrototype(Object* object) { Object* context = heap()->native_contexts_list(); while (!context->IsUndefined(this)) { Context* current_context = Context::cast(context); if (current_context->initial_object_prototype() == object || current_context->initial_array_prototype() == object) { return true; } context = current_context->next_context_link(); } return false; } bool Isolate::IsInAnyContext(Object* object, uint32_t index) { DisallowHeapAllocation no_gc; Object* context = heap()->native_contexts_list(); while (!context->IsUndefined(this)) { Context* current_context = Context::cast(context); if (current_context->get(index) == object) { return true; } context = current_context->next_context_link(); } return false; } bool Isolate::IsFastArrayConstructorPrototypeChainIntact() { PropertyCell* no_elements_cell = heap()->array_protector(); bool cell_reports_intact = no_elements_cell->value()->IsSmi() && Smi::cast(no_elements_cell->value())->value() == kArrayProtectorValid; #ifdef DEBUG Map* root_array_map = get_initial_js_array_map(GetInitialFastElementsKind()); Context* native_context = context()->native_context(); JSObject* initial_array_proto = JSObject::cast( native_context->get(Context::INITIAL_ARRAY_PROTOTYPE_INDEX)); JSObject* initial_object_proto = JSObject::cast( native_context->get(Context::INITIAL_OBJECT_PROTOTYPE_INDEX)); if (root_array_map == NULL || initial_array_proto == initial_object_proto) { // We are in the bootstrapping process, and the entire check sequence // shouldn't be performed. return cell_reports_intact; } // Check that the array prototype hasn't been altered WRT empty elements. if (root_array_map->prototype() != initial_array_proto) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } FixedArrayBase* elements = initial_array_proto->elements(); if (elements != heap()->empty_fixed_array() && elements != heap()->empty_slow_element_dictionary()) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } // Check that the object prototype hasn't been altered WRT empty elements. PrototypeIterator iter(this, initial_array_proto); if (iter.IsAtEnd() || iter.GetCurrent() != initial_object_proto) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } elements = initial_object_proto->elements(); if (elements != heap()->empty_fixed_array() && elements != heap()->empty_slow_element_dictionary()) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } iter.Advance(); if (!iter.IsAtEnd()) { DCHECK_EQ(false, cell_reports_intact); return cell_reports_intact; } #endif return cell_reports_intact; } bool Isolate::IsIsConcatSpreadableLookupChainIntact() { Cell* is_concat_spreadable_cell = heap()->is_concat_spreadable_protector(); bool is_is_concat_spreadable_set = Smi::cast(is_concat_spreadable_cell->value())->value() == kArrayProtectorInvalid; #ifdef DEBUG Map* root_array_map = get_initial_js_array_map(GetInitialFastElementsKind()); if (root_array_map == NULL) { // Ignore the value of is_concat_spreadable during bootstrap. return !is_is_concat_spreadable_set; } Handle<Object> array_prototype(array_function()->prototype(), this); Handle<Symbol> key = factory()->is_concat_spreadable_symbol(); Handle<Object> value; LookupIterator it(array_prototype, key); if (it.IsFound() && !JSReceiver::GetDataProperty(&it)->IsUndefined(this)) { // TODO(cbruni): Currently we do not revert if we unset the // @@isConcatSpreadable property on Array.prototype or Object.prototype // hence the reverse implication doesn't hold. DCHECK(is_is_concat_spreadable_set); return false; } #endif // DEBUG return !is_is_concat_spreadable_set; } void Isolate::UpdateArrayProtectorOnSetElement(Handle<JSObject> object) { DisallowHeapAllocation no_gc; if (!object->map()->is_prototype_map()) return; if (!IsFastArrayConstructorPrototypeChainIntact()) return; if (!IsArrayOrObjectPrototype(*object)) return; PropertyCell::SetValueWithInvalidation( factory()->array_protector(), handle(Smi::FromInt(kArrayProtectorInvalid), this)); } void Isolate::InvalidateHasInstanceProtector() { DCHECK(factory()->has_instance_protector()->value()->IsSmi()); DCHECK(IsHasInstanceLookupChainIntact()); PropertyCell::SetValueWithInvalidation( factory()->has_instance_protector(), handle(Smi::FromInt(kArrayProtectorInvalid), this)); DCHECK(!IsHasInstanceLookupChainIntact()); } void Isolate::InvalidateIsConcatSpreadableProtector() { DCHECK(factory()->is_concat_spreadable_protector()->value()->IsSmi()); DCHECK(IsIsConcatSpreadableLookupChainIntact()); factory()->is_concat_spreadable_protector()->set_value( Smi::FromInt(kArrayProtectorInvalid)); DCHECK(!IsIsConcatSpreadableLookupChainIntact()); } void Isolate::InvalidateArraySpeciesProtector() { DCHECK(factory()->species_protector()->value()->IsSmi()); DCHECK(IsArraySpeciesLookupChainIntact()); factory()->species_protector()->set_value( Smi::FromInt(kArrayProtectorInvalid)); DCHECK(!IsArraySpeciesLookupChainIntact()); } bool Isolate::IsAnyInitialArrayPrototype(Handle<JSArray> array) { DisallowHeapAllocation no_gc; return IsInAnyContext(*array, Context::INITIAL_ARRAY_PROTOTYPE_INDEX); } CallInterfaceDescriptorData* Isolate::call_descriptor_data(int index) { DCHECK(0 <= index && index < CallDescriptors::NUMBER_OF_DESCRIPTORS); return &call_descriptor_data_[index]; } base::RandomNumberGenerator* Isolate::random_number_generator() { if (random_number_generator_ == NULL) { if (FLAG_random_seed != 0) { random_number_generator_ = new base::RandomNumberGenerator(FLAG_random_seed); } else { random_number_generator_ = new base::RandomNumberGenerator(); } } return random_number_generator_; } Object* Isolate::FindCodeObject(Address a) { return inner_pointer_to_code_cache()->GcSafeFindCodeForInnerPointer(a); } #ifdef DEBUG #define ISOLATE_FIELD_OFFSET(type, name, ignored) \ const intptr_t Isolate::name##_debug_offset_ = OFFSET_OF(Isolate, name##_); ISOLATE_INIT_LIST(ISOLATE_FIELD_OFFSET) ISOLATE_INIT_ARRAY_LIST(ISOLATE_FIELD_OFFSET) #undef ISOLATE_FIELD_OFFSET #endif Handle<JSObject> Isolate::SetUpSubregistry(Handle<JSObject> registry, Handle<Map> map, const char* cname) { Handle<String> name = factory()->InternalizeUtf8String(cname); Handle<JSObject> obj = factory()->NewJSObjectFromMap(map); JSObject::NormalizeProperties(obj, CLEAR_INOBJECT_PROPERTIES, 0, "SetupSymbolRegistry"); JSObject::AddProperty(registry, name, obj, NONE); return obj; } Handle<JSObject> Isolate::GetSymbolRegistry() { if (heap()->symbol_registry()->IsSmi()) { Handle<Map> map = factory()->NewMap(JS_OBJECT_TYPE, JSObject::kHeaderSize); Handle<JSObject> registry = factory()->NewJSObjectFromMap(map); heap()->set_symbol_registry(*registry); SetUpSubregistry(registry, map, "for"); SetUpSubregistry(registry, map, "for_api"); SetUpSubregistry(registry, map, "keyFor"); SetUpSubregistry(registry, map, "private_api"); } return Handle<JSObject>::cast(factory()->symbol_registry()); } void Isolate::AddBeforeCallEnteredCallback(BeforeCallEnteredCallback callback) { for (int i = 0; i < before_call_entered_callbacks_.length(); i++) { if (callback == before_call_entered_callbacks_.at(i)) return; } before_call_entered_callbacks_.Add(callback); } void Isolate::RemoveBeforeCallEnteredCallback( BeforeCallEnteredCallback callback) { for (int i = 0; i < before_call_entered_callbacks_.length(); i++) { if (callback == before_call_entered_callbacks_.at(i)) { before_call_entered_callbacks_.Remove(i); } } } void Isolate::FireBeforeCallEnteredCallback() { for (int i = 0; i < before_call_entered_callbacks_.length(); i++) { before_call_entered_callbacks_.at(i)(reinterpret_cast<v8::Isolate*>(this)); } } void Isolate::AddCallCompletedCallback(CallCompletedCallback callback) { for (int i = 0; i < call_completed_callbacks_.length(); i++) { if (callback == call_completed_callbacks_.at(i)) return; } call_completed_callbacks_.Add(callback); } void Isolate::RemoveCallCompletedCallback(CallCompletedCallback callback) { for (int i = 0; i < call_completed_callbacks_.length(); i++) { if (callback == call_completed_callbacks_.at(i)) { call_completed_callbacks_.Remove(i); } } } void Isolate::FireCallCompletedCallback() { if (!handle_scope_implementer()->CallDepthIsZero()) return; bool run_microtasks = pending_microtask_count() && !handle_scope_implementer()->HasMicrotasksSuppressions() && handle_scope_implementer()->microtasks_policy() == v8::MicrotasksPolicy::kAuto; if (run_microtasks) RunMicrotasks(); // Prevent stepping from spilling into the next call made by the embedder. if (debug()->is_active()) debug()->ClearStepping(); if (call_completed_callbacks_.is_empty()) return; // Fire callbacks. Increase call depth to prevent recursive callbacks. v8::Isolate* isolate = reinterpret_cast<v8::Isolate*>(this); v8::Isolate::SuppressMicrotaskExecutionScope suppress(isolate); for (int i = 0; i < call_completed_callbacks_.length(); i++) { call_completed_callbacks_.at(i)(isolate); } } void Isolate::SetPromiseRejectCallback(PromiseRejectCallback callback) { promise_reject_callback_ = callback; } void Isolate::ReportPromiseReject(Handle<JSObject> promise, Handle<Object> value, v8::PromiseRejectEvent event) { if (promise_reject_callback_ == NULL) return; Handle<JSArray> stack_trace; if (event == v8::kPromiseRejectWithNoHandler && value->IsJSObject()) { stack_trace = GetDetailedStackTrace(Handle<JSObject>::cast(value)); } promise_reject_callback_(v8::PromiseRejectMessage( v8::Utils::PromiseToLocal(promise), event, v8::Utils::ToLocal(value), v8::Utils::StackTraceToLocal(stack_trace))); } void Isolate::EnqueueMicrotask(Handle<Object> microtask) { DCHECK(microtask->IsJSFunction() || microtask->IsCallHandlerInfo()); Handle<FixedArray> queue(heap()->microtask_queue(), this); int num_tasks = pending_microtask_count(); DCHECK(num_tasks <= queue->length()); if (num_tasks == 0) { queue = factory()->NewFixedArray(8); heap()->set_microtask_queue(*queue); } else if (num_tasks == queue->length()) { queue = factory()->CopyFixedArrayAndGrow(queue, num_tasks); heap()->set_microtask_queue(*queue); } DCHECK(queue->get(num_tasks)->IsUndefined(this)); queue->set(num_tasks, *microtask); set_pending_microtask_count(num_tasks + 1); } void Isolate::RunMicrotasks() { // Increase call depth to prevent recursive callbacks. v8::Isolate::SuppressMicrotaskExecutionScope suppress( reinterpret_cast<v8::Isolate*>(this)); is_running_microtasks_ = true; RunMicrotasksInternal(); is_running_microtasks_ = false; FireMicrotasksCompletedCallback(); } void Isolate::RunMicrotasksInternal() { while (pending_microtask_count() > 0) { HandleScope scope(this); int num_tasks = pending_microtask_count(); Handle<FixedArray> queue(heap()->microtask_queue(), this); DCHECK(num_tasks <= queue->length()); set_pending_microtask_count(0); heap()->set_microtask_queue(heap()->empty_fixed_array()); Isolate* isolate = this; FOR_WITH_HANDLE_SCOPE(isolate, int, i = 0, i, i < num_tasks, i++, { Handle<Object> microtask(queue->get(i), this); if (microtask->IsJSFunction()) { Handle<JSFunction> microtask_function = Handle<JSFunction>::cast(microtask); SaveContext save(this); set_context(microtask_function->context()->native_context()); MaybeHandle<Object> maybe_exception; MaybeHandle<Object> result = Execution::TryCall( this, microtask_function, factory()->undefined_value(), 0, NULL, &maybe_exception); // If execution is terminating, just bail out. Handle<Object> exception; if (result.is_null() && maybe_exception.is_null()) { // Clear out any remaining callbacks in the queue. heap()->set_microtask_queue(heap()->empty_fixed_array()); set_pending_microtask_count(0); return; } } else { Handle<CallHandlerInfo> callback_info = Handle<CallHandlerInfo>::cast(microtask); v8::MicrotaskCallback callback = v8::ToCData<v8::MicrotaskCallback>(callback_info->callback()); void* data = v8::ToCData<void*>(callback_info->data()); callback(data); } }); } } void Isolate::AddMicrotasksCompletedCallback( MicrotasksCompletedCallback callback) { for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) { if (callback == microtasks_completed_callbacks_.at(i)) return; } microtasks_completed_callbacks_.Add(callback); } void Isolate::RemoveMicrotasksCompletedCallback( MicrotasksCompletedCallback callback) { for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) { if (callback == microtasks_completed_callbacks_.at(i)) { microtasks_completed_callbacks_.Remove(i); } } } void Isolate::FireMicrotasksCompletedCallback() { for (int i = 0; i < microtasks_completed_callbacks_.length(); i++) { microtasks_completed_callbacks_.at(i)(reinterpret_cast<v8::Isolate*>(this)); } } void Isolate::SetUseCounterCallback(v8::Isolate::UseCounterCallback callback) { DCHECK(!use_counter_callback_); use_counter_callback_ = callback; } void Isolate::CountUsage(v8::Isolate::UseCounterFeature feature) { // The counter callback may cause the embedder to call into V8, which is not // generally possible during GC. if (heap_.gc_state() == Heap::NOT_IN_GC) { if (use_counter_callback_) { HandleScope handle_scope(this); use_counter_callback_(reinterpret_cast<v8::Isolate*>(this), feature); } } else { heap_.IncrementDeferredCount(feature); } } BasicBlockProfiler* Isolate::GetOrCreateBasicBlockProfiler() { if (basic_block_profiler_ == NULL) { basic_block_profiler_ = new BasicBlockProfiler(); } return basic_block_profiler_; } std::string Isolate::GetTurboCfgFileName() { if (FLAG_trace_turbo_cfg_file == NULL) { std::ostringstream os; os << "turbo-" << base::OS::GetCurrentProcessId() << "-" << id() << ".cfg"; return os.str(); } else { return FLAG_trace_turbo_cfg_file; } } void Isolate::SetTailCallEliminationEnabled(bool enabled) { if (is_tail_call_elimination_enabled_ == enabled) return; is_tail_call_elimination_enabled_ = enabled; // TODO(ishell): Introduce DependencyGroup::kTailCallChangedGroup to // deoptimize only those functions that are affected by the change of this // flag. internal::Deoptimizer::DeoptimizeAll(this); } // Heap::detached_contexts tracks detached contexts as pairs // (number of GC since the context was detached, the context). void Isolate::AddDetachedContext(Handle<Context> context) { HandleScope scope(this); Handle<WeakCell> cell = factory()->NewWeakCell(context); Handle<FixedArray> detached_contexts(heap()->detached_contexts()); int length = detached_contexts->length(); detached_contexts = factory()->CopyFixedArrayAndGrow(detached_contexts, 2); detached_contexts->set(length, Smi::FromInt(0)); detached_contexts->set(length + 1, *cell); heap()->set_detached_contexts(*detached_contexts); } void Isolate::CheckDetachedContextsAfterGC() { HandleScope scope(this); Handle<FixedArray> detached_contexts(heap()->detached_contexts()); int length = detached_contexts->length(); if (length == 0) return; int new_length = 0; for (int i = 0; i < length; i += 2) { int mark_sweeps = Smi::cast(detached_contexts->get(i))->value(); DCHECK(detached_contexts->get(i + 1)->IsWeakCell()); WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1)); if (!cell->cleared()) { detached_contexts->set(new_length, Smi::FromInt(mark_sweeps + 1)); detached_contexts->set(new_length + 1, cell); new_length += 2; } counters()->detached_context_age_in_gc()->AddSample(mark_sweeps + 1); } if (FLAG_trace_detached_contexts) { PrintF("%d detached contexts are collected out of %d\n", length - new_length, length); for (int i = 0; i < new_length; i += 2) { int mark_sweeps = Smi::cast(detached_contexts->get(i))->value(); DCHECK(detached_contexts->get(i + 1)->IsWeakCell()); WeakCell* cell = WeakCell::cast(detached_contexts->get(i + 1)); if (mark_sweeps > 3) { PrintF("detached context %p\n survived %d GCs (leak?)\n", static_cast<void*>(cell->value()), mark_sweeps); } } } if (new_length == 0) { heap()->set_detached_contexts(heap()->empty_fixed_array()); } else if (new_length < length) { heap()->RightTrimFixedArray<Heap::CONCURRENT_TO_SWEEPER>( *detached_contexts, length - new_length); } } void Isolate::SetRAILMode(RAILMode rail_mode) { rail_mode_.SetValue(rail_mode); if (FLAG_trace_rail) { PrintIsolate(this, "RAIL mode: %s\n", RAILModeName(rail_mode)); } } bool StackLimitCheck::JsHasOverflowed(uintptr_t gap) const { StackGuard* stack_guard = isolate_->stack_guard(); #ifdef USE_SIMULATOR // The simulator uses a separate JS stack. Address jssp_address = Simulator::current(isolate_)->get_sp(); uintptr_t jssp = reinterpret_cast<uintptr_t>(jssp_address); if (jssp - gap < stack_guard->real_jslimit()) return true; #endif // USE_SIMULATOR return GetCurrentStackPosition() - gap < stack_guard->real_climit(); } SaveContext::SaveContext(Isolate* isolate) : isolate_(isolate), prev_(isolate->save_context()) { if (isolate->context() != NULL) { context_ = Handle<Context>(isolate->context()); } isolate->set_save_context(this); c_entry_fp_ = isolate->c_entry_fp(isolate->thread_local_top()); } SaveContext::~SaveContext() { isolate_->set_context(context_.is_null() ? NULL : *context_); isolate_->set_save_context(prev_); } #ifdef DEBUG AssertNoContextChange::AssertNoContextChange(Isolate* isolate) : isolate_(isolate), context_(isolate->context(), isolate) {} #endif // DEBUG bool PostponeInterruptsScope::Intercept(StackGuard::InterruptFlag flag) { // First check whether the previous scope intercepts. if (prev_ && prev_->Intercept(flag)) return true; // Then check whether this scope intercepts. if ((flag & intercept_mask_)) { intercepted_flags_ |= flag; return true; } return false; } } // namespace internal } // namespace v8
[ "liuming@kuaishou.com" ]
liuming@kuaishou.com
cfefc658aa63d07d767f2980a026aee7ea5aafc4
3792b3bb6446a0f40e9e1d4ce0873f94f41a85fe
/samples/test.cc
f1d8c3e3880d3d88e2ca21f8c1d582902223733a
[]
no_license
mismayil/rpc
7d3addd4119d3b0fee247d4028cb3f8a4e4eda55
dc7deca8c82403def17a41432c2bc29ed0a6eaab
refs/heads/master
2021-01-21T15:21:54.391504
2018-03-01T02:04:56
2018-03-01T02:04:56
54,075,365
0
0
null
null
null
null
UTF-8
C++
false
false
75
cc
#include <iostream> using namespace std; int main() { delete NULL; }
[ "mismayil@uwaterloo.ca" ]
mismayil@uwaterloo.ca
7b6dc4187a55de7260730cf5383bdb71d97469d9
b1c3093282dceadd3e367ae14af633ed39957fd6
/dump/APTDUMP.CPP
b76abbacb909d8984b6040fbe214b1cbd4e0c333
[ "CC0-1.0", "LicenseRef-scancode-public-domain" ]
permissive
nmathewson/aptor1995
23c00f21646f601faa6e2a82b701f1fd489b4d52
8858d7ba871d9263eca302e7ca9e15b005c54d99
refs/heads/master
2020-06-06T09:51:11.644133
2013-08-29T01:45:09
2013-08-29T01:45:09
null
0
0
null
null
null
null
UTF-8
C++
false
false
10,786
cpp
/////////////////////////////////////////////////////////////////////////// /// Filename: APTDUMP.CPP /// /// Long filename: APTOR .apx dumping file /// /// File type: C ++ code /// /// Project: APTOR /// /////////////////////////////////////////////////////////////////////////// /// Uses: APTOR, NAMEREF2, CRYPT /// /////////////////////////////////////////////////////////////////////////// /// Synopsis: This is a simple dumping program that will test APTOR.CPP /// /// by echoing (to a file, or to the screen) a complete read- /// /// out of a given .APX family. /// /////////////////////////////////////////////////////////////////////////// /// Author: N.A.A. Mathewson /// /// Date: 7/19/95 Revision: 1.0 /// /////////////////////////////////////////////////////////////////////////// #include <fstream.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #include <dir.h> #include "flag.h" #include "aptor.h" #define FNAME_LEN 12 #define DEBUGGING 1 ///////////// // GLOBALS // ///////////// flag verbose; ///////////// // STRUCTS // ///////////// struct control { char family[FNAME_LEN+1]; char apx_name[FNAME_LEN+1]; char map_name[FNAME_LEN+1]; char mpx_name[FNAME_LEN+1]; flag mpx; // TRUE: use .MPX has been forced. flag out_file; char out_name[FNAME_LEN+1]; }; enum types { APX = 0, MAP = 1, MPX = 2 }; struct which_files { flag apx; flag map; flag mpx; }; ///////////// // PARSING // ///////////// void build_control( control &c, int argc, char *argv[] ); // Builds the given control structure from the command line and from the // disk directory. void check_files( control &c, which_files &w ); // Checks to see which files of a given family name exist. void parse_cmd_line(control &c, int argc, char *argv[]); // Called by build_control. void subparse_cmd_line(control &c, char *word); // Called by parse_cmd_line. int parse_filename(char *d, const char *s); // Copies & parsesfilename s into d, returning nonzero for error. char *new_ext(char *f, const char *ext); // Tacks extention ext onto parsed fname f. ////////// // HELP // ////////// void show_help(void); // Displays the standard help screen. Exits APTDUMP. /////////////// // DEBUGGING // /////////////// void show_control(control &c); // Pretty-prints members of c. ////////// // DUMP // ////////// void dump(control &c); // Opens APTOR_file, output file, and handles all actual dumping. void print(APTOR_file &af, int n, ostream &out, flag mpx); // Prints a given block to the given output device. void header(control &c, APTOR_file &af, ostream &out); // Prints a header to the output device. ////////// // MAIN // ////////// int main(int argc, char *argv[]) { control c; build_control(c, argc, argv); if (DEBUGGING || verbose) show_control(c); dump(c); return 0; }; ///////////// // PARSING // ///////////// void build_control(control &c, int argc, char *argv[]) { // SETUP MEMBERS c.family[0] = '\0'; c.apx_name[0] = '\0'; c.map_name[0] = '\0'; c.mpx_name[0] = '\0'; c.out_name[0] = '\0'; c.out_file = FALSE; c.mpx = FALSE; parse_cmd_line(c, argc, argv); if (! c.family[0]) { cout << "ERROR: No filename specified.\n"; exit(1); }; if (c.out_name[0]) c.out_file = TRUE; which_files w; check_files(c, w); if (! w.apx) { cout << "ERROR: " << c.apx_name << " does not exist.\n"; exit(1); }; if (c.mpx) { if (! w.mpx) { cout << "ERROR: " << new_ext(c.family, "MPX") << " does not exist.\n"; exit(1); }; } else { if (! w.map) { if (w.mpx) c.mpx = TRUE; else { cout << "ERROR: Can't find " << new_ext(c.family, "MAP") << " or " << new_ext(c.family, "MPX"); exit(1); }; }; }; } void check_files(control &c, which_files &w) { ffblk ff; char *cp; int done; w.apx = FALSE; w.map = FALSE; w.mpx = FALSE; new_ext(c.family, " "); // FIRST, FIND A GOOD APX strcpy(c.apx_name, c.family); new_ext(c.apx_name, "APX"); if (findfirst(c.apx_name, &ff, 0)) // no apx found? return; if (parse_filename(c.apx_name, ff.ff_name)) return; w.apx = TRUE; // THEN, SEE WHAT ELSE THERE IS! strcpy(c.family, c.apx_name); new_ext(c.family, "* "); if (findfirst(c.family, &ff, 0)) return; done = FALSE; while (! done) { cp = strchr(ff.ff_name, '.'); if (strcmpi(cp, ".map") == 0) { parse_filename(c.map_name, ff.ff_name); w.map = TRUE; }; if (strcmpi(cp, ".mpx") == 0) { parse_filename(c.mpx_name, ff.ff_name); w.mpx = TRUE; }; done = findnext(&ff); }; } void parse_cmd_line(control &c, int argc, char *argv[]) { if (argc == 1) show_help(); for(int i = 1; i < argc; ++i) subparse_cmd_line(c, argv[i]); } void subparse_cmd_line(control &c, char *word) { strlwr(word); if ((word[0] == '-') || (word[0] == '/')) { if ( (strcmp(&word[1], "?") == 0) || (strcmp(&word[1], "h") == 0) ) show_help(); else if (strcmp(&word[1], "mpx") == 0) c.mpx = TRUE; else if (strcmp(&word[1], "v") == 0) verbose = TRUE; else if (word[1] == 'f') { if (c.out_name[0] != '\0') { cout << "ERROR: Multiple output files.\n"; exit(1); }; if (parse_filename(c.out_name, &word[2])) { cout << "Bad output filename: " << (&word[2]) << "\n"; exit(1); }; } else { cout << "Bad switch: " << word << "\n"; exit(1); }; } else { if (c.family[0] != '\0') { cout << "ERROR: Multiple input files.\n"; exit(1); }; if (parse_filename(c.family, word)) { cout << "Bad filename: " << word << "\n"; exit(1); }; }; } int parse_filename(char *d, const char *s) { if (strlen(s) > FNAME_LEN) // s too long? return 2; if (s[0] == 0) // s too short? return 3; strcpy(d, s); // copy s into d. for(int i = 0; d[i]; i++) // make d uppercase. d[i] = toupper(d[i]); i = 0; int period_pos = -1; while(d[i]) // make sure fname in bounds... { if (d[i] == ' ') // This should never happen. return 5; if ((d[i] == '.') && (period_pos > -1) ) period_pos = 50; if ((d[i] == '.') && (period_pos == -1)) period_pos = i; i++; }; if (period_pos > 8) // If more than 8 characters read return 6; // before the '.', error. if (period_pos == 0) // At least 1 char in fname. return 7; // At this point, we know that FFF.XXX has 1<= FFF <=8. Maybe no '.', // and maybe XXX too long. if ((period_pos == -1) && // prevent FFFF > 8, no '.' (i > 8)) return 8; if ((period_pos > -1) && // prevent .XXXX ((i - period_pos) > 4) ) return 9; if (period_pos == -1) // There must be a period!!! { d[i] = '.'; d[i+1] = '\x00'; }; return 0; // Everything's OK!! } char *new_ext(char *f, const char *ext) { char *d; d = f; while ((*d) && (*d != '.')) ++d; ++d; strcpy(d, ext); return f; } ////////// // HELP // ////////// void show_help(void) { cout << "SYNTAX: \n" " APTDUMP [switches] <filename> [switches]\n\n" "-mpx : use .mpx file only.\n" "-f!!!! : echo dump to file !!!!\n" "-v : verbose messages (for debugging)\n" "-? : display this screeen.\n"; exit(0); } /////////////// // DEBUGGING // /////////////// void show_control(control &c) { cout << "Family name: " << c.family << "\n" ".apx name: " << c.apx_name << "\n" ".map name: " << c.map_name << "\n" ".mpx name: " << c.mpx_name << "\n"; if (c.mpx) cout << "Reading map from " << c.mpx_name << "\n"; else cout << "Reading map from " << c.map_name << "\n"; if (c.out_file) cout << "Writing info to " << c.out_name << "\n\n"; else cout << "Writing info to the screen.\n\n"; } ////////// // DUMP // ////////// void dump(control &c) { ofstream *out; // OPEN OUTPUT FILE if (c.out_file) { out = new ofstream(c.out_name); if (! out->good()) { cout << "ERROR: Unable to open " << c.out_name << "\n"; exit(1); }; }; // OPEN APTOR FILE APTOR_file af; if (c.mpx) af.open(c.apx_name, c.mpx_name); else af.open(c.apx_name, c.map_name); if (! af.ok()) { cout << "ERROR: Unable to open APTOR_file\n"; exit(1); }; // DUMP! header(c, af, cout); if (c.out_file) header(c, af, *out); int i, n; n = af.n(); for(i = 0; i < n; ++i) { print(af, i, cout, c.mpx); if (c.out_file) print(af, i, *out, c.mpx); }; if (c.out_file) out->close(); af.close(); }; void print(APTOR_file &af, int n, ostream &out, flag mpx) { static char line[80]; static char word[80]; for(int i = 0; i < 79; ++i) line[i] = '-'; line[i] = '\0'; itoa(n, word, 10); if (! mpx) { strcat(word, " "); strcat(word, af.name(n)); }; int pos, len; len = strlen(word); pos = (79 - len) / 2; strcpy(&line[pos], word); line[pos-1] = ' '; line[pos+len] = ' '; out << line << "\n"; out << af[n] << "\n"; }; void header(control &c, APTOR_file &af, ostream &out) { static char line[] = "\ -------------------------------------------------------------------------------\ "; out << line << "\n"; out << "TRANSCRIPT OF " << c.apx_name; if (c.mpx) out << "\n"; else out << ", WITH BLOCK NAMES\n"; out << "TOTAL OF " << af.n() << " BLOCKS\n"; out << line << "\n"; }
[ "nickm@torproject.org" ]
nickm@torproject.org
507aeae68f0446b0ecfec910ec6637d33cbabd35
9a0af9a2a1fb9aba567f392bbf7ac0e9601f5f9f
/FinalProject2/New/include/PizzaFromMenu.h
a3ebe43fbfa0e775a436530c3904d6423d637ce0
[]
no_license
omars08/three.weeks
9f920ea063efa1709326ab880242df4a8a211249
7ab2a308dd17d86bed5b5b5adb1e438d52a0e570
refs/heads/master
2021-08-28T14:49:29.439861
2017-12-12T13:49:15
2017-12-12T13:49:15
null
0
0
null
null
null
null
UTF-8
C++
false
false
203
h
#ifndef PIZZAFROMMENU_H #define PIZZAFROMMENU_H class PizzaFromMenu { public: PizzaFromMenu(); virtual ~PizzaFromMenu(); protected: private: }; #endif // PIZZAFROMMENU_H
[ "sindridan@gmail.com" ]
sindridan@gmail.com
881ca26fca9e71b5f6ca61a74f2f20408219a0a8
8236d6101d21f50dda499c4ead7862c922885aee
/Arduino/ADC_DAC_Timer/ADC_DAC_Timer.h
1966e6b209fd710b5b4360f568ef381cffc9cdcf
[ "MIT" ]
permissive
manasdas17/NightcoreThis
fdd498dc39ad870b7439e3bdaf63fa3e4fa97b56
fce141ad69f159e4cd4d9e741c6603761d882411
refs/heads/master
2021-01-22T09:04:10.071096
2016-01-30T11:27:52
2016-01-30T11:27:52
null
0
0
null
null
null
null
UTF-8
C++
false
false
408
h
/* ADC_DAC_Timer.h - Library for running ADC and DAC at a specified sample rate on the Ardunio Due Created by Robert FK Triggs, July 30th 2014 Released into the public domain. */ #ifndef ADC_DAC_Timer_h #define ADC_DAC_Timer_h #include "Arduino.h" class ADC_DAC_Timer { public: ADC_DAC_Timer(); void set_sample_rate(int Freq); void dac0_setup (); void adc0_setup (); private: }; #endif
[ "brecht.carlier@student.ap.be" ]
brecht.carlier@student.ap.be
388cf8c2acb3b247403143df6a134f3ee3f78915
79eb83cc3e7f4324ad3f7e56f094384ee494a7a9
/Async/AsyncResource.h
814fa53b26ea8a8076056b88848e30359fffe055
[]
no_license
JiaoMing/Blackcat
4a32ab2ec1abc356a4494ec9177ad0b3128d575b
95fa6f74429ead752741cbff3debca8bb0cbdb6e
refs/heads/master
2020-04-15T11:08:28.111536
2014-11-13T08:40:57
2014-11-13T08:40:57
30,082,134
0
4
null
2015-01-30T17:10:54
2015-01-30T17:10:53
null
UTF-8
C++
false
false
547
h
#ifndef __ASYNC_RESOURCE_H__ #define __ASYNC_RESOURCE_H__ #include "cocos2d.h" using namespace cocos2d; typedef CCScene* (*SEL_SceneHandler)(); #define scene_selector(_SELECTOR) (SEL_SceneHandler)(&_SELECTOR) class AsyncResource { public: AsyncResource(); ~AsyncResource(); static AsyncResource *sharedAsyncResource(); const char *getPlistData(const char *pszSceneName); const char *getJpgData(const char *pszSceneName); SEL_SceneHandler getSelector(const char *pszSceneName); }; #endif // __ASYNC_RESOURCE_H__
[ "380050803@qq.com" ]
380050803@qq.com
43788ab30a627e091e6b30b47d221c889e698501
f2825e96de42b553eb974c97b55b5834946d1f64
/musci/login.cpp
72a90715107e4e60c606454ac3ee3677dbcc6da2
[]
no_license
GYSml/QT
afce7102abf6ffec10c153903071826a483bba3b
965a1fb2456f52c242ac19fa613a222dab455d57
refs/heads/master
2021-01-01T04:45:55.196646
2016-05-14T11:36:04
2016-05-14T11:36:04
56,762,352
1
1
null
null
null
null
UTF-8
C++
false
false
373
cpp
#include "login.h" #include "ui_login.h" Login::Login(QWidget *parent) : QDialog(parent), ui(new Ui::Login) { ui->setupUi(this); resize(300,200); } Login::~Login() { delete ui; } void Login::on_pushButton_3_clicked() { exit(0); } void Login::on_pushButton_4_clicked() { this->setWindowFlags(windowFlags()|Qt::WindowMinimizeButtonHint); }
[ "1358121691@qq.com" ]
1358121691@qq.com
aa87359be2add5f9ebcc52bb78e217f987a0d3f7
0bf5a4f159e45546ec3e9b094608e3e4439608a7
/PAT/Basic Level/1032. 挖掘机技术哪家强.cpp
355c34479b6dc85a010784a7f31b8b0c1ffaa911
[ "ICU" ]
permissive
richenyunqi/CCF-CSP-and-PAT-solution
4178694c8b213cf2aeb51f0846e99e7d47863d4a
4e12e2dbe9a3822e357ba98799d82700f46beb24
refs/heads/master
2023-09-02T12:49:32.328292
2022-05-14T08:37:48
2022-05-14T08:37:48
162,964,774
668
118
null
2022-05-14T08:39:08
2018-12-24T07:45:38
C++
UTF-8
C++
false
false
373
cpp
#include <bits/stdc++.h> using namespace std; using gg = long long; int main() { ios::sync_with_stdio(false); cin.tie(0); array<gg, (gg)1e5 + 5> h{}; gg n; cin >> n; while (n--) { gg a, b; cin >> a >> b; h[a] += b; } auto i = max_element(h.begin(), h.end()); cout << (i - h.begin()) << ' ' << *i; return 0; }
[ "csjiangfeng@gmail.com" ]
csjiangfeng@gmail.com
768db8256f8fb273fd81b04ccb371b755f3602b8
fbf49ac1585c87725a0f5edcb80f1fe7a6c2041f
/SDK/Sub_Npc003_01_classes.h
a736f29c134c5b8ae32f47fd74a41e00d4b8a5cc
[]
no_license
zanzo420/DBZ-Kakarot-SDK
d5a69cd4b147d23538b496b7fa7ba4802fccf7ac
73c2a97080c7ebedc7d538f72ee21b50627f2e74
refs/heads/master
2021-02-12T21:14:07.098275
2020-03-16T10:07:00
2020-03-16T10:07:00
244,631,123
0
1
null
null
null
null
UTF-8
C++
false
false
1,576
h
#pragma once // Name: DBZKakarot, Version: 1.0.3 #ifdef _MSC_VER #pragma pack(push, 0x8) #endif namespace SDK { //--------------------------------------------------------------------------- // Classes //--------------------------------------------------------------------------- // BlueprintGeneratedClass Sub_Npc003_01.Sub_Npc003_01_C // 0x0011 (0x04D1 - 0x04C0) class ASub_Npc003_01_C : public AQuestGeneral_BP_C { public: struct FPointerToUberGraphFrame UberGraphFrame; // 0x04C0(0x0008) (ZeroConstructor, Transient, DuplicateTransient) struct FName quest_id; // 0x04C8(0x0008) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) bool canceled; // 0x04D0(0x0001) (Edit, BlueprintVisible, ZeroConstructor, DisableEditOnInstance, IsPlainOldData) static UClass* StaticClass() { static auto ptr = UObject::FindClass("BlueprintGeneratedClass Sub_Npc003_01.Sub_Npc003_01_C"); return ptr; } void hidden_actor(const struct FName& findId); void UserConstructionScript(); void PhaseEvent(); void OnCancelSubQuestTransition(); void OnCancelSubQuest(); void OnOpenSimpleTalk(const struct FName& SimpleTalkId, const struct FName& messageId); void OnIngameBegan(); void CustomEvent_1(); void ExecuteUbergraph_Sub_Npc003_01(int EntryPoint); }; } #ifdef _MSC_VER #pragma pack(pop) #endif
[ "zp2kshield@gmail.com" ]
zp2kshield@gmail.com
ab1717146ef83de5b2e4d80270d0335ec7f48216
95f374301236308e4c3820e0deb5b02a1baa7f91
/rymobile/frameworks/runtime-src/Classes/LuaAssert/ry_Util.h
3d1c4da6708920bab345a3b45545256c63a83e0b
[]
no_license
aywlcn/510Game
53f02b1a07818ad3661f1b2c0c8d52791b355b05
653490b2e0246fb7f37864a164d65236ab05a410
refs/heads/master
2020-07-04T05:04:27.937878
2019-08-13T23:19:36
2019-08-13T23:19:36
202,165,219
0
0
null
2019-08-13T14:45:44
2019-08-13T14:45:43
null
UTF-8
C++
false
false
433
h
// // ry_Util.hpp // GloryProject // // Created by chunyong chen on 2017/9/15. // // #ifndef ry_Util_hpp #define ry_Util_hpp #include "cocos2d.h" USING_NS_CC; int register_all_RyUtil(); class ryUtil { public: static ryUtil* getIns(); std::string getSign1(const char* userid, const char* key, const char* time); std::string getUnixTime(); void trimSpace(std::string *s); }; #endif /* ry_Util_hpp */
[ "81663573@qq.com" ]
81663573@qq.com
5fce89b2b1f962e5e648dd2d67c1ad80fd79da99
91078848badd7c00cbe92065e81b13b67a4908d0
/Vector.h
dd9ffbda3563a82121c05af0db30e09b5302b037
[]
no_license
sschepis/ArdUtils
ba6e254d9eb8a26c03de72e454c2a3a0f5aecb1b
700fc747eb21599e5a7f52bb935f624299f42001
refs/heads/master
2020-04-21T11:46:55.381051
2019-02-17T09:57:54
2019-02-17T09:57:54
169,538,467
0
0
null
null
null
null
UTF-8
C++
false
false
2,274
h
template<typename Data> class Vector { size_t d_size; // Stores no. of actually stored objects size_t d_capacity; // Stores allocated capacity Data *d_data; // Stores data public: Vector() : d_size(0), d_capacity(0), d_data(0) { d_data = NULL; resize(); }; Vector(Vector const &other) : d_size(other.d_size), d_capacity(other.d_capacity), d_data(0) { d_data = (Data *)malloc(d_capacity*sizeof(Data)); memcpy(d_data, other.d_data, d_size*sizeof(Data)); }; // Copy constuctor ~Vector() { if(d_data != NULL) free(d_data); }; // Destructor Vector &operator=(Vector const &other) { if(d_data != NULL) free(d_data); d_size = other.d_size; d_capacity = other.d_capacity; d_data = (Data *)malloc(d_capacity*sizeof(Data)); memcpy(d_data, other.d_data, d_size*sizeof(Data)); return *this; }; void push_back(Data const &x) { if (d_capacity == d_size) resize(); d_data[d_size++] = x; }; // Adds new value. If needed, allocates more space size_t size() const { return d_size; }; // Size getter Data dummyData; Data &front() { return d_data != NULL ? d_data[0] : dummyData; }; Data &back() { return d_data != NULL ? d_data[d_size - 1] : dummyData; }; boolean remove(size_t idx) { if(d_data == NULL || idx >= d_size || d_size == 0) return false; if(idx == d_size - 1) { d_data[idx] = NULL; } else { for(int i = idx; i < d_size - 1; i++) { d_data[i] = d_data[i+1]; } d_data[d_size - 1] = NULL; } d_size--; return true; }; Data const &operator[](size_t idx) const { return d_data == NULL || d_size <= idx ? dummyData : d_data[idx]; }; // Const getter Data &operator[](size_t idx) { return d_data == NULL || d_size <= idx ? dummyData : d_data[idx]; }; private: void resize() { d_capacity = d_capacity ? d_capacity * 2 : 10; Data *newdata = (Data *)malloc(d_capacity*sizeof(Data)); if(d_data != NULL) { memcpy(newdata, d_data, d_size * sizeof(Data)); free(d_data); } d_data = newdata; }; };
[ "sschepis@blockchainfoundry.co" ]
sschepis@blockchainfoundry.co
1bf32c7283123900c56a6f941d6f1b9fd01a532a
cfa14e948602283e8e7dd1b033c9bac79cfcf64f
/q4.cpp
df248cb79be3fb2978425872fb7818cce5a0a502
[]
no_license
PPL-IIITA/ppl-assignment-manasi-mds
aa15679287ed57e6936fd0b32fa0ec05eb238fe0
169a9c0fead568e547548780a561013669738d25
refs/heads/master
2021-01-21T06:27:01.565794
2017-04-09T21:46:11
2017-04-09T21:46:11
83,233,886
0
0
null
null
null
null
UTF-8
C++
false
false
549
cpp
#include<iostream> #include<stdio.h> #include<stdlib.h> #include<string.h> #include "couple.h" using namespace std; void readfile(gift **g,couple c[]); int breakup(gift **g, couple c[], couple br[],int m); void re_pair(gift **g,couple c[],couple br[],int m,int brindex); int main() { FILE *fc; gift **g; int m; fc = fopen("coupledetailsq2.txt","r"); fscanf(fc,"%d",&m); g = (gift **)malloc(m*sizeof(gift *)); couple c[m],br[m]; int j; readfile(g,c); int brindex = breakup(g,c,br,m); re_pair(g,c,br,m,brindex); return 0; }
[ "manasi.mds@gmail.com" ]
manasi.mds@gmail.com
325297d1a5ba4dcbe7e52881cf360201ef092622
184bcf7925e6718b3021946581576f8cae80526b
/CF/zDiv2/1082/B.cpp
ea2a4e52bd5a957c7a7f62fe10756b75fbdd9621
[]
no_license
iPhreetom/ACM
a99be74de61df37c427ffb685b375febad74ed9a
f3e639172be326846fe1f70437dcf98c90241aa0
refs/heads/master
2021-06-14T08:11:24.003465
2019-09-13T22:54:34
2019-09-13T22:54:34
142,748,718
0
0
null
null
null
null
UTF-8
C++
false
false
1,144
cpp
// fyt #include<bits/stdc++.h> #define int long long #define double long double #define endl '\n' using namespace std; int a[212345][3]; signed main(){ ios::sync_with_stdio(false),cin.tie(0),cout.tie(0); int n; string s; cin>>n; cin>>s; int cnt = 0; int mx = 0; int num = 0; int l = -1; int r = 0; int index = 0; for (int i=0; i<n; i++){ if(s[i] == 'G'){ if(l == -1){ l = i; } cnt++; } else{ if(cnt != 0){ r = i-1; int len = r-l+1; a[++index][0] = l; a[index][1] = r; a[index][2] = len; l = -1; mx = max(cnt,mx); num++; cnt = 0; } } if(i == n-1 && s[i] == 'G'){ r = i; int len = r-l+1; a[++index][0] = l; a[index][1] = r; a[index][2] = len; mx = max(mx,cnt); num++; cnt = 0; } } if(num <= 1){ cout<<mx<<endl; } else{ for(int i=2; i<=index; i++){ if(a[i][0] == a[i-1][1]+2){ if(num >= 3){ mx = max(mx,a[i][2] + a[i-1][2] + 1); } else{ mx = max(mx,a[i][2] + a[i-1][2]); } } else{ if(num >= 2){ mx = max(mx,max(a[i][2],a[i-1][2])+1); } } } cout<<mx<<endl; } return 0; }
[ "iPhreetom@gmail.com" ]
iPhreetom@gmail.com
bfe7c8edc983c336ef13bd1361bd1c7f514b7c8e
d29e0771d4de64c4cb3f7fc869d6a89d10bef14c
/cbi/cbi.ino
c3e2f876caef2d395d969d58bdd634263cedfc53
[ "MIT" ]
permissive
nad2000/Arduino-with-C-and-ASM
ff94d8e4b884431b7c27094316dfb752775ba63e
eaa547bcb8721c2b5357587eade791e860cd05d4
refs/heads/master
2020-04-25T13:53:30.079126
2019-02-28T04:35:39
2019-02-28T04:35:39
172,822,820
0
0
null
null
null
null
UTF-8
C++
false
false
506
ino
void setup() { Serial.begin(9600); asm("sbi 0x04, 5"); // seting PIN for output asm("rjmp START"); } void loop() { static int count=0; asm("sbi 0x05, 5"); // set bit immediately delay(100); asm("cbi 0x05, 5"); // clear bit immediatedly delay(100); asm("rjmp SKIP"); asm("START:"); asm("sbi 0x05, 5"); Serial.println("The LED on pin 13 should be on"); asm("SKIP:"); // skip START if (count>80) { count = 0; Serial.println("."); } Serial.print("."); count++; }
[ "nad2000@gmail.com" ]
nad2000@gmail.com
ccf35774a5f7c9ede63991c7db42c4e486ccd7d1
1c444bdf16632d78a3801a7fe6b35c054c4cddde
/include/bds/unmapped/BiomeRegistry.h
744d988710a5283531d7a98698e471b593e89b65
[]
no_license
maksym-pasichnyk/symbols
962a082bf6a692563402c87eb25e268e7e712c25
7673aa52391ce93540f0e65081f16cd11c2aa606
refs/heads/master
2022-04-11T03:17:18.078103
2020-03-15T11:30:36
2020-03-15T11:30:36
null
0
0
null
null
null
null
UTF-8
C++
false
false
3,213
h
#pragma once #include "IEntityRegistryOwner.h" #include <string> #include <functional> #include <memory> class BiomeRegistry : public IEntityRegistryOwner { public: class BiomeParent; virtual void getEntityRegistry(); // _ZN13BiomeRegistry17getEntityRegistryEv ~BiomeRegistry(); // _ZN13BiomeRegistryD2Ev void setLoadFromPacks(bool); // _ZN13BiomeRegistry16setLoadFromPacksEb BiomeRegistry(); // _ZN13BiomeRegistryC2Ev void _initTagRegistry(); // _ZN13BiomeRegistry16_initTagRegistryEv void getTagRegistry(); // _ZN13BiomeRegistry14getTagRegistryEv void getTagRegistry()const; // _ZNK13BiomeRegistry14getTagRegistryEv void registerBiome(std::string const&); // _ZN13BiomeRegistry13registerBiomeERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE void _allocateBiomeId(std::string const&); // _ZN13BiomeRegistry16_allocateBiomeIdERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE void _register(std::unique_ptr<Biome> &&); // _ZN13BiomeRegistry9_registerEOSt10unique_ptrI5BiomeSt14default_deleteIS1_EE void forEachBiome(std::function<void (Biome &)>)const; // _ZNK13BiomeRegistry12forEachBiomeESt8functionIFvR5BiomeEE void lookupById(int)const; // _ZNK13BiomeRegistry10lookupByIdEi void lookupByName(std::string const&)const; // _ZNK13BiomeRegistry12lookupByNameERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE void initServerFromPacks(ResourcePackManager &, IWorldRegistriesProvider &); // _ZN13BiomeRegistry19initServerFromPacksER19ResourcePackManagerR24IWorldRegistriesProvider void _buildInheritanceTree(ResourcePackManager &); // _ZN13BiomeRegistry21_buildInheritanceTreeER19ResourcePackManager // void _initServerFromInheritanceTree(InheritanceTree<BiomeRegistry::BiomeParent> &, IWorldRegistriesProvider &); //TODO: incomplete function definition // _ZN13BiomeRegistry30_initServerFromInheritanceTreeER15InheritanceTreeINS_11BiomeParentEER24IWorldRegistriesProvider void initClientFromPacks(ResourcePackManager &); // _ZN13BiomeRegistry19initClientFromPacksER19ResourcePackManager void registrationFinished(); // _ZN13BiomeRegistry20registrationFinishedEv // void _loadSingleBiome(ResourcePackManager &, InheritanceTree<BiomeRegistry::BiomeParent> &, std::string const&); //TODO: incomplete function definition // _ZN13BiomeRegistry16_loadSingleBiomeER19ResourcePackManagerR15InheritanceTreeINS_11BiomeParentEERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEE // void _mergeDataInheritance(Json::Value &, InheritanceTree<BiomeRegistry::BiomeParent> &, BiomeRegistry::BiomeParent const&); //TODO: incomplete function definition // _ZN13BiomeRegistry21_mergeDataInheritanceERN4Json5ValueER15InheritanceTreeINS_11BiomeParentEERKS4_ // void _addToInheritanceTree(InheritanceTree<BiomeRegistry::BiomeParent> &, std::string const&, Json::Value &&); //TODO: incomplete function definition // _ZN13BiomeRegistry21_addToInheritanceTreeER15InheritanceTreeINS_11BiomeParentEERKNSt7__cxx1112basic_stringIcSt11char_traitsIcESaIcEEEON4Json5ValueE class BiomeParent { public: ~BiomeParent(); // _ZN13BiomeRegistry11BiomeParentD2Ev BiomeParent(); // _ZN13BiomeRegistry11BiomeParentC2Ev }; };
[ "honzaxp01@gmail.com" ]
honzaxp01@gmail.com
0a69d259f798de3fbb061f55fe4e23c24754e931
777a75e6ed0934c193aece9de4421f8d8db01aac
/src/Providers/UNIXProviders/VLANFor/UNIX_VLANFor_HPUX.hxx
69332aab9eac5732120316857e74957a230094bc
[ "MIT" ]
permissive
brunolauze/openpegasus-providers-old
20fc13958016e35dc4d87f93d1999db0eae9010a
b00f1aad575bae144b8538bf57ba5fd5582a4ec7
refs/heads/master
2021-01-01T20:05:44.559362
2014-04-30T17:50:06
2014-04-30T17:50:06
19,132,738
1
0
null
null
null
null
UTF-8
C++
false
false
109
hxx
#ifdef PEGASUS_OS_HPUX #ifndef __UNIX_VLANFOR_PRIVATE_H #define __UNIX_VLANFOR_PRIVATE_H #endif #endif
[ "brunolauze@msn.com" ]
brunolauze@msn.com
971738345c9dd88c1543a994f186b15a71a76828
4e179ff01fafa327786c8096a4ff1e1492ccdaaf
/Engine/Graphics.h
6ee911f4bd03f3d97edd93242fb00dde9b286f56
[]
no_license
Aescosaurus/Jump-Framework
ed680ec57ef04c6831ac423322877eb65fc1adef
859f2460301c25f2fe3f5c789678b7cee429282a
refs/heads/master
2020-03-14T08:21:20.556961
2018-05-13T06:31:39
2018-05-13T06:31:39
null
0
0
null
null
null
null
UTF-8
C++
false
false
6,779
h
/****************************************************************************************** * Chili DirectX Framework Version 16.07.20 * * Graphics.h * * Copyright 2016 PlanetChili <http://www.planetchili.net> * * * * This file is part of The Chili DirectX Framework. * * * * The Chili DirectX Framework is free software: you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation, either version 3 of the License, or * * (at your option) any later version. * * * * The Chili DirectX 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 General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with The Chili DirectX Framework. If not, see <http://www.gnu.org/licenses/>. * ******************************************************************************************/ #pragma once #include "ChiliWin.h" #include <d3d11.h> #include <wrl.h> #include "ChiliException.h" #include "Colors.h" #include "Surface.h" #include "Rect.h" #include <cassert> class Graphics { public: class Exception : public ChiliException { public: Exception( HRESULT hr,const std::wstring& note,const wchar_t* file,unsigned int line ); std::wstring GetErrorName() const; std::wstring GetErrorDescription() const; virtual std::wstring GetFullMessage() const override; virtual std::wstring GetExceptionType() const override; private: HRESULT hr; }; private: // vertex format for the framebuffer fullscreen textured quad struct FSQVertex { float x,y,z; // position float u,v; // texcoords }; public: Graphics( class HWNDKey& key ); Graphics( const Graphics& ) = delete; Graphics& operator=( const Graphics& ) = delete; void EndFrame(); void BeginFrame(); void PutPixel( int x,int y,int r,int g,int b ) { PutPixel( x,y,{ unsigned char( r ),unsigned char( g ),unsigned char( b ) } ); } Color& GetPixel( int x,int y ) const; void PutPixel( int x,int y,Color c ); void PutPixel( int x,int y,Color c,unsigned char alpha ); void PutPixel( int x,int y,Color c,float alpha ); void DrawRect( int x,int y,int width,int height,Color c ); void DrawRectDim( int x1,int y1,int x2,int y2,Color c ); void DrawCircle( int x,int y,int radius,Color c ); void DrawLine( int x0,int y0,int x1,int y1,Color c ); template<typename R> void DrawHitbox( const Rect_<R>& hitbox,Color c = { 255,160,0 } ) { DrawLine( int( hitbox.left ),int( hitbox.top ), int( hitbox.right ),int( hitbox.top ),c ); DrawLine( int( hitbox.right ),int( hitbox.top ), int( hitbox.right ),int( hitbox.bottom ),c ); DrawLine( int( hitbox.right ),int( hitbox.bottom ), int( hitbox.left ),int( hitbox.bottom ),c ); DrawLine( int( hitbox.left ),int( hitbox.bottom ), int( hitbox.left ),int( hitbox.top ),c ); } template<typename E> void DrawSprite( int x,int y,const Surface& s,E effect,bool reversed = false ) { DrawSprite( x,y,s.GetRect(),s,effect,reversed ); } template<typename E> void DrawSprite( int x,int y,const RectI& srcRect,const Surface& s,E effect,bool reversed = false ) { DrawSprite( x,y,srcRect,GetScreenRect(),s,effect,reversed ); } template<typename E> void DrawSprite( int x,int y,RectI srcRect,const RectI& clip,const Surface& s,E effect,bool reversed = false ) { assert( srcRect.left >= 0 ); assert( srcRect.right <= s.GetWidth() ); assert( srcRect.top >= 0 ); assert( srcRect.bottom <= s.GetHeight() ); // Mirror in x depending on reversed bool switch. if( !reversed ) { // Clipping is different depending on mirroring status. if( x < clip.left ) { srcRect.left += clip.left - x; x = clip.left; } if( y < clip.top ) { srcRect.top += clip.top - y; y = clip.top; } if( x + srcRect.GetWidth() > clip.right ) { srcRect.right -= x + srcRect.GetWidth() - clip.right; } if( y + srcRect.GetHeight() > clip.bottom ) { srcRect.bottom -= y + srcRect.GetHeight() - clip.bottom; } for( int sy = srcRect.top; sy < srcRect.bottom; sy++ ) { for( int sx = srcRect.left; sx < srcRect.right; sx++ ) { effect( // No mirroring! s.GetPixel( sx,sy ), x + sx - srcRect.left, y + sy - srcRect.top, *this ); } } } else { if( x < clip.left ) { srcRect.right -= clip.left - x; x = clip.left; } if( y < clip.top ) { srcRect.top += clip.top - y; y = clip.top; } if( x + srcRect.GetWidth() > clip.right ) { srcRect.left += x + srcRect.GetWidth() - clip.right; } if( y + srcRect.GetHeight() > clip.bottom ) { srcRect.bottom -= y + srcRect.GetHeight() - clip.bottom; } const int xOffset = srcRect.left + srcRect.right - 1; for( int sy = srcRect.top; sy < srcRect.bottom; sy++ ) { for( int sx = srcRect.left; sx < srcRect.right; sx++ ) { effect( // Mirror in x. s.GetPixel( xOffset - sx,sy ), x + sx - srcRect.left, y + sy - srcRect.top, *this ); } } } } void JSDrawImage( const Surface& image,int dx,int dy ) { JSDrawImage( image,dx,dy,image.GetWidth(),image.GetHeight() ); } void JSDrawImage( const Surface& image,int dx,int dy,int dWidth,int dHeight ) { JSDrawImage( image,dx,dy,dWidth,dHeight, dx,dy,dWidth,dHeight ); } void JSDrawImage( const Surface& image,int sx,int sy,int sWidth,int sHeight,int dx,int dy,int dWidth,int dHeight ); ~Graphics(); private: Microsoft::WRL::ComPtr<IDXGISwapChain> pSwapChain; Microsoft::WRL::ComPtr<ID3D11Device> pDevice; Microsoft::WRL::ComPtr<ID3D11DeviceContext> pImmediateContext; Microsoft::WRL::ComPtr<ID3D11RenderTargetView> pRenderTargetView; Microsoft::WRL::ComPtr<ID3D11Texture2D> pSysBufferTexture; Microsoft::WRL::ComPtr<ID3D11ShaderResourceView> pSysBufferTextureView; Microsoft::WRL::ComPtr<ID3D11PixelShader> pPixelShader; Microsoft::WRL::ComPtr<ID3D11VertexShader> pVertexShader; Microsoft::WRL::ComPtr<ID3D11Buffer> pVertexBuffer; Microsoft::WRL::ComPtr<ID3D11InputLayout> pInputLayout; Microsoft::WRL::ComPtr<ID3D11SamplerState> pSamplerState; D3D11_MAPPED_SUBRESOURCE mappedSysBufferTexture; Color* pSysBuffer = nullptr; public: static constexpr int ScreenWidth = 64 * 16; static constexpr int ScreenHeight = 64 * 12; static RectI GetScreenRect(); };
[ "michaelbuslik@hotmail.com" ]
michaelbuslik@hotmail.com
da5b6a58575d7ca5379d1bdcade5024cbc9275d6
005cb1c69358d301f72c6a6890ffeb430573c1a1
/Pods/Headers/Private/GeoFeatures/boost/preprocessor/repetition/enum.hpp
f75690686eb9f20a32a1b3109f0ee8b89f89f304
[ "Apache-2.0" ]
permissive
TheClimateCorporation/DemoCLUs
05588dcca687cc5854755fad72f07759f81fe673
f343da9b41807694055151a721b497cf6267f829
refs/heads/master
2021-01-10T15:10:06.021498
2016-04-19T20:31:34
2016-04-19T20:31:34
51,960,444
0
0
null
null
null
null
UTF-8
C++
false
false
80
hpp
../../../../../../GeoFeatures/GeoFeatures/boost/preprocessor/repetition/enum.hpp
[ "tommy.rogers@climate.com" ]
tommy.rogers@climate.com
3776bcf3a2ab0620551257000e30861cc441c5d1
cfeac52f970e8901871bd02d9acb7de66b9fb6b4
/generated/src/aws-cpp-sdk-ram/source/model/SetDefaultPermissionVersionRequest.cpp
9faa75c5c783b80f7df5d23779b3b5cce66503e0
[ "Apache-2.0", "MIT", "JSON" ]
permissive
aws/aws-sdk-cpp
aff116ddf9ca2b41e45c47dba1c2b7754935c585
9a7606a6c98e13c759032c2e920c7c64a6a35264
refs/heads/main
2023-08-25T11:16:55.982089
2023-08-24T18:14:53
2023-08-24T18:14:53
35,440,404
1,681
1,133
Apache-2.0
2023-09-12T15:59:33
2015-05-11T17:57:32
null
UTF-8
C++
false
false
1,021
cpp
/** * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * SPDX-License-Identifier: Apache-2.0. */ #include <aws/ram/model/SetDefaultPermissionVersionRequest.h> #include <aws/core/utils/json/JsonSerializer.h> #include <utility> using namespace Aws::RAM::Model; using namespace Aws::Utils::Json; using namespace Aws::Utils; SetDefaultPermissionVersionRequest::SetDefaultPermissionVersionRequest() : m_permissionArnHasBeenSet(false), m_permissionVersion(0), m_permissionVersionHasBeenSet(false), m_clientTokenHasBeenSet(false) { } Aws::String SetDefaultPermissionVersionRequest::SerializePayload() const { JsonValue payload; if(m_permissionArnHasBeenSet) { payload.WithString("permissionArn", m_permissionArn); } if(m_permissionVersionHasBeenSet) { payload.WithInteger("permissionVersion", m_permissionVersion); } if(m_clientTokenHasBeenSet) { payload.WithString("clientToken", m_clientToken); } return payload.View().WriteReadable(); }
[ "github-aws-sdk-cpp-automation@amazon.com" ]
github-aws-sdk-cpp-automation@amazon.com
b5bee412f6a49aaf467409e881fe9cdcc01240b7
6b40e9dccf2edc767c44df3acd9b626fcd586b4d
/NT/com/rpc/midl/codegen/cgvisitor.hxx
4651dbb151ac9cdb80b0ed6215af43807dc0603a
[]
no_license
jjzhang166/WinNT5_src_20201004
712894fcf94fb82c49e5cd09d719da00740e0436
b2db264153b80fbb91ef5fc9f57b387e223dbfc2
refs/heads/Win2K3
2023-08-12T01:31:59.670176
2021-10-14T15:14:37
2021-10-14T15:14:37
586,134,273
1
0
null
2023-01-07T03:47:45
2023-01-07T03:47:44
null
UTF-8
C++
false
false
20,624
hxx
/*+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ Copyright (c) 1999-1999 Microsoft Corporation Module Name: cgvisitor.hxx Abstract: classes and templates for visitors Notes: History: mzoran Nov-24-1999 Created. ----------------------------------------------------------------------------*/ class CG_ARRAY; class CG_ASYNC_HANDLE; class CG_AUX; class CG_BASETYPE; class CG_BYTE_COUNT_POINTER; class CG_CALLBACK_PROC; class CG_CASE; class CG_CLASS; class CG_COCLASS; class CG_COMP; class CG_COMPLEX_STRUCT; class CG_CONFORMANT_ARRAY; class CG_CONFORMANT_STRING_ARRAY; class CG_CONFORMANT_STRUCT; class CG_CONFORMANT_VARYING_ARRAY; class CG_CONFORMANT_VARYING_STRUCT; class CG_CONTEXT_HANDLE; class CG_CS_TAG; class CG_CSTUB_FILE; class CG_DEFAULT_CASE; class CG_DISPINTERFACE; class CG_ENCAPSULATED_STRUCT; class CG_ENCODE_PROC; class CG_ENUM; class CG_ERROR_STATUS_T; class CG_FIELD; class CG_FILE; class CG_FIXED_ARRAY; class CG_GENERIC_HANDLE; class CG_HDR_FILE; class CG_HRESULT; class CG_ID; class CG_IGNORED_POINTER; class CG_IID_FILE; class CG_IIDIS_INTERFACE_POINTER; class CG_INHERITED_OBJECT_INTERFACE; class CG_INHERITED_OBJECT_PROC; class CG_INT3264; class CG_INTERFACE; class CG_INTERFACE_POINTER; class CG_INTERFACE_REFERENCE; class CG_IUNKNOWN_OBJECT_INTERFACE; class CG_IUNKNOWN_OBJECT_PROC; class CG_LENGTH_POINTER; class CG_LIBRARY; class CG_LOCAL_OBJECT_PROC; class CG_MODULE; class CG_NETMONSTUB_FILE; class CG_OBJECT_INTERFACE; class CG_OBJECT_PROC; class CG_PARAM; class CG_PIPE; class CG_POINTER; class CG_PRIMITIVE_HANDLE; class CG_PROC; class CG_PROXY_FILE; class CG_QUALIFIED_POINTER; class CG_REPRESENT_AS; class CG_RETURN; class CG_SAFEARRAY; class CG_SIZE_LENGTH_POINTER; class CG_SIZE_POINTER; class CG_SIZE_STRING_POINTER; class CG_SOURCE; class CG_SSTUB_FILE; class CG_STRING_ARRAY; class CG_STRING_POINTER; class CG_STRUCT; class CG_TRANSMIT_AS; class CG_TYPE_ENCODE; class CG_TYPE_ENCODE_PROC; class CG_TYPEDEF; class CG_TYPELIBRARY_FILE; class CG_UNION; class CG_UNION_FIELD; class CG_USER_MARSHAL; class CG_VARYING_ARRAY; // // New 64b NDR types // // // New Class for 64bit NDR // // structures class CG_FULL_COMPLEX_STRUCT; class CG_FORCED_COMPLEX_STRUCT; class CG_CONFORMANT_FULL_COMPLEX_STRUCT; class CG_CONFORMANT_FORCED_COMPLEX_STRUCT; class CG_REGION; class CG_SIMPLE_REGION; class CG_COMPLEX_REGION; // arrays class CG_COMPLEX_FIXED_ARRAY; class CG_FORCED_COMPLEX_FIXED_ARRAY; class CG_FULL_COMPLEX_FIXED_ARRAY; class CG_COMPLEX_CONFORMANT_ARRAY; class CG_FORCED_COMPLEX_CONFORMANT_ARRAY; class CG_FULL_COMPLEX_CONFORMANT_ARRAY; class CG_COMPLEX_VARYING_ARRAY; class CG_FORCED_COMPLEX_VARYING_ARRAY; class CG_FULL_COMPLEX_VARYING_ARRAY; class CG_COMPLEX_CONFORMANT_VARYING_ARRAY; class CG_FORCED_COMPLEX_CONFORMANT_VARYING_ARRAY; class CG_FULL_COMPLEX_CONFORMANT_VARYING_ARRAY; // qualified pointers class CG_COMPLEX_SIZE_POINTER; class CG_FORCED_COMPLEX_SIZE_POINTER; class CG_FULL_COMPLEX_SIZE_POINTER; class CG_COMPLEX_LENGTH_POINTER; class CG_FORCED_COMPLEX_LENGTH_POINTER; class CG_FULL_COMPLEX_LENGTH_POINTER; class CG_COMPLEX_SIZE_LENGTH_POINTER; class CG_FORCED_COMPLEX_SIZE_LENGTH_POINTER; class CG_FULL_COMPLEX_SIZE_LENGTH_POINTER; class CG_PAD; class CG_VISITOR { public: virtual void Visit( CG_ARRAY *pClass ) = 0; virtual void Visit( CG_ASYNC_HANDLE *pClass ) = 0; virtual void Visit( CG_AUX *pClass ) = 0; virtual void Visit( CG_BASETYPE *pClass ) = 0; virtual void Visit( CG_BYTE_COUNT_POINTER *pClass ) = 0; virtual void Visit( CG_CALLBACK_PROC *pClass ) = 0; virtual void Visit( CG_CASE *pClass ) = 0; virtual void Visit( CG_CLASS *pClass ) = 0; virtual void Visit( CG_COCLASS *pClass ) = 0; virtual void Visit( CG_COMP *pClass ) = 0; virtual void Visit( CG_COMPLEX_STRUCT *pClass ) = 0; virtual void Visit( CG_CONFORMANT_ARRAY *pClass ) = 0; virtual void Visit( CG_CONFORMANT_STRING_ARRAY *pClass ) = 0; virtual void Visit( CG_CONFORMANT_STRUCT *pClass ) = 0; virtual void Visit( CG_CONFORMANT_VARYING_ARRAY *pClass ) = 0; virtual void Visit( CG_CONFORMANT_VARYING_STRUCT *pClass ) = 0; virtual void Visit( CG_CONTEXT_HANDLE *pClass ) = 0; virtual void Visit( CG_CS_TAG *pClass ) = 0; virtual void Visit( CG_CSTUB_FILE *pClass ) = 0; virtual void Visit( CG_DEFAULT_CASE *pClass ) = 0; virtual void Visit( CG_DISPINTERFACE *pClass ) = 0; virtual void Visit( CG_ENCAPSULATED_STRUCT *pClass ) = 0; virtual void Visit( CG_ENCODE_PROC *pClass ) = 0; virtual void Visit( CG_ENUM *pClass ) = 0; virtual void Visit( CG_ERROR_STATUS_T *pClass ) = 0; virtual void Visit( CG_FIELD *pClass ) = 0; virtual void Visit( CG_FILE *pClass ) = 0; virtual void Visit( CG_FIXED_ARRAY *pClass ) = 0; virtual void Visit( CG_GENERIC_HANDLE *pClass ) = 0; virtual void Visit( CG_HDR_FILE *pClass ) = 0; virtual void Visit( CG_HRESULT *pClass ) = 0; virtual void Visit( CG_ID *pClass ) = 0; virtual void Visit( CG_IGNORED_POINTER *pClass ) = 0; virtual void Visit( CG_IID_FILE *pClass ) = 0; virtual void Visit( CG_IIDIS_INTERFACE_POINTER *pClass ) = 0; virtual void Visit( CG_INHERITED_OBJECT_INTERFACE *pClass ) = 0; virtual void Visit( CG_INHERITED_OBJECT_PROC *pClass ) = 0; virtual void Visit( CG_INT3264 *pClass ) = 0; virtual void Visit( CG_INTERFACE *pClass ) = 0; virtual void Visit( CG_INTERFACE_POINTER *pClass ) = 0; virtual void Visit( CG_INTERFACE_REFERENCE *pClass ) = 0; virtual void Visit( CG_IUNKNOWN_OBJECT_INTERFACE *pClass ) = 0; virtual void Visit( CG_IUNKNOWN_OBJECT_PROC *pClass ) = 0; virtual void Visit( CG_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_LIBRARY *pClass ) = 0; virtual void Visit( CG_LOCAL_OBJECT_PROC *pClass ) = 0; virtual void Visit( CG_MODULE *pClass ) = 0; virtual void Visit( CG_NETMONSTUB_FILE *pClass ) = 0; virtual void Visit( CG_OBJECT_INTERFACE *pClass ) = 0; virtual void Visit( CG_OBJECT_PROC *pClass ) = 0; virtual void Visit( CG_PARAM *pClass ) = 0; virtual void Visit( CG_PIPE *pClass ) = 0; virtual void Visit( CG_POINTER *pClass ) = 0; virtual void Visit( CG_PRIMITIVE_HANDLE *pClass ) = 0; virtual void Visit( CG_PROC *pClass ) = 0; virtual void Visit( CG_PROXY_FILE *pClass ) = 0; virtual void Visit( CG_QUALIFIED_POINTER *pClass ) = 0; virtual void Visit( CG_REPRESENT_AS *pClass ) = 0; virtual void Visit( CG_RETURN *pClass ) = 0; virtual void Visit( CG_SAFEARRAY *pClass ) = 0; virtual void Visit( CG_SIZE_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_SIZE_POINTER *pClass ) = 0; virtual void Visit( CG_SIZE_STRING_POINTER *pClass ) = 0; virtual void Visit( CG_SOURCE *pClass ) = 0; virtual void Visit( CG_SSTUB_FILE *pClass ) = 0; virtual void Visit( CG_STRING_ARRAY *pClass ) = 0; virtual void Visit( CG_STRING_POINTER *pClass ) = 0; virtual void Visit( CG_STRUCT *pClass ) = 0; virtual void Visit( CG_TRANSMIT_AS *pClass ) = 0; virtual void Visit( CG_TYPE_ENCODE *pClass ) = 0; virtual void Visit( CG_TYPE_ENCODE_PROC *pClass ) = 0; virtual void Visit( CG_TYPEDEF *pClass ) = 0; virtual void Visit( CG_TYPELIBRARY_FILE *pClass ) = 0; virtual void Visit( CG_UNION *pClass ) = 0; virtual void Visit( CG_UNION_FIELD *pClass ) = 0; virtual void Visit( CG_USER_MARSHAL *pClass ) = 0; virtual void Visit( CG_VARYING_ARRAY *pClass ) = 0; // New Class for 64bit NDR // structures virtual void Visit( CG_FULL_COMPLEX_STRUCT *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_STRUCT *pClass ) = 0; virtual void Visit( CG_CONFORMANT_FULL_COMPLEX_STRUCT *pClass ) = 0; virtual void Visit( CG_CONFORMANT_FORCED_COMPLEX_STRUCT *pClass ) = 0; virtual void Visit( CG_REGION *pClass ) = 0; virtual void Visit( CG_SIMPLE_REGION *pClass ) = 0; virtual void Visit( CG_COMPLEX_REGION *pClass ) = 0; // arrays virtual void Visit( CG_COMPLEX_FIXED_ARRAY *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_FIXED_ARRAY *pClass ) = 0; virtual void Visit( CG_FULL_COMPLEX_FIXED_ARRAY *pClass ) = 0; virtual void Visit( CG_COMPLEX_CONFORMANT_ARRAY *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_CONFORMANT_ARRAY *pClass ) = 0; virtual void Visit( CG_FULL_COMPLEX_CONFORMANT_ARRAY *pClass ) = 0; virtual void Visit( CG_COMPLEX_VARYING_ARRAY *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_VARYING_ARRAY *pClass ) = 0; virtual void Visit( CG_FULL_COMPLEX_VARYING_ARRAY *pClass ) = 0; virtual void Visit( CG_COMPLEX_CONFORMANT_VARYING_ARRAY *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_CONFORMANT_VARYING_ARRAY *pClass ) = 0; virtual void Visit( CG_FULL_COMPLEX_CONFORMANT_VARYING_ARRAY *pClass ) = 0; // qualified pointers virtual void Visit( CG_COMPLEX_SIZE_POINTER *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_SIZE_POINTER *pClass ) = 0; virtual void Visit( CG_FULL_COMPLEX_SIZE_POINTER *pClass ) = 0; virtual void Visit( CG_COMPLEX_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_FULL_COMPLEX_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_COMPLEX_SIZE_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_FORCED_COMPLEX_SIZE_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_FULL_COMPLEX_SIZE_LENGTH_POINTER *pClass ) = 0; virtual void Visit( CG_PAD *pClass ) = 0; }; template<class T> class CG_VISITOR_TEMPLATE : public CG_VISITOR, public T { public: CG_VISITOR_TEMPLATE() : T() {} CG_VISITOR_TEMPLATE( const T & Node ) : T( Node ) {} operator=( const T & Node ) { *(( T *)this) = Node; } virtual void Visit( CG_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_ASYNC_HANDLE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_AUX *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_BASETYPE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_BYTE_COUNT_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CALLBACK_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CASE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CLASS *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COCLASS *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMP *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMPLEX_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONFORMANT_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONFORMANT_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONFORMANT_STRING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONFORMANT_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONFORMANT_VARYING_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONTEXT_HANDLE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CS_TAG *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CSTUB_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_DEFAULT_CASE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_DISPINTERFACE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_ENCAPSULATED_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_ENCODE_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_ENUM *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_ERROR_STATUS_T *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FIELD *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FIXED_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_GENERIC_HANDLE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_HDR_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_HRESULT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_ID *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_IGNORED_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_IID_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_IIDIS_INTERFACE_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_INHERITED_OBJECT_INTERFACE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_INHERITED_OBJECT_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_INT3264 *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_INTERFACE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_INTERFACE_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_INTERFACE_REFERENCE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_IUNKNOWN_OBJECT_INTERFACE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_IUNKNOWN_OBJECT_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_LIBRARY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_LOCAL_OBJECT_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_MODULE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_NETMONSTUB_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_OBJECT_INTERFACE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_OBJECT_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_PARAM *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_PIPE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_PRIMITIVE_HANDLE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_PROXY_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_QUALIFIED_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_REPRESENT_AS *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_RETURN *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_SAFEARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_SIZE_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_SIZE_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_SIZE_STRING_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_SOURCE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_SSTUB_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_STRING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_STRING_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_TRANSMIT_AS *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_TYPE_ENCODE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_TYPE_ENCODE_PROC *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_TYPEDEF *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_TYPELIBRARY_FILE *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_UNION *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_UNION_FIELD *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_USER_MARSHAL *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } // structures virtual void Visit( CG_FULL_COMPLEX_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONFORMANT_FULL_COMPLEX_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_CONFORMANT_FORCED_COMPLEX_STRUCT *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_REGION *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_SIMPLE_REGION *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMPLEX_REGION *pClass ) { T::Visit( pClass ); } // arrays virtual void Visit( CG_COMPLEX_FIXED_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_FIXED_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FULL_COMPLEX_FIXED_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMPLEX_CONFORMANT_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_CONFORMANT_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FULL_COMPLEX_CONFORMANT_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMPLEX_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FULL_COMPLEX_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMPLEX_CONFORMANT_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_CONFORMANT_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FULL_COMPLEX_CONFORMANT_VARYING_ARRAY *pClass ) { T::Visit( pClass ); } // qualified pointers virtual void Visit( CG_COMPLEX_SIZE_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_SIZE_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FULL_COMPLEX_SIZE_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMPLEX_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FULL_COMPLEX_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_COMPLEX_SIZE_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FORCED_COMPLEX_SIZE_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_FULL_COMPLEX_SIZE_LENGTH_POINTER *pClass ) { T::Visit( pClass ); } virtual void Visit( CG_PAD *pClass ) { T::Visit( pClass ); } };
[ "seta7D5@protonmail.com" ]
seta7D5@protonmail.com