1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
|
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// https://developers.google.com/protocol-buffers/
//
// 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.
// A hack to include windows.h first, which ensures the GetMessage macro can
// be undefined when we include <stubs/common.h>
#if defined(_MSC_VER)
#define _WINSOCKAPI_ // to avoid re-definition in WinSock2.h
#define NOMINMAX // to avoid defining min/max macros
#include <windows.h>
#endif // _WIN32
#include <algorithm>
#include <map>
#include <memory>
#include <random>
#include <set>
#include <sstream>
#include <unordered_map>
#include <unordered_set>
#include <vector>
#include <stubs/logging.h>
#include <stubs/common.h>
#include <stubs/stringprintf.h>
#include <testing/file.h>
#include <arena_test_util.h>
#include <test_util2.h>
#include <io/coded_stream.h>
#include <io/tokenizer.h>
#include <io/zero_copy_stream_impl.h>
#include <descriptor.pb.h>
#include <descriptor.h>
#include <descriptor_database.h>
#include <dynamic_message.h>
#include <map.h>
#include <map_field_inl.h>
#include <message.h>
#include <reflection.h>
#include <reflection_ops.h>
#include <text_format.h>
#include <wire_format.h>
#include <util/message_differencer.h>
#include <util/time_util.h>
#include <gmock/gmock.h>
#include <testing/googletest.h>
#include <gtest/gtest.h>
#include <stubs/casts.h>
#include <stubs/substitute.h>
// Must be included last.
#include <port_def.inc>
namespace google {
namespace protobuf {
using UNITTEST::ForeignMessage;
using UNITTEST::TestAllTypes;
using UNITTEST::TestMap;
using UNITTEST::TestRecursiveMapMessage;
namespace internal {
void MapTestForceDeterministic() {
io::CodedOutputStream::SetDefaultSerializationDeterministic();
}
namespace {
// Map API Test =====================================================
class MapImplTest : public ::testing::Test {
protected:
MapImplTest()
: map_ptr_(new Map<int32, int32>()),
map_(*map_ptr_),
const_map_(*map_ptr_) {
EXPECT_TRUE(map_.empty());
EXPECT_EQ(0, map_.size());
}
void ExpectSingleElement(int32 key, int32 value) {
EXPECT_FALSE(map_.empty());
EXPECT_EQ(1, map_.size());
ExpectElement(key, value);
}
void ExpectElements(const std::map<int32, int32>& map) {
EXPECT_FALSE(map_.empty());
EXPECT_EQ(map.size(), map_.size());
for (std::map<int32, int32>::const_iterator it = map.begin();
it != map.end(); ++it) {
ExpectElement(it->first, it->second);
}
}
void ExpectElement(int32 key, int32 value) {
// Test map size is correct.
EXPECT_EQ(value, map_[key]);
EXPECT_EQ(1, map_.count(key));
EXPECT_TRUE(map_.contains(key));
// Check mutable at and find work correctly.
EXPECT_EQ(value, map_.at(key));
Map<int32, int32>::iterator it = map_.find(key);
// iterator dereferenceable
EXPECT_EQ(key, (*it).first);
EXPECT_EQ(value, (*it).second);
EXPECT_EQ(key, it->first);
EXPECT_EQ(value, it->second);
// iterator mutable
((*it).second) = value + 1;
EXPECT_EQ(value + 1, map_[key]);
((*it).second) = value;
EXPECT_EQ(value, map_[key]);
it->second = value + 1;
EXPECT_EQ(value + 1, map_[key]);
it->second = value;
EXPECT_EQ(value, map_[key]);
// copy constructor
Map<int32, int32>::iterator it_copy = it;
EXPECT_EQ(key, it_copy->first);
EXPECT_EQ(value, it_copy->second);
// Immutable API ================================================
// Check immutable at and find work correctly.
EXPECT_EQ(value, const_map_.at(key));
Map<int32, int32>::const_iterator const_it = const_map_.find(key);
// iterator dereferenceable
EXPECT_EQ(key, (*const_it).first);
EXPECT_EQ(value, (*const_it).second);
EXPECT_EQ(key, const_it->first);
EXPECT_EQ(value, const_it->second);
// copy constructor
Map<int32, int32>::const_iterator const_it_copy = const_it;
EXPECT_EQ(key, const_it_copy->first);
EXPECT_EQ(value, const_it_copy->second);
}
std::unique_ptr<Map<int32, int32> > map_ptr_;
Map<int32, int32>& map_;
const Map<int32, int32>& const_map_;
};
TEST_F(MapImplTest, OperatorBracket) {
int32 key = 0;
int32 value1 = 100;
int32 value2 = 101;
EXPECT_EQ(0, map_[key]);
map_[key] = value1;
ExpectSingleElement(key, value1);
map_[key] = value2;
ExpectSingleElement(key, value2);
}
struct MoveTestKey {
MoveTestKey(int data, int* copies) : data(data), copies(copies) {}
MoveTestKey(const MoveTestKey& other)
: data(other.data), copies(other.copies) {
++*copies;
}
MoveTestKey(MoveTestKey&& other) noexcept
: data(other.data), copies(other.copies) {}
friend bool operator==(const MoveTestKey& lhs, const MoveTestKey& rhs) {
return lhs.data == rhs.data;
}
friend bool operator<(const MoveTestKey& lhs, const MoveTestKey& rhs) {
return lhs.data < rhs.data;
}
int data;
int* copies;
};
} // namespace
} // namespace internal
} // namespace protobuf
} // namespace google
namespace std {
template <> // NOLINT
struct hash<google::protobuf::internal::MoveTestKey> {
size_t operator()(const google::protobuf::internal::MoveTestKey& key) const {
return hash<int>{}(key.data);
}
};
} // namespace std
namespace google {
namespace protobuf {
namespace internal {
namespace {
TEST_F(MapImplTest, OperatorBracketRValue) {
Arena arena;
for (Arena* arena_to_use : {&arena, static_cast<Arena*>(nullptr)}) {
int copies = 0;
Map<MoveTestKey, int> map(arena_to_use);
MoveTestKey key1(1, &copies);
EXPECT_EQ(copies, 0);
map[key1] = 0;
EXPECT_EQ(copies, 1);
map[MoveTestKey(2, &copies)] = 2;
EXPECT_EQ(copies, 1);
}
}
TEST_F(MapImplTest, OperatorBracketNonExist) {
int32 key = 0;
int32 default_value = 0;
EXPECT_EQ(default_value, map_[key]);
ExpectSingleElement(key, default_value);
}
TEST_F(MapImplTest, MutableAt) {
int32 key = 0;
int32 value1 = 100;
int32 value2 = 101;
map_[key] = value1;
ExpectSingleElement(key, value1);
map_.at(key) = value2;
ExpectSingleElement(key, value2);
}
#ifdef PROTOBUF_HAS_DEATH_TEST
TEST_F(MapImplTest, MutableAtNonExistDeathTest) {
EXPECT_DEATH(map_.at(0), "");
}
TEST_F(MapImplTest, ImmutableAtNonExistDeathTest) {
EXPECT_DEATH(const_map_.at(0), "");
}
TEST_F(MapImplTest, UsageErrors) {
MapKey key;
key.SetInt64Value(1);
EXPECT_DEATH(key.GetUInt64Value(),
"Protocol Buffer map usage error:\n"
"MapKey::GetUInt64Value type does not match\n"
" Expected : uint64\n"
" Actual : int64");
MapValueRef value;
EXPECT_DEATH(
value.SetFloatValue(0.1),
"Protocol Buffer map usage error:\n"
"MapValue[Const]*Ref::type MapValue[Const]*Ref is not initialized.");
}
#endif // PROTOBUF_HAS_DEATH_TEST
TEST_F(MapImplTest, MapKeyAssignment) {
MapKey from, to;
from.SetStringValue("abc");
to = from;
EXPECT_EQ("abc", to.GetStringValue());
}
TEST_F(MapImplTest, CountNonExist) { EXPECT_EQ(0, map_.count(0)); }
TEST_F(MapImplTest, ContainNotExist) { EXPECT_FALSE(map_.contains(0)); }
TEST_F(MapImplTest, ImmutableContainNotExist) {
EXPECT_FALSE(const_map_.contains(0));
}
TEST_F(MapImplTest, MutableFindNonExist) {
EXPECT_TRUE(map_.end() == map_.find(0));
}
TEST_F(MapImplTest, ImmutableFindNonExist) {
EXPECT_TRUE(const_map_.end() == const_map_.find(0));
}
TEST_F(MapImplTest, ConstEnd) {
EXPECT_TRUE(const_map_.end() == const_map_.cend());
}
TEST_F(MapImplTest, GetReferenceFromIterator) {
for (int i = 0; i < 10; i++) {
map_[i] = i;
}
for (Map<int32, int32>::const_iterator it = map_.cbegin();
it != map_.cend();) {
Map<int32, int32>::const_reference entry = *it++;
EXPECT_EQ(entry.first, entry.second);
}
for (Map<int32, int32>::const_iterator it = const_map_.begin();
it != const_map_.end();) {
Map<int32, int32>::const_reference entry = *it++;
EXPECT_EQ(entry.first, entry.second);
}
for (Map<int32, int32>::iterator it = map_.begin(); it != map_.end();) {
Map<int32, int32>::reference entry = *it++;
EXPECT_EQ(entry.first + 1, ++entry.second);
}
}
TEST_F(MapImplTest, IteratorBasic) {
map_[0] = 0;
// Default constructible (per forward iterator requirements).
Map<int, int>::const_iterator cit;
Map<int, int>::iterator it;
it = map_.begin();
cit = it; // Converts to const_iterator
// Can compare between them.
EXPECT_TRUE(it == cit);
EXPECT_FALSE(cit != it);
// Pre increment.
EXPECT_FALSE(it == ++cit);
// Post increment.
EXPECT_FALSE(it++ == cit);
EXPECT_TRUE(it == cit);
}
template <typename Iterator>
static int64 median(Iterator i0, Iterator i1) {
std::vector<int64> v(i0, i1);
std::nth_element(v.begin(), v.begin() + v.size() / 2, v.end());
return v[v.size() / 2];
}
static int64 Now() {
return util::TimeUtil::TimestampToNanoseconds(
util::TimeUtil::GetCurrentTime());
}
// Arbitrary odd integers for creating test data.
static int k0 = 812398771;
static int k1 = 1312938717;
static int k2 = 1321555333;
// A naive begin() implementation will cause begin() to get slower and slower
// if one erases elements at the "front" of the hash map, and we'd like to
// avoid that, as std::unordered_map does.
TEST_F(MapImplTest, BeginIsFast) {
if (true) return; // TODO(gpike): make this less flaky and re-enable it.
Map<int32, int32> map;
const int kTestSize = 250000;
// Create a random-looking map of size n. Use non-negative integer keys.
uint32 frog = 123983;
int last_key = 0;
int counter = 0;
while (map.size() < kTestSize) {
frog *= static_cast<uint32>(k0);
frog ^= frog >> 17;
frog += counter++;
last_key =
static_cast<int>(frog) >= 0 ? static_cast<int>(frog) : last_key ^ 1;
GOOGLE_DCHECK_GE(last_key, 0);
map[last_key] = last_key ^ 1;
}
std::vector<int64> times;
// We're going to do map.erase(map.begin()) over and over again. But,
// just in case one iteration is fast compared to the granularity of
// our time keeping, we measure kChunkSize iterations per outer-loop iter.
const int kChunkSize = 1000;
GOOGLE_CHECK_EQ(kTestSize % kChunkSize, 0);
do {
const int64 start = Now();
for (int i = 0; i < kChunkSize; i++) {
map.erase(map.begin());
}
const int64 end = Now();
if (end > start) {
times.push_back(end - start);
}
} while (!map.empty());
if (times.size() < .99 * kTestSize / kChunkSize) {
GOOGLE_LOG(WARNING) << "Now() isn't helping us measure time";
return;
}
int64 x0 = median(times.begin(), times.begin() + 9);
int64 x1 = median(times.begin() + times.size() - 9, times.end());
GOOGLE_LOG(INFO) << "x0=" << x0 << ", x1=" << x1;
// x1 will greatly exceed x0 if the code we just executed took O(n^2) time.
// And we'll probably time out and never get here. So, this test is
// intentionally loose: we check that x0 and x1 are within a factor of 8.
EXPECT_GE(x1, x0 / 8);
EXPECT_GE(x0, x1 / 8);
}
// Try to create kTestSize keys that will land in just a few buckets, and
// time the insertions, to get a rough estimate of whether an O(n^2) worst case
// was triggered. This test is a hacky, but probably better than nothing.
TEST_F(MapImplTest, HashFlood) {
const int kTestSize = 1024; // must be a power of 2
std::set<int> s;
for (int i = 0; s.size() < kTestSize; i++) {
if ((map_.hash_function()(i) & (kTestSize - 1)) < 3) {
s.insert(i);
}
}
// Create hash table with kTestSize entries that hash flood a table with
// 1024 (or 512 or 2048 or ...) entries. This assumes that map_ uses powers
// of 2 for table sizes, and that it's sufficient to "flood" with respect to
// the low bits of the output of map_.hash_function().
std::vector<int64> times;
std::set<int>::iterator it = s.begin();
int count = 0;
do {
const int64 start = Now();
map_[*it] = 0;
const int64 end = Now();
if (end > start) {
times.push_back(end - start);
}
++count;
++it;
} while (it != s.end());
if (times.size() < .99 * count) return;
int64 x0 = median(times.begin(), times.begin() + 9);
int64 x1 = median(times.begin() + times.size() - 9, times.end());
// x1 will greatly exceed x0 if the code we just executed took O(n^2) time.
// But we want to allow O(n log n). A factor of 20 should be generous enough.
EXPECT_LE(x1, x0 * 20);
}
TEST_F(MapImplTest, CopyIteratorStressTest) {
std::vector<Map<int32, int32>::iterator> v;
const int kIters = 1e5;
for (uint32 i = 0; i < kIters; i++) {
int32 key = (3 + i * (5 + i * (-8 + i * (62 + i)))) & 0x77777777;
map_[key] = i;
v.push_back(map_.find(key));
}
for (std::vector<Map<int32, int32>::iterator>::const_iterator it = v.begin();
it != v.end(); it++) {
Map<int32, int32>::iterator i = *it;
ASSERT_EQ(i->first, (*it)->first);
ASSERT_EQ(i->second, (*it)->second);
}
}
template <typename T, typename U>
static void TestValidityForAllKeysExcept(int key_to_avoid, const T& check_map,
const U& map) {
typedef typename U::value_type value_type; // a key-value pair
for (typename U::const_iterator it = map.begin(); it != map.end(); ++it) {
const int key = it->first;
if (key == key_to_avoid) continue;
// All iterators relevant to this key, whether old (from check_map) or new,
// must point to the same memory. So, test pointer equality here.
const value_type* check_val = &*check_map.find(key)->second;
EXPECT_EQ(check_val, &*it);
EXPECT_EQ(check_val, &*map.find(key));
}
}
// EXPECT i0 and i1 to be the same. Advancing them should have the same effect,
// too.
template <typename Iter>
static void TestEqualIterators(Iter i0, Iter i1, Iter end) {
const int kMaxAdvance = 10;
for (int i = 0; i < kMaxAdvance; i++) {
EXPECT_EQ(i0 == end, i1 == end);
if (i0 == end) return;
EXPECT_EQ(&*i0, &*i1) << "iter " << i;
++i0;
++i1;
}
}
template <typename IteratorType>
static void TestOldVersusNewIterator(int skip, Map<int, int>* m) {
const int initial_size = m->size();
IteratorType it = m->begin();
for (int i = 0; i < skip && it != m->end(); it++, i++) {
}
if (it == m->end()) return;
const IteratorType old = it;
GOOGLE_LOG(INFO) << "skip=" << skip << ", old->first=" << old->first;
const int target_size =
initial_size < 100 ? initial_size * 5 : initial_size * 5 / 4;
for (int i = 0; m->size() <= target_size; i++) {
(*m)[i] = 0;
}
// Iterator 'old' should still work just fine despite the growth of *m.
const IteratorType after_growth = m->find(old->first);
TestEqualIterators<IteratorType>(old, after_growth, m->end());
// Now shrink the number of elements. Do this with a mix of erases and
// inserts to increase the chance that the hashtable will resize to a lower
// number of buckets. (But, in any case, the test is still useful.)
for (int i = 0; i < 2 * (target_size - initial_size); i++) {
if (i != old->first) {
m->erase(i);
}
if (((i ^ m->begin()->first) & 15) == 0) {
(*m)[i * 342] = i;
}
}
// Now, the table has grown and shrunk; test again.
TestEqualIterators<IteratorType>(old, m->find(old->first), m->end());
TestEqualIterators<IteratorType>(old, after_growth, m->end());
}
// Create and test an n-element Map, with emphasis on iterator correctness.
static void StressTestIterators(int n) {
GOOGLE_LOG(INFO) << "StressTestIterators " << n;
GOOGLE_CHECK_GT(n, 0);
// Create a random-looking map of size n. Use non-negative integer keys.
Map<int, int> m;
uint32 frog = 123987 + n;
int last_key = 0;
int counter = 0;
while (m.size() < n) {
frog *= static_cast<uint32>(k0);
frog ^= frog >> 17;
frog += counter++;
last_key =
static_cast<int>(frog) >= 0 ? static_cast<int>(frog) : last_key ^ 1;
GOOGLE_DCHECK_GE(last_key, 0);
m[last_key] = last_key ^ 1;
}
// Test it.
ASSERT_EQ(n, m.size());
// Create maps of pointers and iterators.
// These should remain valid even if we modify m.
std::unordered_map<int, Map<int, int>::value_type*> mp(n);
std::unordered_map<int, Map<int, int>::iterator> mi(n);
for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
mp[it->first] = &*it;
mi[it->first] = it;
}
ASSERT_EQ(m.size(), mi.size());
ASSERT_EQ(m.size(), mp.size());
m.erase(last_key);
ASSERT_EQ(n - 1, m.size());
TestValidityForAllKeysExcept(last_key, mp, m);
TestValidityForAllKeysExcept(last_key, mi, m);
m[last_key] = 0;
ASSERT_EQ(n, m.size());
// Test old iterator vs new iterator, with table modification in between.
TestOldVersusNewIterator<Map<int, int>::const_iterator>(n % 3, &m);
TestOldVersusNewIterator<Map<int, int>::iterator>(n % (1 + (n / 40)), &m);
// Finally, ensure erase(iterator) doesn't reorder anything, because that is
// what its documentation says.
m[last_key] = m[last_key ^ 999] = 0;
std::vector<Map<int, int>::iterator> v;
v.reserve(m.size());
int position_of_last_key = 0;
for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it) {
if (it->first == last_key) {
position_of_last_key = v.size();
}
v.push_back(it);
}
ASSERT_EQ(m.size(), v.size());
const Map<int, int>::iterator erase_result = m.erase(m.find(last_key));
int index = 0;
for (Map<int, int>::iterator it = m.begin(); it != m.end(); ++it, ++index) {
if (index == position_of_last_key) {
EXPECT_EQ(&*erase_result, &*v[++index]);
}
ASSERT_EQ(&*it, &*v[index]);
}
}
TEST_F(MapImplTest, IteratorInvalidation) {
// Create a set of pseudo-random sizes to test.
#ifndef NDEBUG
const int kMaxSizeToTest = 100 * 1000;
#else
const int kMaxSizeToTest = 1000 * 1000;
#endif
std::set<int> s;
int n = kMaxSizeToTest;
unsigned int frog = k1 + n;
while (n > 1 && s.size() < 25) {
s.insert(n);
n = static_cast<int>(n * 100 / (101.0 + (frog & 63)));
frog *= k2;
frog ^= frog >> 17;
}
// Ensure we test a few small sizes.
s.insert(1);
s.insert(2);
s.insert(3);
// Now, the real work.
for (std::set<int>::iterator i = s.begin(); i != s.end(); ++i) {
StressTestIterators(*i);
}
}
// Test that erase() revalidates iterators.
TEST_F(MapImplTest, EraseRevalidates) {
map_[3] = map_[13] = map_[20] = 0;
const int initial_size = map_.size();
EXPECT_EQ(3, initial_size);
std::vector<Map<int, int>::iterator> v;
for (Map<int, int>::iterator it = map_.begin(); it != map_.end(); ++it) {
v.push_back(it);
}
EXPECT_EQ(initial_size, v.size());
for (int i = 0; map_.size() <= initial_size * 20; i++) {
map_[i] = 0;
}
const int larger_size = map_.size();
// We've greatly increased the size of the map, so it is highly likely that
// the following will corrupt m if erase() doesn't properly revalidate
// iterators passed to it. Finishing this routine without crashing indicates
// success.
for (int i = 0; i < v.size(); i++) {
map_.erase(v[i]);
}
EXPECT_EQ(larger_size - v.size(), map_.size());
}
template <typename T>
bool IsConstHelper(T& /*t*/) { // NOLINT. We want to catch non-const refs here.
return false;
}
template <typename T>
bool IsConstHelper(const T& /*t*/) {
return true;
}
TEST_F(MapImplTest, IteratorConstness) {
map_[0] = 0;
EXPECT_TRUE(IsConstHelper(*map_.cbegin()));
EXPECT_TRUE(IsConstHelper(*const_map_.begin()));
EXPECT_FALSE(IsConstHelper(*map_.begin()));
}
bool IsForwardIteratorHelper(std::forward_iterator_tag /*tag*/) { return true; }
TEST_F(MapImplTest, IteratorCategory) {
EXPECT_TRUE(IsForwardIteratorHelper(
std::iterator_traits<Map<int, int>::iterator>::iterator_category()));
EXPECT_TRUE(IsForwardIteratorHelper(
std::iterator_traits<
Map<int, int>::const_iterator>::iterator_category()));
}
TEST_F(MapImplTest, InsertSingle) {
int32 key = 0;
int32 value1 = 100;
int32 value2 = 101;
// Insert a non-existed key.
std::pair<Map<int32, int32>::iterator, bool> result1 =
map_.insert(Map<int32, int32>::value_type(key, value1));
ExpectSingleElement(key, value1);
Map<int32, int32>::iterator it1 = result1.first;
EXPECT_EQ(key, it1->first);
EXPECT_EQ(value1, it1->second);
EXPECT_TRUE(result1.second);
// Insert an existed key.
std::pair<Map<int32, int32>::iterator, bool> result2 =
map_.insert(Map<int32, int32>::value_type(key, value2));
ExpectSingleElement(key, value1);
Map<int32, int32>::iterator it2 = result2.first;
EXPECT_TRUE(it1 == it2);
EXPECT_FALSE(result2.second);
}
TEST_F(MapImplTest, InsertByIterator) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1a = 100;
int32 value1b = 101;
int32 value2a = 200;
int32 value2b = 201;
std::map<int32, int32> map1;
map1[key1] = value1a;
map1[key2] = value2a;
map_.insert(map1.begin(), map1.end());
ExpectElements(map1);
std::map<int32, int32> map2;
map2[key1] = value1b;
map2[key2] = value2b;
map_.insert(map2.begin(), map2.end());
ExpectElements(map1);
}
TEST_F(MapImplTest, InsertByInitializerList) {
map_.insert({{1, 100}, {2, 200}});
ExpectElements({{1, 100}, {2, 200}});
map_.insert({{2, 201}, {3, 301}});
ExpectElements({{1, 100}, {2, 200}, {3, 301}});
}
TEST_F(MapImplTest, EraseSingleByKey) {
int32 key = 0;
int32 value = 100;
map_[key] = value;
ExpectSingleElement(key, value);
// Erase an existing key.
EXPECT_EQ(1, map_.erase(key));
EXPECT_TRUE(map_.empty());
EXPECT_EQ(0, map_.size());
EXPECT_TRUE(map_.end() == map_.find(key));
EXPECT_TRUE(map_.begin() == map_.end());
// Erase a non-existing key.
EXPECT_EQ(0, map_.erase(key));
}
TEST_F(MapImplTest, EraseMutipleByKey) {
// erase in one specific order to trigger corner cases
for (int i = 0; i < 5; i++) {
map_[i] = i;
}
map_.erase(0);
EXPECT_EQ(4, map_.size());
EXPECT_TRUE(map_.end() == map_.find(0));
map_.erase(1);
EXPECT_EQ(3, map_.size());
EXPECT_TRUE(map_.end() == map_.find(1));
map_.erase(3);
EXPECT_EQ(2, map_.size());
EXPECT_TRUE(map_.end() == map_.find(3));
map_.erase(4);
EXPECT_EQ(1, map_.size());
EXPECT_TRUE(map_.end() == map_.find(4));
map_.erase(2);
EXPECT_EQ(0, map_.size());
EXPECT_TRUE(map_.end() == map_.find(2));
}
TEST_F(MapImplTest, EraseSingleByIterator) {
int32 key = 0;
int32 value = 100;
map_[key] = value;
ExpectSingleElement(key, value);
Map<int32, int32>::iterator it = map_.find(key);
map_.erase(it);
EXPECT_TRUE(map_.empty());
EXPECT_EQ(0, map_.size());
EXPECT_TRUE(map_.end() == map_.find(key));
EXPECT_TRUE(map_.begin() == map_.end());
}
TEST_F(MapImplTest, ValidIteratorAfterErase) {
for (int i = 0; i < 10; i++) {
map_[i] = i;
}
int count = 0;
for (Map<int32, int32>::iterator it = map_.begin(); it != map_.end();) {
count++;
if (it->first % 2 == 1) {
map_.erase(it++);
} else {
++it;
}
}
EXPECT_EQ(10, count);
EXPECT_EQ(5, map_.size());
}
TEST_F(MapImplTest, EraseByIterator) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1 = 100;
int32 value2 = 101;
std::map<int32, int32> map;
map[key1] = value1;
map[key2] = value2;
map_.insert(map.begin(), map.end());
ExpectElements(map);
map_.erase(map_.begin(), map_.end());
EXPECT_TRUE(map_.empty());
EXPECT_EQ(0, map_.size());
EXPECT_TRUE(map_.end() == map_.find(key1));
EXPECT_TRUE(map_.end() == map_.find(key2));
EXPECT_TRUE(map_.begin() == map_.end());
}
TEST_F(MapImplTest, Clear) {
int32 key = 0;
int32 value = 100;
map_[key] = value;
ExpectSingleElement(key, value);
map_.clear();
EXPECT_TRUE(map_.empty());
EXPECT_EQ(0, map_.size());
EXPECT_TRUE(map_.end() == map_.find(key));
EXPECT_TRUE(map_.begin() == map_.end());
}
static void CopyConstructorHelper(Arena* arena, Map<int32, int32>* m) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1 = 100;
int32 value2 = 101;
std::map<int32, int32> map;
map[key1] = value1;
map[key2] = value2;
m->insert(map.begin(), map.end());
Map<int32, int32> other(*m);
EXPECT_EQ(2, other.size());
EXPECT_EQ(value1, other.at(key1));
EXPECT_EQ(value2, other.at(key2));
}
TEST_F(MapImplTest, CopyConstructorWithArena) {
Arena a;
CopyConstructorHelper(&a, &map_);
}
TEST_F(MapImplTest, CopyConstructorWithoutArena) {
CopyConstructorHelper(nullptr, &map_);
}
TEST_F(MapImplTest, IterConstructor) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1 = 100;
int32 value2 = 101;
std::map<int32, int32> map;
map[key1] = value1;
map[key2] = value2;
Map<int32, int32> new_map(map.begin(), map.end());
EXPECT_EQ(2, new_map.size());
EXPECT_EQ(value1, new_map.at(key1));
EXPECT_EQ(value2, new_map.at(key2));
}
TEST_F(MapImplTest, Assigner) {
int32 key1 = 0;
int32 key2 = 1;
int32 value1 = 100;
int32 value2 = 101;
std::map<int32, int32> map;
map[key1] = value1;
map[key2] = value2;
map_.insert(map.begin(), map.end());
Map<int32, int32> other;
int32 key_other = 123;
int32 value_other = 321;
other[key_other] = value_other;
EXPECT_EQ(1, other.size());
other = map_;
EXPECT_EQ(2, other.size());
EXPECT_EQ(value1, other.at(key1));
EXPECT_EQ(value2, other.at(key2));
EXPECT_TRUE(other.find(key_other) == other.end());
// Self assign
other = *&other; // Avoid -Wself-assign.
EXPECT_EQ(2, other.size());
EXPECT_EQ(value1, other.at(key1));
EXPECT_EQ(value2, other.at(key2));
}
TEST_F(MapImplTest, Rehash) {
const int test_size = 50;
std::map<int32, int32> reference_map;
for (int i = 0; i < test_size; i++) {
reference_map[i] = i;
}
for (int i = 0; i < test_size; i++) {
map_[i] = reference_map[i];
EXPECT_EQ(reference_map[i], map_[i]);
}
for (int i = 0; i < test_size; i++) {
map_.erase(i);
EXPECT_TRUE(map_.end() == map_.find(i));
}
EXPECT_TRUE(map_.empty());
}
TEST_F(MapImplTest, EqualRange) {
int key = 100, key_missing = 101;
map_[key] = 100;
std::pair<Map<int32, int32>::iterator, Map<int32, int32>::iterator> range =
map_.equal_range(key);
EXPECT_TRUE(map_.find(key) == range.first);
EXPECT_TRUE(++map_.find(key) == range.second);
range = map_.equal_range(key_missing);
EXPECT_TRUE(map_.end() == range.first);
EXPECT_TRUE(map_.end() == range.second);
std::pair<Map<int32, int32>::const_iterator,
Map<int32, int32>::const_iterator>
const_range = const_map_.equal_range(key);
EXPECT_TRUE(const_map_.find(key) == const_range.first);
EXPECT_TRUE(++const_map_.find(key) == const_range.second);
const_range = const_map_.equal_range(key_missing);
EXPECT_TRUE(const_map_.end() == const_range.first);
EXPECT_TRUE(const_map_.end() == const_range.second);
}
TEST_F(MapImplTest, ConvertToStdMap) {
map_[100] = 101;
std::map<int32, int32> std_map(map_.begin(), map_.end());
EXPECT_EQ(1, std_map.size());
EXPECT_EQ(101, std_map[100]);
}
TEST_F(MapImplTest, ConvertToStdVectorOfPairs) {
map_[100] = 101;
std::vector<std::pair<int32, int32> > std_vec(map_.begin(), map_.end());
EXPECT_EQ(1, std_vec.size());
EXPECT_EQ(100, std_vec[0].first);
EXPECT_EQ(101, std_vec[0].second);
}
TEST_F(MapImplTest, SwapBasic) {
Map<int32, int32> another;
map_[9398] = 41999;
another[9398] = 41999;
another[8070] = 42056;
another.swap(map_);
EXPECT_THAT(another,
testing::UnorderedElementsAre(testing::Pair(9398, 41999)));
EXPECT_THAT(map_, testing::UnorderedElementsAre(testing::Pair(8070, 42056),
testing::Pair(9398, 41999)));
}
TEST_F(MapImplTest, SwapArena) {
Arena arena1, arena2;
Map<int32, int32> m1(&arena1);
Map<int32, int32> m2(&arena2);
map_[9398] = 41999;
m1[9398] = 41999;
m1[8070] = 42056;
m2[10244] = 10247;
m2[8070] = 42056;
m1.swap(map_);
EXPECT_THAT(m1, testing::UnorderedElementsAre(testing::Pair(9398, 41999)));
EXPECT_THAT(map_, testing::UnorderedElementsAre(testing::Pair(8070, 42056),
testing::Pair(9398, 41999)));
m2.swap(m1);
EXPECT_THAT(m1, testing::UnorderedElementsAre(testing::Pair(8070, 42056),
testing::Pair(10244, 10247)));
EXPECT_THAT(m2, testing::UnorderedElementsAre(testing::Pair(9398, 41999)));
}
TEST_F(MapImplTest, SwapFieldArenaReflection) {
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
Arena arena;
{
// Tests filled lfs and empty rhs.
TestMap rhs;
{
// Use local_arena to allocate lhs to trigger use-after-free error.
Arena local_arena;
auto* lhs = Arena::CreateMessage<TestMap>(&local_arena);
const auto* reflection = lhs->GetReflection();
std::vector<const FieldDescriptor*> fields;
reflection_tester.SetMapFieldsViaReflection(lhs);
reflection->ListFields(*lhs, &fields);
reflection->SwapFields(lhs, &rhs, fields);
reflection_tester.ExpectClearViaReflection(*lhs);
}
reflection_tester.ExpectMapFieldsSetViaReflection(rhs);
}
}
TEST_F(MapImplTest, CopyAssignMapIterator) {
TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaMapReflection(&message);
MapIterator it1 = reflection_tester.MapBegin(&message, "map_int32_int32");
MapIterator it2 = reflection_tester.MapEnd(&message, "map_int32_int32");
it2 = it1;
EXPECT_EQ(it1.GetKey().GetInt32Value(), it2.GetKey().GetInt32Value());
}
TEST_F(MapImplTest, SpaceUsed) {
constexpr size_t kMinCap = 8;
Map<int32, int32> m;
// An newly constructed map should have no space used.
EXPECT_EQ(m.SpaceUsedExcludingSelfLong(), 0);
size_t capacity = kMinCap;
for (int i = 0; i < 100; ++i) {
m[i];
static constexpr double kMaxLoadFactor = .75;
if (m.size() >= capacity * kMaxLoadFactor) {
capacity *= 2;
}
EXPECT_EQ(m.SpaceUsedExcludingSelfLong(),
sizeof(void*) * capacity +
m.size() * sizeof(std::pair<std::pair<int32, int32>, void*>));
}
// Test string, and non-scalar keys.
Map<std::string, int32> m2;
std::string str = "Some arbitrarily large string";
m2[str] = 1;
EXPECT_EQ(m2.SpaceUsedExcludingSelfLong(),
sizeof(void*) * kMinCap +
sizeof(std::pair<std::pair<std::string, int32>, void*>) +
internal::StringSpaceUsedExcludingSelfLong(str));
// Test messages, and non-scalar values.
Map<int32, TestAllTypes> m3;
m3[0].set_optional_string(str);
EXPECT_EQ(m3.SpaceUsedExcludingSelfLong(),
sizeof(void*) * kMinCap +
sizeof(std::pair<std::pair<int32, TestAllTypes>, void*>) +
m3[0].SpaceUsedLong() - sizeof(m3[0]));
}
// Attempts to verify that a map with keys a and b has a random ordering. This
// function returns true if it succeeds in observing both possible orderings.
bool MapOrderingIsRandom(int a, int b) {
bool saw_a_first = false;
bool saw_b_first = false;
std::vector<Map<int32, int32>> v(50);
for (int i = 0; i < 50; ++i) {
Map<int32, int32>& m = v[i];
m[a] = 0;
m[b] = 0;
int32 first_element = m.begin()->first;
if (first_element == a) saw_a_first = true;
if (first_element == b) saw_b_first = true;
if (saw_a_first && saw_b_first) {
return true;
}
}
return false;
}
// This test verifies that the iteration order is reasonably random even for
// small maps.
TEST_F(MapImplTest, RandomOrdering) {
for (int i = 0; i < 10; ++i) {
for (int j = i + 1; j < 10; ++j) {
EXPECT_TRUE(MapOrderingIsRandom(i, j))
<< "Map with keys " << i << " and " << j
<< " has deterministic ordering";
}
}
}
template <typename Key>
void TestTransparent(const Key& key, const Key& miss_key) {
Map<std::string, int> m;
const auto& cm = m;
m.insert({"ABC", 1});
const auto abc_it = m.begin();
m.insert({"DEF", 2});
using testing::Pair;
using testing::UnorderedElementsAre;
EXPECT_EQ(m.at(key), 1);
EXPECT_EQ(cm.at(key), 1);
#ifdef PROTOBUF_HAS_DEATH_TEST
EXPECT_DEATH(m.at(miss_key), "");
EXPECT_DEATH(cm.at(miss_key), "");
#endif // PROTOBUF_HAS_DEATH_TEST
EXPECT_EQ(m.count(key), 1);
EXPECT_EQ(cm.count(key), 1);
EXPECT_EQ(m.count(miss_key), 0);
EXPECT_EQ(cm.count(miss_key), 0);
EXPECT_EQ(m.find(key), abc_it);
EXPECT_EQ(cm.find(key), abc_it);
EXPECT_EQ(m.find(miss_key), m.end());
EXPECT_EQ(cm.find(miss_key), cm.end());
EXPECT_TRUE(m.contains(key));
EXPECT_TRUE(cm.contains(key));
EXPECT_FALSE(m.contains(miss_key));
EXPECT_FALSE(cm.contains(miss_key));
EXPECT_THAT(m.equal_range(key), Pair(abc_it, std::next(abc_it)));
EXPECT_THAT(cm.equal_range(key), Pair(abc_it, std::next(abc_it)));
EXPECT_THAT(m.equal_range(miss_key), Pair(m.end(), m.end()));
EXPECT_THAT(cm.equal_range(miss_key), Pair(m.end(), m.end()));
EXPECT_THAT(m, UnorderedElementsAre(Pair("ABC", 1), Pair("DEF", 2)));
EXPECT_EQ(m.erase(key), 1);
EXPECT_THAT(m, UnorderedElementsAre(Pair("DEF", 2)));
EXPECT_EQ(m.erase(key), 0);
EXPECT_EQ(m.erase(miss_key), 0);
EXPECT_THAT(m, UnorderedElementsAre(Pair("DEF", 2)));
m[key];
EXPECT_THAT(m, UnorderedElementsAre(Pair("ABC", 0), Pair("DEF", 2)));
m[key] = 1;
EXPECT_THAT(m, UnorderedElementsAre(Pair("ABC", 1), Pair("DEF", 2)));
}
TEST_F(MapImplTest, TransparentLookupForString) {
TestTransparent("ABC", "LKJ");
TestTransparent(std::string("ABC"), std::string("LKJ"));
#if defined(__cpp_lib_string_view)
TestTransparent(std::string_view("ABC"), std::string_view("LKJ"));
#endif // defined(__cpp_lib_string_view)
// std::reference_wrapper
std::string abc = "ABC", lkj = "LKJ";
TestTransparent(std::ref(abc), std::ref(lkj));
TestTransparent(std::cref(abc), std::cref(lkj));
}
TEST_F(MapImplTest, ConstInit) {
PROTOBUF_CONSTINIT static Map<int, int> map; // NOLINT
EXPECT_TRUE(map.empty());
}
// Map Field Reflection Test ========================================
static int Func(int i, int j) { return i * j; }
static std::string StrFunc(int i, int j) { return StrCat(Func(i, j)); }
static int Int(const std::string& value) {
int result = 0;
std::istringstream(value) >> result;
return result;
}
} // namespace
// This class is a friend, so no anonymous namespace.
class MapFieldReflectionTest : public testing::Test {
protected:
typedef FieldDescriptor FD;
int MapSize(const Reflection* reflection, const FieldDescriptor* field,
const Message& message) {
return reflection->MapSize(message, field);
}
};
namespace {
TEST_F(MapFieldReflectionTest, RegularFields) {
TestMap message;
const Reflection* refl = message.GetReflection();
const Descriptor* desc = message.GetDescriptor();
Map<int32, int32>* map_int32_int32 = message.mutable_map_int32_int32();
Map<int32, double>* map_int32_double = message.mutable_map_int32_double();
Map<std::string, std::string>* map_string_string =
message.mutable_map_string_string();
Map<int32, ForeignMessage>* map_int32_foreign_message =
message.mutable_map_int32_foreign_message();
for (int i = 0; i < 10; ++i) {
(*map_int32_int32)[i] = Func(i, 1);
(*map_int32_double)[i] = Func(i, 2);
(*map_string_string)[StrFunc(i, 1)] = StrFunc(i, 5);
(*map_int32_foreign_message)[i].set_c(Func(i, 6));
}
// Get FieldDescriptors for all the fields of interest.
const FieldDescriptor* fd_map_int32_int32 =
desc->FindFieldByName("map_int32_int32");
const FieldDescriptor* fd_map_int32_double =
desc->FindFieldByName("map_int32_double");
const FieldDescriptor* fd_map_string_string =
desc->FindFieldByName("map_string_string");
const FieldDescriptor* fd_map_int32_foreign_message =
desc->FindFieldByName("map_int32_foreign_message");
const FieldDescriptor* fd_map_int32_in32_key =
fd_map_int32_int32->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_int32_in32_value =
fd_map_int32_int32->message_type()->FindFieldByName("value");
const FieldDescriptor* fd_map_int32_double_key =
fd_map_int32_double->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_int32_double_value =
fd_map_int32_double->message_type()->FindFieldByName("value");
const FieldDescriptor* fd_map_string_string_key =
fd_map_string_string->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_string_string_value =
fd_map_string_string->message_type()->FindFieldByName("value");
const FieldDescriptor* fd_map_int32_foreign_message_key =
fd_map_int32_foreign_message->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_int32_foreign_message_value =
fd_map_int32_foreign_message->message_type()->FindFieldByName("value");
// Get RepeatedPtrField objects for all fields of interest.
const RepeatedPtrField<Message>& mf_int32_int32 =
refl->GetRepeatedPtrField<Message>(message, fd_map_int32_int32);
const RepeatedPtrField<Message>& mf_int32_double =
refl->GetRepeatedPtrField<Message>(message, fd_map_int32_double);
const RepeatedPtrField<Message>& mf_string_string =
refl->GetRepeatedPtrField<Message>(message, fd_map_string_string);
const RepeatedPtrField<Message>& mf_int32_foreign_message =
refl->GetRepeatedPtrField<Message>(message, fd_map_int32_foreign_message);
// Get mutable RepeatedPtrField objects for all fields of interest.
RepeatedPtrField<Message>* mmf_int32_int32 =
refl->MutableRepeatedPtrField<Message>(&message, fd_map_int32_int32);
RepeatedPtrField<Message>* mmf_int32_double =
refl->MutableRepeatedPtrField<Message>(&message, fd_map_int32_double);
RepeatedPtrField<Message>* mmf_string_string =
refl->MutableRepeatedPtrField<Message>(&message, fd_map_string_string);
RepeatedPtrField<Message>* mmf_int32_foreign_message =
refl->MutableRepeatedPtrField<Message>(&message,
fd_map_int32_foreign_message);
// Make sure we can do gets through the RepeatedPtrField objects.
for (int i = 0; i < 10; ++i) {
{
// Check gets through const objects.
const Message& message_int32_int32 = mf_int32_int32.Get(i);
int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_key);
int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_value);
EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
const Message& message_int32_double = mf_int32_double.Get(i);
int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
message_int32_double, fd_map_int32_double_key);
double value_int32_double =
message_int32_double.GetReflection()->GetDouble(
message_int32_double, fd_map_int32_double_value);
EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
const Message& message_string_string = mf_string_string.Get(i);
std::string key_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_key);
std::string value_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_value);
EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
const Message& message_int32_message = mf_int32_foreign_message.Get(i);
int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
message_int32_message, fd_map_int32_foreign_message_key);
const ForeignMessage& value_int32_message =
down_cast<const ForeignMessage&>(
message_int32_message.GetReflection()->GetMessage(
message_int32_message, fd_map_int32_foreign_message_value));
EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
}
{
// Check gets through mutable objects.
const Message& message_int32_int32 = mmf_int32_int32->Get(i);
int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_key);
int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_value);
EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
const Message& message_int32_double = mmf_int32_double->Get(i);
int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
message_int32_double, fd_map_int32_double_key);
double value_int32_double =
message_int32_double.GetReflection()->GetDouble(
message_int32_double, fd_map_int32_double_value);
EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
const Message& message_string_string = mmf_string_string->Get(i);
std::string key_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_key);
std::string value_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_value);
EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
const Message& message_int32_message = mmf_int32_foreign_message->Get(i);
int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
message_int32_message, fd_map_int32_foreign_message_key);
const ForeignMessage& value_int32_message =
down_cast<const ForeignMessage&>(
message_int32_message.GetReflection()->GetMessage(
message_int32_message, fd_map_int32_foreign_message_value));
EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
}
}
// Do sets through the RepeatedPtrField objects.
for (int i = 0; i < 10; i++) {
{
Message* message_int32_int32 = mmf_int32_int32->Mutable(i);
int32 key_int32_int32 = message_int32_int32->GetReflection()->GetInt32(
*message_int32_int32, fd_map_int32_in32_key);
message_int32_int32->GetReflection()->SetInt32(message_int32_int32,
fd_map_int32_in32_value,
Func(key_int32_int32, -1));
Message* message_int32_double = mmf_int32_double->Mutable(i);
int32 key_int32_double = message_int32_double->GetReflection()->GetInt32(
*message_int32_double, fd_map_int32_double_key);
message_int32_double->GetReflection()->SetDouble(
message_int32_double, fd_map_int32_double_value,
Func(key_int32_double, -2));
Message* message_string_string = mmf_string_string->Mutable(i);
std::string key_string_string =
message_string_string->GetReflection()->GetString(
*message_string_string, fd_map_string_string_key);
message_string_string->GetReflection()->SetString(
message_string_string, fd_map_string_string_value,
StrFunc(Int(key_string_string), -5));
Message* message_int32_message = mmf_int32_foreign_message->Mutable(i);
int32 key_int32_message =
message_int32_message->GetReflection()->GetInt32(
*message_int32_message, fd_map_int32_foreign_message_key);
ForeignMessage* value_int32_message = down_cast<ForeignMessage*>(
message_int32_message->GetReflection()->MutableMessage(
message_int32_message, fd_map_int32_foreign_message_value));
value_int32_message->set_c(Func(key_int32_message, -6));
}
}
// Check gets through mutable objects.
for (int i = 0; i < 10; i++) {
EXPECT_EQ(Func(i, -1), message.map_int32_int32().at(i));
EXPECT_EQ(Func(i, -2), message.map_int32_double().at(i));
EXPECT_EQ(StrFunc(i, -5), message.map_string_string().at(StrFunc(i, 1)));
EXPECT_EQ(Func(i, -6), message.map_int32_foreign_message().at(i).c());
}
}
TEST_F(MapFieldReflectionTest, RepeatedFieldRefForRegularFields) {
TestMap message;
const Reflection* refl = message.GetReflection();
const Descriptor* desc = message.GetDescriptor();
Map<int32, int32>* map_int32_int32 = message.mutable_map_int32_int32();
Map<int32, double>* map_int32_double = message.mutable_map_int32_double();
Map<std::string, std::string>* map_string_string =
message.mutable_map_string_string();
Map<int32, ForeignMessage>* map_int32_foreign_message =
message.mutable_map_int32_foreign_message();
for (int i = 0; i < 10; ++i) {
(*map_int32_int32)[i] = Func(i, 1);
(*map_int32_double)[i] = Func(i, 2);
(*map_string_string)[StrFunc(i, 1)] = StrFunc(i, 5);
(*map_int32_foreign_message)[i].set_c(Func(i, 6));
}
// Get FieldDescriptors for all the fields of interest.
const FieldDescriptor* fd_map_int32_int32 =
desc->FindFieldByName("map_int32_int32");
const FieldDescriptor* fd_map_int32_double =
desc->FindFieldByName("map_int32_double");
const FieldDescriptor* fd_map_string_string =
desc->FindFieldByName("map_string_string");
const FieldDescriptor* fd_map_int32_foreign_message =
desc->FindFieldByName("map_int32_foreign_message");
const FieldDescriptor* fd_map_int32_in32_key =
fd_map_int32_int32->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_int32_in32_value =
fd_map_int32_int32->message_type()->FindFieldByName("value");
const FieldDescriptor* fd_map_int32_double_key =
fd_map_int32_double->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_int32_double_value =
fd_map_int32_double->message_type()->FindFieldByName("value");
const FieldDescriptor* fd_map_string_string_key =
fd_map_string_string->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_string_string_value =
fd_map_string_string->message_type()->FindFieldByName("value");
const FieldDescriptor* fd_map_int32_foreign_message_key =
fd_map_int32_foreign_message->message_type()->FindFieldByName("key");
const FieldDescriptor* fd_map_int32_foreign_message_value =
fd_map_int32_foreign_message->message_type()->FindFieldByName("value");
// Get RepeatedFieldRef objects for all fields of interest.
const RepeatedFieldRef<Message> mf_int32_int32 =
refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_int32);
const RepeatedFieldRef<Message> mf_int32_double =
refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_double);
const RepeatedFieldRef<Message> mf_string_string =
refl->GetRepeatedFieldRef<Message>(message, fd_map_string_string);
const RepeatedFieldRef<Message> mf_int32_foreign_message =
refl->GetRepeatedFieldRef<Message>(message, fd_map_int32_foreign_message);
// Get mutable RepeatedFieldRef objects for all fields of interest.
const MutableRepeatedFieldRef<Message> mmf_int32_int32 =
refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_int32_int32);
const MutableRepeatedFieldRef<Message> mmf_int32_double =
refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_int32_double);
const MutableRepeatedFieldRef<Message> mmf_string_string =
refl->GetMutableRepeatedFieldRef<Message>(&message, fd_map_string_string);
const MutableRepeatedFieldRef<Message> mmf_int32_foreign_message =
refl->GetMutableRepeatedFieldRef<Message>(&message,
fd_map_int32_foreign_message);
// Get entry default instances
std::unique_ptr<Message> entry_int32_int32(
MessageFactory::generated_factory()
->GetPrototype(fd_map_int32_int32->message_type())
->New(message.GetArena()));
std::unique_ptr<Message> entry_int32_double(
MessageFactory::generated_factory()
->GetPrototype(fd_map_int32_double->message_type())
->New(message.GetArena()));
std::unique_ptr<Message> entry_string_string(
MessageFactory::generated_factory()
->GetPrototype(fd_map_string_string->message_type())
->New(message.GetArena()));
std::unique_ptr<Message> entry_int32_foreign_message(
MessageFactory::generated_factory()
->GetPrototype(fd_map_int32_foreign_message->message_type())
->New(message.GetArena()));
EXPECT_EQ(10, mf_int32_int32.size());
EXPECT_EQ(10, mmf_int32_int32.size());
EXPECT_EQ(10, mf_int32_double.size());
EXPECT_EQ(10, mmf_int32_double.size());
EXPECT_EQ(10, mf_string_string.size());
EXPECT_EQ(10, mmf_string_string.size());
EXPECT_EQ(10, mf_int32_foreign_message.size());
EXPECT_EQ(10, mmf_int32_foreign_message.size());
EXPECT_FALSE(mf_int32_int32.empty());
EXPECT_FALSE(mmf_int32_int32.empty());
EXPECT_FALSE(mf_int32_double.empty());
EXPECT_FALSE(mmf_int32_double.empty());
EXPECT_FALSE(mf_string_string.empty());
EXPECT_FALSE(mmf_string_string.empty());
EXPECT_FALSE(mf_int32_foreign_message.empty());
EXPECT_FALSE(mmf_int32_foreign_message.empty());
// Make sure we can do gets through the RepeatedFieldRef objects.
for (int i = 0; i < 10; ++i) {
{
// Check gets through const objects.
const Message& message_int32_int32 =
mf_int32_int32.Get(i, entry_int32_int32.get());
int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_key);
int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_value);
EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
const Message& message_int32_double =
mf_int32_double.Get(i, entry_int32_double.get());
int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
message_int32_double, fd_map_int32_double_key);
double value_int32_double =
message_int32_double.GetReflection()->GetDouble(
message_int32_double, fd_map_int32_double_value);
EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
const Message& message_string_string =
mf_string_string.Get(i, entry_string_string.get());
std::string key_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_key);
std::string value_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_value);
EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
const Message& message_int32_message =
mf_int32_foreign_message.Get(i, entry_int32_foreign_message.get());
int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
message_int32_message, fd_map_int32_foreign_message_key);
const ForeignMessage& value_int32_message =
down_cast<const ForeignMessage&>(
message_int32_message.GetReflection()->GetMessage(
message_int32_message, fd_map_int32_foreign_message_value));
EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
}
{
// Check gets through mutable objects.
const Message& message_int32_int32 =
mmf_int32_int32.Get(i, entry_int32_int32.get());
int32 key_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_key);
int32 value_int32_int32 = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_value);
EXPECT_EQ(value_int32_int32, Func(key_int32_int32, 1));
const Message& message_int32_double =
mmf_int32_double.Get(i, entry_int32_double.get());
int32 key_int32_double = message_int32_double.GetReflection()->GetInt32(
message_int32_double, fd_map_int32_double_key);
double value_int32_double =
message_int32_double.GetReflection()->GetDouble(
message_int32_double, fd_map_int32_double_value);
EXPECT_EQ(value_int32_double, Func(key_int32_double, 2));
const Message& message_string_string =
mmf_string_string.Get(i, entry_string_string.get());
std::string key_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_key);
std::string value_string_string =
message_string_string.GetReflection()->GetString(
message_string_string, fd_map_string_string_value);
EXPECT_EQ(value_string_string, StrFunc(Int(key_string_string), 5));
const Message& message_int32_message =
mmf_int32_foreign_message.Get(i, entry_int32_foreign_message.get());
int32 key_int32_message = message_int32_message.GetReflection()->GetInt32(
message_int32_message, fd_map_int32_foreign_message_key);
const ForeignMessage& value_int32_message =
down_cast<const ForeignMessage&>(
message_int32_message.GetReflection()->GetMessage(
message_int32_message, fd_map_int32_foreign_message_value));
EXPECT_EQ(value_int32_message.c(), Func(key_int32_message, 6));
}
}
// Make sure we can do sets through the RepeatedFieldRef objects.
for (int i = 0; i < 10; i++) {
const Message& message_int32_int32 =
mmf_int32_int32.Get(i, entry_int32_int32.get());
int key = message_int32_int32.GetReflection()->GetInt32(
message_int32_int32, fd_map_int32_in32_key);
entry_int32_int32->GetReflection()->SetInt32(
entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(0),
key);
entry_int32_int32->GetReflection()->SetInt32(
entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(1),
Func(key, -1));
entry_int32_double->GetReflection()->SetInt32(
entry_int32_double.get(), fd_map_int32_double->message_type()->field(0),
key);
entry_int32_double->GetReflection()->SetDouble(
entry_int32_double.get(), fd_map_int32_double->message_type()->field(1),
Func(key, -2));
entry_string_string->GetReflection()->SetString(
entry_string_string.get(),
fd_map_string_string->message_type()->field(0), StrFunc(key, 1));
entry_string_string->GetReflection()->SetString(
entry_string_string.get(),
fd_map_string_string->message_type()->field(1), StrFunc(key, -5));
entry_int32_foreign_message->GetReflection()->SetInt32(
entry_int32_foreign_message.get(),
fd_map_int32_foreign_message->message_type()->field(0), key);
Message* value_message =
entry_int32_foreign_message->GetReflection()->MutableMessage(
entry_int32_foreign_message.get(),
fd_map_int32_foreign_message->message_type()->field(1));
value_message->GetReflection()->SetInt32(
value_message, value_message->GetDescriptor()->FindFieldByName("c"),
Func(key, -6));
mmf_int32_int32.Set(i, *entry_int32_int32);
mmf_int32_double.Set(i, *entry_int32_double);
mmf_string_string.Set(i, *entry_string_string);
mmf_int32_foreign_message.Set(i, *entry_int32_foreign_message);
}
for (int i = 0; i < 10; i++) {
EXPECT_EQ(Func(i, -1), message.map_int32_int32().at(i));
EXPECT_EQ(Func(i, -2), message.map_int32_double().at(i));
EXPECT_EQ(StrFunc(i, -5), message.map_string_string().at(StrFunc(i, 1)));
EXPECT_EQ(Func(i, -6), message.map_int32_foreign_message().at(i).c());
}
// Test iterators.
{
int index = 0;
std::unordered_map<int32, int32> result;
for (RepeatedFieldRef<Message>::iterator it = mf_int32_int32.begin();
it != mf_int32_int32.end(); ++it) {
const Message& message = *it;
int32 key =
message.GetReflection()->GetInt32(message, fd_map_int32_in32_key);
int32 value =
message.GetReflection()->GetInt32(message, fd_map_int32_in32_value);
result[key] = value;
++index;
}
EXPECT_EQ(10, index);
for (std::unordered_map<int32, int32>::const_iterator it = result.begin();
it != result.end(); ++it) {
EXPECT_EQ(message.map_int32_int32().at(it->first), it->second);
}
}
{
int index = 0;
std::unordered_map<int32, double> result;
for (RepeatedFieldRef<Message>::iterator it = mf_int32_double.begin();
it != mf_int32_double.end(); ++it) {
const Message& message = *it;
int32 key =
message.GetReflection()->GetInt32(message, fd_map_int32_double_key);
double value = message.GetReflection()->GetDouble(
message, fd_map_int32_double_value);
result[key] = value;
++index;
}
EXPECT_EQ(10, index);
for (std::unordered_map<int32, double>::const_iterator it = result.begin();
it != result.end(); ++it) {
EXPECT_EQ(message.map_int32_double().at(it->first), it->second);
}
}
{
int index = 0;
std::unordered_map<std::string, std::string> result;
for (RepeatedFieldRef<Message>::iterator it = mf_string_string.begin();
it != mf_string_string.end(); ++it) {
const Message& message = *it;
std::string key =
message.GetReflection()->GetString(message, fd_map_string_string_key);
std::string value = message.GetReflection()->GetString(
message, fd_map_string_string_value);
result[key] = value;
++index;
}
EXPECT_EQ(10, index);
for (std::unordered_map<std::string, std::string>::const_iterator it =
result.begin();
it != result.end(); ++it) {
EXPECT_EQ(message.map_string_string().at(it->first), it->second);
}
}
{
int index = 0;
std::map<int32, ForeignMessage> result;
for (RepeatedFieldRef<Message>::iterator it =
mf_int32_foreign_message.begin();
it != mf_int32_foreign_message.end(); ++it) {
const Message& message = *it;
int32 key = message.GetReflection()->GetInt32(
message, fd_map_int32_foreign_message_key);
const ForeignMessage& sub_message =
down_cast<const ForeignMessage&>(message.GetReflection()->GetMessage(
message, fd_map_int32_foreign_message_value));
result[key].MergeFrom(sub_message);
++index;
}
EXPECT_EQ(10, index);
for (std::map<int32, ForeignMessage>::const_iterator it = result.begin();
it != result.end(); ++it) {
EXPECT_EQ(message.map_int32_foreign_message().at(it->first).c(),
it->second.c());
}
}
// Test MutableRepeatedFieldRef::Add()
entry_int32_int32->GetReflection()->SetInt32(
entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(0),
4321);
entry_int32_int32->GetReflection()->SetInt32(
entry_int32_int32.get(), fd_map_int32_int32->message_type()->field(1),
1234);
mmf_int32_int32.Add(*entry_int32_int32);
EXPECT_EQ(1234, message.map_int32_int32().at(4321));
entry_int32_double->GetReflection()->SetInt32(
entry_int32_double.get(), fd_map_int32_double->message_type()->field(0),
4321);
entry_int32_double->GetReflection()->SetDouble(
entry_int32_double.get(), fd_map_int32_double->message_type()->field(1),
1234.0);
mmf_int32_double.Add(*entry_int32_double);
EXPECT_EQ(1234.0, message.map_int32_double().at(4321));
entry_string_string->GetReflection()->SetString(
entry_string_string.get(), fd_map_string_string->message_type()->field(0),
"4321");
entry_string_string->GetReflection()->SetString(
entry_string_string.get(), fd_map_string_string->message_type()->field(1),
"1234");
mmf_string_string.Add(*entry_string_string);
EXPECT_EQ("1234", message.map_string_string().at("4321"));
entry_int32_foreign_message->GetReflection()->SetInt32(
entry_int32_foreign_message.get(),
fd_map_int32_foreign_message->message_type()->field(0), 4321);
Message* value_message =
entry_int32_foreign_message->GetReflection()->MutableMessage(
entry_int32_foreign_message.get(),
fd_map_int32_foreign_message->message_type()->field(1));
ForeignMessage foreign_message;
foreign_message.set_c(1234);
value_message->CopyFrom(foreign_message);
mmf_int32_foreign_message.Add(*entry_int32_foreign_message);
EXPECT_EQ(1234, message.map_int32_foreign_message().at(4321).c());
// Test Reflection::AddAllocatedMessage
Message* free_entry_string_string =
MessageFactory::generated_factory()
->GetPrototype(fd_map_string_string->message_type())
->New();
entry_string_string->GetReflection()->SetString(
free_entry_string_string, fd_map_string_string->message_type()->field(0),
"4321");
entry_string_string->GetReflection()->SetString(
free_entry_string_string, fd_map_string_string->message_type()->field(1),
"1234");
refl->AddAllocatedMessage(&message, fd_map_string_string,
free_entry_string_string);
// Test MutableRepeatedFieldRef::RemoveLast()
mmf_int32_int32.RemoveLast();
mmf_int32_double.RemoveLast();
mmf_string_string.RemoveLast();
mmf_int32_foreign_message.RemoveLast();
EXPECT_EQ(10, message.map_int32_int32().size());
EXPECT_EQ(10, message.map_int32_double().size());
EXPECT_EQ(11, message.map_string_string().size());
EXPECT_EQ(10, message.map_int32_foreign_message().size());
// Test MutableRepeatedFieldRef::SwapElements()
{
const Message& message0a = mmf_int32_int32.Get(0, entry_int32_int32.get());
int32 int32_value0a =
message0a.GetReflection()->GetInt32(message0a, fd_map_int32_in32_value);
const Message& message9a = mmf_int32_int32.Get(9, entry_int32_int32.get());
int32 int32_value9a =
message9a.GetReflection()->GetInt32(message9a, fd_map_int32_in32_value);
mmf_int32_int32.SwapElements(0, 9);
const Message& message0b = mmf_int32_int32.Get(0, entry_int32_int32.get());
int32 int32_value0b =
message0b.GetReflection()->GetInt32(message0b, fd_map_int32_in32_value);
const Message& message9b = mmf_int32_int32.Get(9, entry_int32_int32.get());
int32 int32_value9b =
message9b.GetReflection()->GetInt32(message9b, fd_map_int32_in32_value);
EXPECT_EQ(int32_value9a, int32_value0b);
EXPECT_EQ(int32_value0a, int32_value9b);
}
{
const Message& message0a =
mmf_int32_double.Get(0, entry_int32_double.get());
double double_value0a = message0a.GetReflection()->GetDouble(
message0a, fd_map_int32_double_value);
const Message& message9a =
mmf_int32_double.Get(9, entry_int32_double.get());
double double_value9a = message9a.GetReflection()->GetDouble(
message9a, fd_map_int32_double_value);
mmf_int32_double.SwapElements(0, 9);
const Message& message0b =
mmf_int32_double.Get(0, entry_int32_double.get());
double double_value0b = message0b.GetReflection()->GetDouble(
message0b, fd_map_int32_double_value);
const Message& message9b =
mmf_int32_double.Get(9, entry_int32_double.get());
double double_value9b = message9b.GetReflection()->GetDouble(
message9b, fd_map_int32_double_value);
EXPECT_EQ(double_value9a, double_value0b);
EXPECT_EQ(double_value0a, double_value9b);
}
{
const Message& message0a =
mmf_string_string.Get(0, entry_string_string.get());
std::string string_value0a = message0a.GetReflection()->GetString(
message0a, fd_map_string_string_value);
const Message& message9a =
mmf_string_string.Get(9, entry_string_string.get());
std::string string_value9a = message9a.GetReflection()->GetString(
message9a, fd_map_string_string_value);
mmf_string_string.SwapElements(0, 9);
const Message& message0b =
mmf_string_string.Get(0, entry_string_string.get());
std::string string_value0b = message0b.GetReflection()->GetString(
message0b, fd_map_string_string_value);
const Message& message9b =
mmf_string_string.Get(9, entry_string_string.get());
std::string string_value9b = message9b.GetReflection()->GetString(
message9b, fd_map_string_string_value);
EXPECT_EQ(string_value9a, string_value0b);
EXPECT_EQ(string_value0a, string_value9b);
}
{
const Message& message0a =
mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get());
const ForeignMessage& sub_message0a =
down_cast<const ForeignMessage&>(message0a.GetReflection()->GetMessage(
message0a, fd_map_int32_foreign_message_value));
int32 int32_value0a = sub_message0a.c();
const Message& message9a =
mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get());
const ForeignMessage& sub_message9a =
down_cast<const ForeignMessage&>(message9a.GetReflection()->GetMessage(
message9a, fd_map_int32_foreign_message_value));
int32 int32_value9a = sub_message9a.c();
mmf_int32_foreign_message.SwapElements(0, 9);
const Message& message0b =
mmf_int32_foreign_message.Get(0, entry_int32_foreign_message.get());
const ForeignMessage& sub_message0b =
down_cast<const ForeignMessage&>(message0b.GetReflection()->GetMessage(
message0b, fd_map_int32_foreign_message_value));
int32 int32_value0b = sub_message0b.c();
const Message& message9b =
mmf_int32_foreign_message.Get(9, entry_int32_foreign_message.get());
const ForeignMessage& sub_message9b =
down_cast<const ForeignMessage&>(message9b.GetReflection()->GetMessage(
message9b, fd_map_int32_foreign_message_value));
int32 int32_value9b = sub_message9b.c();
EXPECT_EQ(int32_value9a, int32_value0b);
EXPECT_EQ(int32_value0a, int32_value9b);
}
// TODO(b/181148674): After supporting arena agnostic delete or let map entry
// handle heap allocation, this could be removed.
if (message.GetArena() != nullptr) {
entry_int32_int32.release();
entry_int32_double.release();
entry_string_string.release();
entry_int32_foreign_message.release();
}
}
TEST_F(MapFieldReflectionTest, RepeatedFieldRefMergeFromAndSwap) {
// Set-up message content.
TestMap m0, m1, m2;
for (int i = 0; i < 10; ++i) {
(*m0.mutable_map_int32_int32())[i] = Func(i, 1);
(*m0.mutable_map_int32_double())[i] = Func(i, 2);
(*m0.mutable_map_string_string())[StrFunc(i, 1)] = StrFunc(i, 5);
(*m0.mutable_map_int32_foreign_message())[i].set_c(Func(i, 6));
(*m1.mutable_map_int32_int32())[i + 10] = Func(i, 11);
(*m1.mutable_map_int32_double())[i + 10] = Func(i, 12);
(*m1.mutable_map_string_string())[StrFunc(i + 10, 1)] = StrFunc(i, 15);
(*m1.mutable_map_int32_foreign_message())[i + 10].set_c(Func(i, 16));
(*m2.mutable_map_int32_int32())[i + 20] = Func(i, 21);
(*m2.mutable_map_int32_double())[i + 20] = Func(i, 22);
(*m2.mutable_map_string_string())[StrFunc(i + 20, 1)] = StrFunc(i, 25);
(*m2.mutable_map_int32_foreign_message())[i + 20].set_c(Func(i, 26));
}
const Reflection* refl = m0.GetReflection();
const Descriptor* desc = m0.GetDescriptor();
// Get FieldDescriptors for all the fields of interest.
const FieldDescriptor* fd_map_int32_int32 =
desc->FindFieldByName("map_int32_int32");
const FieldDescriptor* fd_map_int32_double =
desc->FindFieldByName("map_int32_double");
const FieldDescriptor* fd_map_string_string =
desc->FindFieldByName("map_string_string");
const FieldDescriptor* fd_map_int32_foreign_message =
desc->FindFieldByName("map_int32_foreign_message");
// Get MutableRepeatedFieldRef objects for all fields of interest.
const MutableRepeatedFieldRef<Message> mmf_int32_int32 =
refl->GetMutableRepeatedFieldRef<Message>(&m0, fd_map_int32_int32);
const MutableRepeatedFieldRef<Message> mmf_int32_double =
refl->GetMutableRepeatedFieldRef<Message>(&m0, fd_map_int32_double);
const MutableRepeatedFieldRef<Message> mmf_string_string =
refl->GetMutableRepeatedFieldRef<Message>(&m0, fd_map_string_string);
const MutableRepeatedFieldRef<Message> mmf_int32_foreign_message =
refl->GetMutableRepeatedFieldRef<Message>(&m0,
fd_map_int32_foreign_message);
// Test MutableRepeatedRef::CopyFrom
mmf_int32_int32.CopyFrom(
refl->GetRepeatedFieldRef<Message>(m1, fd_map_int32_int32));
mmf_int32_double.CopyFrom(
refl->GetRepeatedFieldRef<Message>(m1, fd_map_int32_double));
mmf_string_string.CopyFrom(
refl->GetRepeatedFieldRef<Message>(m1, fd_map_string_string));
mmf_int32_foreign_message.CopyFrom(
refl->GetRepeatedFieldRef<Message>(m1, fd_map_int32_foreign_message));
for (int i = 0; i < 10; ++i) {
EXPECT_EQ(Func(i, 11), m0.map_int32_int32().at(i + 10));
EXPECT_EQ(Func(i, 12), m0.map_int32_double().at(i + 10));
EXPECT_EQ(StrFunc(i, 15), m0.map_string_string().at(StrFunc(i + 10, 1)));
EXPECT_EQ(Func(i, 16), m0.map_int32_foreign_message().at(i + 10).c());
}
// Test MutableRepeatedRef::MergeFrom
mmf_int32_int32.MergeFrom(
refl->GetRepeatedFieldRef<Message>(m2, fd_map_int32_int32));
mmf_int32_double.MergeFrom(
refl->GetRepeatedFieldRef<Message>(m2, fd_map_int32_double));
mmf_string_string.MergeFrom(
refl->GetRepeatedFieldRef<Message>(m2, fd_map_string_string));
mmf_int32_foreign_message.MergeFrom(
refl->GetRepeatedFieldRef<Message>(m2, fd_map_int32_foreign_message));
for (int i = 0; i < 10; ++i) {
EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20));
EXPECT_EQ(Func(i, 22), m0.map_int32_double().at(i + 20));
EXPECT_EQ(StrFunc(i, 25), m0.map_string_string().at(StrFunc(i + 20, 1)));
EXPECT_EQ(Func(i, 26), m0.map_int32_foreign_message().at(i + 20).c());
}
// Test MutableRepeatedRef::Swap
// Swap between m0 and m2.
mmf_int32_int32.Swap(
refl->GetMutableRepeatedFieldRef<Message>(&m2, fd_map_int32_int32));
mmf_int32_double.Swap(
refl->GetMutableRepeatedFieldRef<Message>(&m2, fd_map_int32_double));
mmf_string_string.Swap(
refl->GetMutableRepeatedFieldRef<Message>(&m2, fd_map_string_string));
mmf_int32_foreign_message.Swap(refl->GetMutableRepeatedFieldRef<Message>(
&m2, fd_map_int32_foreign_message));
for (int i = 0; i < 10; ++i) {
// Check the content of m0.
EXPECT_EQ(Func(i, 21), m0.map_int32_int32().at(i + 20));
EXPECT_EQ(Func(i, 22), m0.map_int32_double().at(i + 20));
EXPECT_EQ(StrFunc(i, 25), m0.map_string_string().at(StrFunc(i + 20, 1)));
EXPECT_EQ(Func(i, 26), m0.map_int32_foreign_message().at(i + 20).c());
// Check the content of m2.
EXPECT_EQ(Func(i, 11), m2.map_int32_int32().at(i + 10));
EXPECT_EQ(Func(i, 12), m2.map_int32_double().at(i + 10));
EXPECT_EQ(StrFunc(i, 15), m2.map_string_string().at(StrFunc(i + 10, 1)));
EXPECT_EQ(Func(i, 16), m2.map_int32_foreign_message().at(i + 10).c());
EXPECT_EQ(Func(i, 21), m2.map_int32_int32().at(i + 20));
EXPECT_EQ(Func(i, 22), m2.map_int32_double().at(i + 20));
EXPECT_EQ(StrFunc(i, 25), m2.map_string_string().at(StrFunc(i + 20, 1)));
EXPECT_EQ(Func(i, 26), m2.map_int32_foreign_message().at(i + 20).c());
}
// TODO(teboring): add test for duplicated key
}
TEST_F(MapFieldReflectionTest, MapSizeWithDuplicatedKey) {
// Dynamic Message
{
DynamicMessageFactory factory;
std::unique_ptr<Message> message(
factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
const Reflection* reflection = message->GetReflection();
const FieldDescriptor* field =
UNITTEST::TestMap::descriptor()->FindFieldByName("map_int32_int32");
Message* entry1 = reflection->AddMessage(message.get(), field);
Message* entry2 = reflection->AddMessage(message.get(), field);
const Reflection* entry_reflection = entry1->GetReflection();
const FieldDescriptor* key_field =
entry1->GetDescriptor()->FindFieldByName("key");
entry_reflection->SetInt32(entry1, key_field, 1);
entry_reflection->SetInt32(entry2, key_field, 1);
EXPECT_EQ(2, reflection->FieldSize(*message, field));
EXPECT_EQ(1, MapSize(reflection, field, *message));
EXPECT_EQ(2, reflection->FieldSize(*message, field));
}
// Generated Message
{
UNITTEST::TestMap message;
const Reflection* reflection = message.GetReflection();
const FieldDescriptor* field =
message.GetDescriptor()->FindFieldByName("map_int32_int32");
Message* entry1 = reflection->AddMessage(&message, field);
Message* entry2 = reflection->AddMessage(&message, field);
const Reflection* entry_reflection = entry1->GetReflection();
const FieldDescriptor* key_field =
entry1->GetDescriptor()->FindFieldByName("key");
entry_reflection->SetInt32(entry1, key_field, 1);
entry_reflection->SetInt32(entry2, key_field, 1);
EXPECT_EQ(2, reflection->FieldSize(message, field));
EXPECT_EQ(1, MapSize(reflection, field, message));
}
}
TEST_F(MapFieldReflectionTest, UninitializedEntry) {
UNITTEST::TestRequiredMessageMap message;
const Reflection* reflection = message.GetReflection();
const FieldDescriptor* field =
message.GetDescriptor()->FindFieldByName("map_field");
auto entry = reflection->AddMessage(&message, field);
EXPECT_FALSE(entry->IsInitialized());
EXPECT_FALSE(message.IsInitialized());
}
class MyMapEntry
: public internal::MapEntry<MyMapEntry, ::google::protobuf::int32, ::google::protobuf::int32,
internal::WireFormatLite::TYPE_INT32,
internal::WireFormatLite::TYPE_INT32> {
public:
constexpr MyMapEntry() {}
MyMapEntry(Arena*) { std::abort(); }
Metadata GetMetadata() const override { std::abort(); }
static bool ValidateKey(void*) { return true; }
static bool ValidateValue(void*) { return true; }
};
class MyMapEntryLite
: public internal::MapEntryLite<MyMapEntryLite, ::google::protobuf::int32, ::google::protobuf::int32,
internal::WireFormatLite::TYPE_INT32,
internal::WireFormatLite::TYPE_INT32> {
public:
constexpr MyMapEntryLite() {}
explicit MyMapEntryLite(Arena*) { std::abort(); }
static bool ValidateKey(void*) { return true; }
static bool ValidateValue(void*) { return true; }
};
TEST(MapEntryTest, ConstInit) {
// This verifies that `MapEntry`, `MapEntryLite` and `MapEntryImpl` can be
// constant initialized.
PROTOBUF_CONSTINIT static MyMapEntry entry{};
EXPECT_NE(entry.SpaceUsed(), 0);
PROTOBUF_CONSTINIT static MyMapEntryLite entry_lite{}; // NOLINT
EXPECT_TRUE(entry_lite.IsInitialized());
}
// Generated Message Test ===========================================
TEST(GeneratedMapFieldTest, Accessors) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
MapTestUtil::ExpectMapFieldsSet(message);
MapTestUtil::ModifyMapFields(&message);
MapTestUtil::ExpectMapFieldsModified(message);
}
TEST(GeneratedMapFieldTest, SetMapFieldsInitialized) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFieldsInitialized(&message);
MapTestUtil::ExpectMapFieldsSetInitialized(message);
}
TEST(GeneratedMapFieldTest, Proto2SetMapFieldsInitialized) {
UNITTEST::TestEnumMap message;
EXPECT_EQ(UNITTEST::PROTO2_MAP_ENUM_FOO,
(*message.mutable_known_map_field())[0]);
}
TEST(GeneratedMapFieldTest, Clear) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
message.Clear();
MapTestUtil::ExpectClear(message);
}
TEST(GeneratedMapFieldTest, ClearMessageMap) {
UNITTEST::TestMessageMap message;
// Creates a TestAllTypes with default value
TestUtil::ExpectClear((*message.mutable_map_int32_message())[0]);
}
TEST(GeneratedMapFieldTest, CopyFrom) {
UNITTEST::TestMap message1, message2;
MapTestUtil::SetMapFields(&message1);
message2.CopyFrom(message1);
MapTestUtil::ExpectMapFieldsSet(message2);
// Copying from self should be a no-op.
message2.CopyFrom(message2);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldTest, CopyFromMessageMap) {
UNITTEST::TestMessageMap message1, message2;
(*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
(*message2.mutable_map_int32_message())[0].add_repeated_int32(101);
message1.CopyFrom(message2);
// Checks repeated field is overwritten.
EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
}
TEST(GeneratedMapFieldTest, SwapWithEmpty) {
UNITTEST::TestMap message1, message2;
MapTestUtil::SetMapFields(&message1);
MapTestUtil::ExpectMapFieldsSet(message1);
MapTestUtil::ExpectClear(message2);
message1.Swap(&message2);
MapTestUtil::ExpectMapFieldsSet(message2);
MapTestUtil::ExpectClear(message1);
}
TEST(GeneratedMapFieldTest, SwapWithSelf) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
MapTestUtil::ExpectMapFieldsSet(message);
message.Swap(&message);
MapTestUtil::ExpectMapFieldsSet(message);
}
TEST(GeneratedMapFieldTest, SwapWithOther) {
UNITTEST::TestMap message1, message2;
MapTestUtil::SetMapFields(&message1);
MapTestUtil::SetMapFields(&message2);
MapTestUtil::ModifyMapFields(&message2);
message1.Swap(&message2);
MapTestUtil::ExpectMapFieldsModified(message1);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldTest, CopyConstructor) {
UNITTEST::TestMap message1;
MapTestUtil::SetMapFields(&message1);
UNITTEST::TestMap message2(message1);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldTest, CopyAssignmentOperator) {
UNITTEST::TestMap message1;
MapTestUtil::SetMapFields(&message1);
UNITTEST::TestMap message2;
message2 = message1;
MapTestUtil::ExpectMapFieldsSet(message2);
// Make sure that self-assignment does something sane.
message2.operator=(message2);
MapTestUtil::ExpectMapFieldsSet(message2);
}
#if !defined(PROTOBUF_TEST_NO_DESCRIPTORS) || PROTOBUF_RTTI
TEST(GeneratedMapFieldTest, UpcastCopyFrom) {
// Test the CopyFrom method that takes in the generic const Message&
// parameter.
UNITTEST::TestMap message1, message2;
MapTestUtil::SetMapFields(&message1);
const Message* source = implicit_cast<const Message*>(&message1);
message2.CopyFrom(*source);
MapTestUtil::ExpectMapFieldsSet(message2);
}
#endif
#ifndef PROTOBUF_TEST_NO_DESCRIPTORS
TEST(GeneratedMapFieldTest, CopyFromDynamicMessage) {
// Test copying from a DynamicMessage, which must fall back to using
// reflection.
UNITTEST::TestMap message2;
// Construct a new version of the dynamic message via the factory.
DynamicMessageFactory factory;
std::unique_ptr<Message> message1;
message1.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaReflection(message1.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
message2.CopyFrom(*message1);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldTest, CopyFromDynamicMessageMapReflection) {
UNITTEST::TestMap message2;
// Construct a new version of the dynamic message via the factory.
DynamicMessageFactory factory;
std::unique_ptr<Message> message1;
message1.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaMapReflection(message1.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
message2.CopyFrom(*message1);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldTest, DynamicMessageMergeFromDynamicMessage) {
// Construct two dynamic message and sets via map reflection.
DynamicMessageFactory factory;
std::unique_ptr<Message> message1;
message1.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaMapReflection(message1.get());
// message2 is created by same factory.
std::unique_ptr<Message> message2;
message2.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
reflection_tester.SetMapFieldsViaMapReflection(message2.get());
// message3 is created by different factory.
DynamicMessageFactory factory3;
std::unique_ptr<Message> message3;
message3.reset(factory3.GetPrototype(UNITTEST::TestMap::descriptor())->New());
reflection_tester.SetMapFieldsViaMapReflection(message3.get());
message2->MergeFrom(*message1);
message3->MergeFrom(*message1);
// Test MergeFrom does not sync to repeated fields and
// there is no duplicate keys in text format.
std::string output1, output2, output3;
TextFormat::PrintToString(*message1, &output1);
TextFormat::PrintToString(*message2, &output2);
TextFormat::PrintToString(*message3, &output3);
EXPECT_EQ(output1, output2);
EXPECT_EQ(output1, output3);
}
TEST(GeneratedMapFieldTest, DynamicMessageCopyFrom) {
// Test copying to a DynamicMessage, which must fall back to using reflection.
UNITTEST::TestMap message2;
MapTestUtil::SetMapFields(&message2);
// Construct a new version of the dynamic message via the factory.
DynamicMessageFactory factory;
std::unique_ptr<Message> message1;
message1.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
message1->MergeFrom(message2);
reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
}
TEST(GeneratedMapFieldTest, DynamicMessageCopyFromMapReflection) {
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
UNITTEST::TestMap message2;
reflection_tester.SetMapFieldsViaMapReflection(&message2);
// Construct a dynamic message via the factory.
DynamicMessageFactory factory;
std::unique_ptr<Message> message1;
message1.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
message1->MergeFrom(message2);
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
}
TEST(GeneratedMapFieldTest, SyncDynamicMapWithRepeatedField) {
// Construct a dynamic message via the factory.
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
DynamicMessageFactory factory;
std::unique_ptr<Message> message;
message.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
reflection_tester.SetMapFieldsViaReflection(message.get());
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*message);
}
#endif // !PROTOBUF_TEST_NO_DESCRIPTORS
TEST(GeneratedMapFieldTest, NonEmptyMergeFrom) {
UNITTEST::TestMap message1, message2;
MapTestUtil::SetMapFields(&message1);
// This field will test merging into an empty spot.
(*message2.mutable_map_int32_int32())[1] = 1;
message1.mutable_map_int32_int32()->erase(1);
// This tests overwriting.
(*message2.mutable_map_int32_double())[1] = 1;
(*message1.mutable_map_int32_double())[1] = 2;
message1.MergeFrom(message2);
MapTestUtil::ExpectMapFieldsSet(message1);
// Test reflection MergeFrom does not sync to repeated field
// and there is no duplicated keys.
MapTestUtil::SetMapFields(&message1);
MapTestUtil::SetMapFields(&message2);
message2.MergeFrom(message1);
std::string output1, output2;
TextFormat::PrintToString(message1, &output1);
TextFormat::PrintToString(message2, &output2);
EXPECT_EQ(output1, output2);
}
TEST(GeneratedMapFieldTest, MergeFromMessageMap) {
UNITTEST::TestMessageMap message1, message2;
(*message1.mutable_map_int32_message())[0].add_repeated_int32(100);
(*message2.mutable_map_int32_message())[0].add_repeated_int32(101);
message1.MergeFrom(message2);
// Checks repeated field is overwritten.
EXPECT_EQ(1, message1.map_int32_message().at(0).repeated_int32_size());
EXPECT_EQ(101, message1.map_int32_message().at(0).repeated_int32(0));
}
// Test the generated SerializeWithCachedSizesToArray()
TEST(GeneratedMapFieldTest, SerializationToArray) {
UNITTEST::TestMap message1, message2;
std::string data;
MapTestUtil::SetMapFields(&message1);
size_t size = message1.ByteSizeLong();
data.resize(size);
uint8* start = reinterpret_cast<uint8*>(::google::protobuf::string_as_array(&data));
uint8* end = message1.SerializeWithCachedSizesToArray(start);
EXPECT_EQ(size, end - start);
EXPECT_TRUE(message2.ParseFromString(data));
MapTestUtil::ExpectMapFieldsSet(message2);
}
// Test the generated SerializeWithCachedSizes()
TEST(GeneratedMapFieldTest, SerializationToStream) {
UNITTEST::TestMap message1, message2;
MapTestUtil::SetMapFields(&message1);
size_t size = message1.ByteSizeLong();
std::string data;
data.resize(size);
{
// Allow the output stream to buffer only one byte at a time.
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&data), size, 1);
io::CodedOutputStream output_stream(&array_stream);
message1.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
EXPECT_EQ(size, output_stream.ByteCount());
}
EXPECT_TRUE(message2.ParseFromString(data));
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldTest, ParseFailsIfMalformed) {
UNITTEST::TestMapSubmessage o, p;
auto m = o.mutable_test_map()->mutable_map_int32_foreign_message();
(*m)[0].set_c(-1);
std::string serialized;
EXPECT_TRUE(o.SerializeToString(&serialized));
// Should parse correctly.
EXPECT_TRUE(p.ParseFromString(serialized));
// Overwriting the last byte to 0xFF results in malformed wire.
serialized[serialized.size() - 1] = 0xFF;
EXPECT_FALSE(p.ParseFromString(serialized));
}
TEST(GeneratedMapFieldTest, SameTypeMaps) {
const Descriptor* map1 = UNITTEST::TestSameTypeMap::descriptor()
->FindFieldByName("map1")
->message_type();
const Descriptor* map2 = UNITTEST::TestSameTypeMap::descriptor()
->FindFieldByName("map2")
->message_type();
const Message* map1_entry =
MessageFactory::generated_factory()->GetPrototype(map1);
const Message* map2_entry =
MessageFactory::generated_factory()->GetPrototype(map2);
EXPECT_EQ(map1, map1_entry->GetDescriptor());
EXPECT_EQ(map2, map2_entry->GetDescriptor());
}
TEST(GeneratedMapFieldTest, Proto2UnknownEnum) {
UNITTEST::TestEnumMapPlusExtra from;
(*from.mutable_known_map_field())[0] = UNITTEST::E_PROTO2_MAP_ENUM_FOO;
(*from.mutable_unknown_map_field())[0] = UNITTEST::E_PROTO2_MAP_ENUM_EXTRA;
std::string data;
from.SerializeToString(&data);
UNITTEST::TestEnumMap to;
EXPECT_TRUE(to.ParseFromString(data));
EXPECT_EQ(0, to.unknown_map_field().size());
const UnknownFieldSet& unknown_field_set =
to.GetReflection()->GetUnknownFields(to);
EXPECT_EQ(1, unknown_field_set.field_count());
EXPECT_EQ(1, to.known_map_field().size());
EXPECT_EQ(UNITTEST::PROTO2_MAP_ENUM_FOO, to.known_map_field().at(0));
data.clear();
from.Clear();
to.SerializeToString(&data);
EXPECT_TRUE(from.ParseFromString(data));
EXPECT_EQ(0, from.GetReflection()->GetUnknownFields(from).field_count());
EXPECT_EQ(1, from.known_map_field().size());
EXPECT_EQ(UNITTEST::E_PROTO2_MAP_ENUM_FOO, from.known_map_field().at(0));
EXPECT_EQ(1, from.unknown_map_field().size());
EXPECT_EQ(UNITTEST::E_PROTO2_MAP_ENUM_EXTRA, from.unknown_map_field().at(0));
}
TEST(GeneratedMapFieldTest, StandardWireFormat) {
UNITTEST::TestMap message;
std::string data = "\x0A\x04\x08\x01\x10\x01";
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(1));
}
TEST(GeneratedMapFieldTest, UnorderedWireFormat) {
UNITTEST::TestMap message;
// put value before key in wire format
std::string data = "\x0A\x04\x10\x01\x08\x02";
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
ASSERT_NE(message.map_int32_int32().find(2), message.map_int32_int32().end());
EXPECT_EQ(1, message.map_int32_int32().at(2));
}
TEST(GeneratedMapFieldTest, DuplicatedKeyWireFormat) {
UNITTEST::TestMap message;
// Two key fields in wire format
std::string data = "\x0A\x06\x08\x01\x08\x02\x10\x01";
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(1, message.map_int32_int32().at(2));
// A similar test, but with a map from int to a message type.
// Again, we want to be sure that the "second one wins" when
// there are two separate entries with the same key.
const int key = 99;
UNITTEST::TestRequiredMessageMap map_message;
UNITTEST::TestRequired with_dummy4;
with_dummy4.set_a(0);
with_dummy4.set_b(0);
with_dummy4.set_c(0);
with_dummy4.set_dummy4(11);
(*map_message.mutable_map_field())[key] = with_dummy4;
std::string s = map_message.SerializeAsString();
UNITTEST::TestRequired with_dummy5;
with_dummy5.set_a(0);
with_dummy5.set_b(0);
with_dummy5.set_c(0);
with_dummy5.set_dummy5(12);
(*map_message.mutable_map_field())[key] = with_dummy5;
std::string both = s + map_message.SerializeAsString();
// We don't expect a merge now. The "second one wins."
ASSERT_TRUE(map_message.ParseFromString(both));
ASSERT_EQ(1, map_message.map_field().size());
ASSERT_EQ(1, map_message.map_field().count(key));
EXPECT_EQ(0, map_message.map_field().find(key)->second.a());
EXPECT_EQ(0, map_message.map_field().find(key)->second.b());
EXPECT_EQ(0, map_message.map_field().find(key)->second.c());
EXPECT_FALSE(map_message.map_field().find(key)->second.has_dummy4());
ASSERT_TRUE(map_message.map_field().find(key)->second.has_dummy5());
EXPECT_EQ(12, map_message.map_field().find(key)->second.dummy5());
}
// Exhaustive combinations of keys, values, and junk in any order.
// This re-tests some of the things tested above, but if it fails
// it's more work to determine what went wrong, so it isn't necessarily
// bad that we have the simpler tests too.
TEST(GeneratedMapFieldTest, KeysValuesUnknownsWireFormat) {
UNITTEST::TestMap message;
const int kMaxNumKeysAndValuesAndJunk = 4;
const char kKeyTag = 0x08;
const char kValueTag = 0x10;
const char kJunkTag = 0x20;
for (int items = 0; items <= kMaxNumKeysAndValuesAndJunk; items++) {
std::string data = "\x0A";
// Encode length of what will follow.
data.push_back(items * 2);
static const int kBitsOfIPerItem = 4;
static const int mask = (1 << kBitsOfIPerItem) - 1;
// Each iteration of the following is a test. It uses i as bit vector
// encoding the keys and values to put in the wire format.
for (int i = 0; i < (1 << (items * kBitsOfIPerItem)); i++) {
std::string wire_format = data;
int expected_key = 0;
int expected_value = 0;
for (int k = i, j = 0; j < items; j++, k >>= kBitsOfIPerItem) {
bool is_key = k & 0x1;
bool is_value = !is_key && (k & 0x2);
wire_format.push_back(is_key ? kKeyTag
: is_value ? kValueTag : kJunkTag);
char c = static_cast<char>(k & mask) >> 2; // One char after the tag.
wire_format.push_back(c);
if (is_key) expected_key = static_cast<int>(c);
if (is_value) expected_value = static_cast<int>(c);
bool res = message.ParseFromString(wire_format);
bool expect_success = true;
// Unfortunately the old map parser accepts malformed input, the new
// parser accepts only correct input.
if (j != items - 1) expect_success = false;
if (expect_success) {
ASSERT_TRUE(res);
ASSERT_EQ(1, message.map_int32_int32().size());
ASSERT_EQ(expected_key, message.map_int32_int32().begin()->first);
ASSERT_EQ(expected_value, message.map_int32_int32().begin()->second);
} else {
ASSERT_FALSE(res);
}
}
}
}
}
TEST(GeneratedMapFieldTest, DuplicatedValueWireFormat) {
UNITTEST::TestMap message;
// Two value fields in wire format
std::string data = "\x0A\x06\x08\x01\x10\x01\x10\x02";
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(2, message.map_int32_int32().at(1));
}
TEST(GeneratedMapFieldTest, MissedKeyWireFormat) {
UNITTEST::TestMap message;
// No key field in wire format
std::string data = "\x0A\x02\x10\x01";
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
ASSERT_NE(message.map_int32_int32().find(0), message.map_int32_int32().end());
EXPECT_EQ(1, message.map_int32_int32().at(0));
}
TEST(GeneratedMapFieldTest, MissedValueWireFormat) {
UNITTEST::TestMap message;
// No value field in wire format
std::string data = "\x0A\x02\x08\x01";
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
ASSERT_NE(message.map_int32_int32().find(1), message.map_int32_int32().end());
EXPECT_EQ(0, message.map_int32_int32().at(1));
}
TEST(GeneratedMapFieldTest, MissedValueTextFormat) {
UNITTEST::TestMap message;
// No value field in text format
std::string text =
"map_int32_foreign_message {\n"
" key: 1234567890\n"
"}";
EXPECT_TRUE(TextFormat::ParseFromString(text, &message));
EXPECT_EQ(1, message.map_int32_foreign_message().size());
EXPECT_EQ(11, message.ByteSizeLong());
}
TEST(GeneratedMapFieldTest, UnknownFieldWireFormat) {
UNITTEST::TestMap message;
// Unknown field in wire format
std::string data = "\x0A\x06\x08\x02\x10\x03\x18\x01";
EXPECT_TRUE(message.ParseFromString(data));
EXPECT_EQ(1, message.map_int32_int32().size());
EXPECT_EQ(3, message.map_int32_int32().at(2));
}
TEST(GeneratedMapFieldTest, CorruptedWireFormat) {
UNITTEST::TestMap message;
// corrupted data in wire format
std::string data = "\x0A\x06\x08\x02\x11\x03";
EXPECT_FALSE(message.ParseFromString(data));
}
TEST(GeneratedMapFieldTest, IsInitialized) {
UNITTEST::TestRequiredMessageMap map_message;
// Add an uninitialized message.
(*map_message.mutable_map_field())[0];
EXPECT_FALSE(map_message.IsInitialized());
// Initialize uninitialized message
(*map_message.mutable_map_field())[0].set_a(0);
(*map_message.mutable_map_field())[0].set_b(0);
(*map_message.mutable_map_field())[0].set_c(0);
EXPECT_TRUE(map_message.IsInitialized());
}
TEST(GeneratedMapFieldTest, SpaceUsed) {
UNITTEST::TestRequiredMessageMap map_message;
const size_t initial = map_message.SpaceUsed();
const size_t space_used_message = UNITTEST::TestRequired().SpaceUsed();
auto& m = *map_message.mutable_map_field();
constexpr int kNumValues = 100;
for (int i = 0; i < kNumValues; ++i) {
m[i];
}
// The exact value will depend on internal state, like collisions,
// so we can't predict it. But we can predict a lower bound.
size_t lower_bound =
initial + kNumValues * (space_used_message + sizeof(int32) +
/* Node::next */ sizeof(void*) +
/* table entry */ sizeof(void*));
EXPECT_LE(lower_bound, map_message.SpaceUsed());
}
TEST(GeneratedMapFieldTest, MessagesMustMerge) {
UNITTEST::TestRequiredMessageMap map_message;
UNITTEST::TestRequired with_dummy4;
with_dummy4.set_a(97);
with_dummy4.set_b(91);
with_dummy4.set_dummy4(98);
EXPECT_FALSE(with_dummy4.IsInitialized());
(*map_message.mutable_map_field())[0] = with_dummy4;
EXPECT_FALSE(map_message.IsInitialized());
UNITTEST::TestRequired with_dummy5;
with_dummy5.set_b(0);
with_dummy5.set_c(33);
with_dummy5.set_dummy5(99);
EXPECT_FALSE(with_dummy5.IsInitialized());
(*map_message.mutable_map_field())[0] = with_dummy5;
EXPECT_FALSE(map_message.IsInitialized());
// The wire format of MapEntry is straightforward (*) and can be manually
// constructed to force merging of two uninitialized messages that would
// result in an initialized message.
//
// (*) http://google3/net/proto2/internal/map_test.cc?l=2433&rcl=310012028
std::string dummy4_s = with_dummy4.SerializePartialAsString();
std::string dummy5_s = with_dummy5.SerializePartialAsString();
int payload_size = dummy4_s.size() + dummy5_s.size();
// Makes sure the payload size fits into one byte.
ASSERT_LT(payload_size, 128);
std::string s(6, 0);
char* p = &s[0];
*p++ = WireFormatLite::MakeTag(1, WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
// Length: 2B for key tag & val and 2B for val tag and length of the following
// payload.
*p++ = 4 + payload_size;
*p++ = WireFormatLite::MakeTag(1, WireFormatLite::WIRETYPE_VARINT);
*p++ = 0;
*p++ = WireFormatLite::MakeTag(2, WireFormatLite::WIRETYPE_LENGTH_DELIMITED);
*p++ = payload_size;
StrAppend(&s, dummy4_s, dummy5_s);
// Test key then value then value.
int key = 0;
ASSERT_TRUE(map_message.ParseFromString(s));
ASSERT_EQ(1, map_message.map_field().size());
ASSERT_EQ(1, map_message.map_field().count(key));
EXPECT_EQ(97, map_message.map_field().find(key)->second.a());
EXPECT_EQ(0, map_message.map_field().find(key)->second.b());
EXPECT_EQ(33, map_message.map_field().find(key)->second.c());
EXPECT_EQ(98, map_message.map_field().find(key)->second.dummy4());
EXPECT_EQ(99, map_message.map_field().find(key)->second.dummy5());
// Test key then value then value then key.
s.push_back(s[2]); // Copy the key's tag.
key = 19;
s.push_back(key); // Second key is 19 instead of 0.
s[1] += 2; // Adjust encoded size.
ASSERT_TRUE(map_message.ParseFromString(s));
ASSERT_EQ(1, map_message.map_field().size());
ASSERT_EQ(1, map_message.map_field().count(key));
EXPECT_EQ(97, map_message.map_field().find(key)->second.a());
EXPECT_EQ(0, map_message.map_field().find(key)->second.b());
EXPECT_EQ(33, map_message.map_field().find(key)->second.c());
EXPECT_EQ(98, map_message.map_field().find(key)->second.dummy4());
EXPECT_EQ(99, map_message.map_field().find(key)->second.dummy5());
}
// Generated Message Reflection Test ================================
TEST(GeneratedMapFieldReflectionTest, SpaceUsed) {
UNITTEST::TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaReflection(&message);
EXPECT_LT(0, message.GetReflection()->SpaceUsedLong(message));
}
TEST(GeneratedMapFieldReflectionTest, Accessors) {
// Set every field to a unique value then go back and check all those
// values.
UNITTEST::TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaReflection(&message);
MapTestUtil::ExpectMapFieldsSet(message);
reflection_tester.ExpectMapFieldsSetViaReflection(message);
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(&message);
reflection_tester.ModifyMapFieldsViaReflection(&message);
MapTestUtil::ExpectMapFieldsModified(message);
}
TEST(GeneratedMapFieldReflectionTest, Swap) {
UNITTEST::TestMap message1;
UNITTEST::TestMap message2;
MapTestUtil::SetMapFields(&message1);
const Reflection* reflection = message1.GetReflection();
reflection->Swap(&message1, &message2);
MapTestUtil::ExpectClear(message1);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldReflectionTest, SwapWithBothSet) {
UNITTEST::TestMap message1;
UNITTEST::TestMap message2;
MapTestUtil::SetMapFields(&message1);
MapTestUtil::SetMapFields(&message2);
MapTestUtil::ModifyMapFields(&message2);
const Reflection* reflection = message1.GetReflection();
reflection->Swap(&message1, &message2);
MapTestUtil::ExpectMapFieldsModified(message1);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(GeneratedMapFieldReflectionTest, SwapFields) {
UNITTEST::TestMap message1;
UNITTEST::TestMap message2;
MapTestUtil::SetMapFields(&message2);
std::vector<const FieldDescriptor*> fields;
const Reflection* reflection = message1.GetReflection();
reflection->ListFields(message2, &fields);
reflection->SwapFields(&message1, &message2, fields);
MapTestUtil::ExpectMapFieldsSet(message1);
MapTestUtil::ExpectClear(message2);
}
TEST(GeneratedMapFieldReflectionTest, ClearField) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
MapTestUtil::ExpectMapFieldsSet(message);
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.ClearMapFieldsViaReflection(&message);
reflection_tester.ExpectClearViaReflection(message);
reflection_tester.ExpectClearViaReflectionIterator(&message);
}
TEST(GeneratedMapFieldReflectionTest, RemoveLast) {
UNITTEST::TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
MapTestUtil::SetMapFields(&message);
MapTestUtil::ExpectMapsSize(message, 2);
std::vector<const Message*> expected_entries =
MapTestUtil::GetMapEntries(message, 0);
reflection_tester.RemoveLastMapsViaReflection(&message);
MapTestUtil::ExpectMapsSize(message, 1);
std::vector<const Message*> remained_entries =
MapTestUtil::GetMapEntries(message, 0);
EXPECT_TRUE(expected_entries == remained_entries);
}
TEST(GeneratedMapFieldReflectionTest, ReleaseLast) {
UNITTEST::TestMap message;
const Descriptor* descriptor = message.GetDescriptor();
MapReflectionTester reflection_tester(descriptor);
MapTestUtil::SetMapFields(&message);
MapTestUtil::ExpectMapsSize(message, 2);
reflection_tester.ReleaseLastMapsViaReflection(&message);
MapTestUtil::ExpectMapsSize(message, 1);
// Now test that we actually release the right message.
message.Clear();
MapTestUtil::SetMapFields(&message);
MapTestUtil::ExpectMapsSize(message, 2);
std::vector<const Message*> expect_last =
MapTestUtil::GetMapEntries(message, 1);
std::vector<const Message*> release_last =
MapTestUtil::GetMapEntriesFromRelease(&message);
MapTestUtil::ExpectMapsSize(message, 1);
EXPECT_TRUE(expect_last == release_last);
for (std::vector<const Message*>::iterator it = release_last.begin();
it != release_last.end(); ++it) {
delete *it;
}
}
TEST(GeneratedMapFieldReflectionTest, SwapElements) {
UNITTEST::TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
MapTestUtil::SetMapFields(&message);
// Get pointers of map entries at their original position
std::vector<const Message*> entries0 = MapTestUtil::GetMapEntries(message, 0);
std::vector<const Message*> entries1 = MapTestUtil::GetMapEntries(message, 1);
// Swap the first time.
reflection_tester.SwapMapsViaReflection(&message);
// Get pointer of map entry after swap once.
std::vector<const Message*> entries0_once =
MapTestUtil::GetMapEntries(message, 0);
std::vector<const Message*> entries1_once =
MapTestUtil::GetMapEntries(message, 1);
// Test map entries are swapped.
MapTestUtil::ExpectMapsSize(message, 2);
EXPECT_TRUE(entries0 == entries1_once);
EXPECT_TRUE(entries1 == entries0_once);
// Swap the second time.
reflection_tester.SwapMapsViaReflection(&message);
// Get pointer of map entry after swap once.
std::vector<const Message*> entries0_twice =
MapTestUtil::GetMapEntries(message, 0);
std::vector<const Message*> entries1_twice =
MapTestUtil::GetMapEntries(message, 1);
// Test map entries are swapped back.
MapTestUtil::ExpectMapsSize(message, 2);
EXPECT_TRUE(entries0 == entries0_twice);
EXPECT_TRUE(entries1 == entries1_twice);
}
TEST(GeneratedMapFieldReflectionTest, MutableUnknownFields) {
UNITTEST::TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message);
}
TEST(GeneratedMapFieldReflectionTest, EmbedProto2Message) {
UNITTEST::TestMessageMap message;
const FieldDescriptor* map_field =
UNITTEST::TestMessageMap::descriptor()->FindFieldByName(
"map_int32_message");
const FieldDescriptor* value =
map_field->message_type()->FindFieldByName("value");
Message* entry_message =
message.GetReflection()->AddMessage(&message, map_field);
EXPECT_EQ(
&entry_message->GetReflection()->GetMessage(*entry_message, value),
reinterpret_cast<const Message*>(&TestAllTypes::default_instance()));
Message* proto2_message =
entry_message->GetReflection()->MutableMessage(entry_message, value);
EXPECT_EQ(UNITTEST::TestAllTypes::descriptor(),
proto2_message->GetDescriptor());
ASSERT_EQ(1, message.map_int32_message().size());
}
TEST(GeneratedMapFieldReflectionTest, MergeFromClearMapEntry) {
UNITTEST::TestMap message;
const FieldDescriptor* map_field =
UNITTEST::TestMap::descriptor()->FindFieldByName("map_int32_int32");
const FieldDescriptor* key =
map_field->message_type()->FindFieldByName("key");
const FieldDescriptor* value =
map_field->message_type()->FindFieldByName("value");
Message* entry_message1 =
message.GetReflection()->AddMessage(&message, map_field);
EXPECT_FALSE(entry_message1->GetReflection()->HasField(*entry_message1, key));
EXPECT_FALSE(
entry_message1->GetReflection()->HasField(*entry_message1, value));
Message* entry_message2 =
message.GetReflection()->AddMessage(&message, map_field);
EXPECT_FALSE(entry_message2->GetReflection()->HasField(*entry_message2, key));
EXPECT_FALSE(
entry_message2->GetReflection()->HasField(*entry_message2, value));
entry_message1->MergeFrom(*entry_message2);
EXPECT_FALSE(entry_message1->GetReflection()->HasField(*entry_message1, key));
EXPECT_FALSE(
entry_message1->GetReflection()->HasField(*entry_message1, value));
}
TEST(GeneratedMapFieldReflectionTest, MapEntryClear) {
UNITTEST::TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.MutableUnknownFieldsOfMapFieldsViaReflection(&message);
}
TEST(GeneratedMapFieldReflectionTest, Proto2MapEntryClear) {
UNITTEST::TestEnumMap message;
const Descriptor* descriptor = message.GetDescriptor();
const FieldDescriptor* field_descriptor =
descriptor->FindFieldByName("known_map_field");
const FieldDescriptor* value_descriptor =
field_descriptor->message_type()->FindFieldByName("value");
Message* sub_message =
message.GetReflection()->AddMessage(&message, field_descriptor);
EXPECT_EQ(0, sub_message->GetReflection()->GetEnumValue(*sub_message,
value_descriptor));
}
// Map Reflection API Test =========================================
TEST(GeneratedMapFieldReflectionTest, SetViaMapReflection) {
UNITTEST::TestMap message;
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaMapReflection(&message);
reflection_tester.ExpectMapFieldsSetViaReflection(message);
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(&message);
}
// Dynamic Message Test =============================================
class MapFieldInDynamicMessageTest : public testing::Test {
protected:
const DescriptorPool* pool_;
DynamicMessageFactory factory_;
const Descriptor* map_descriptor_;
const Descriptor* recursive_map_descriptor_;
const Message* map_prototype_;
MapFieldInDynamicMessageTest()
: pool_(DescriptorPool::generated_pool()), factory_(pool_) {}
virtual void SetUp() {
map_descriptor_ = pool_->FindMessageTypeByName(
std::string(UNITTEST_PACKAGE_NAME) + ".TestMap");
recursive_map_descriptor_ = pool_->FindMessageTypeByName(
std::string(UNITTEST_PACKAGE_NAME) + ".TestRecursiveMapMessage");
ASSERT_TRUE(map_descriptor_ != nullptr);
ASSERT_TRUE(recursive_map_descriptor_ != nullptr);
map_prototype_ = factory_.GetPrototype(map_descriptor_);
}
};
TEST_F(MapFieldInDynamicMessageTest, MapIndependentOffsets) {
// Check that all fields have independent offsets by setting each
// one to a unique value then checking that they all still have those
// unique values (i.e. they don't stomp each other).
std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
reflection_tester.SetMapFieldsViaReflection(message.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*message);
}
TEST_F(MapFieldInDynamicMessageTest, DynamicMapReflection) {
// Check that map fields work properly.
std::unique_ptr<Message> message(map_prototype_->New());
// Check set functions.
MapReflectionTester reflection_tester(map_descriptor_);
reflection_tester.SetMapFieldsViaMapReflection(message.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*message);
}
TEST_F(MapFieldInDynamicMessageTest, MapSpaceUsed) {
// Test that SpaceUsedLong() works properly
// Since we share the implementation with generated messages, we don't need
// to test very much here. Just make sure it appears to be working.
std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
int initial_space_used = message->SpaceUsedLong();
reflection_tester.SetMapFieldsViaReflection(message.get());
EXPECT_LT(initial_space_used, message->SpaceUsedLong());
}
TEST_F(MapFieldInDynamicMessageTest, RecursiveMap) {
TestRecursiveMapMessage from;
(*from.mutable_a())[""];
std::string data = from.SerializeAsString();
std::unique_ptr<Message> to(
factory_.GetPrototype(recursive_map_descriptor_)->New());
ASSERT_TRUE(to->ParseFromString(data));
}
TEST_F(MapFieldInDynamicMessageTest, MapValueReferernceValidAfterSerialize) {
std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
reflection_tester.SetMapFieldsViaMapReflection(message.get());
// Get value reference before serialization, so that we know the value is from
// map.
MapKey map_key;
MapValueRef map_val;
map_key.SetInt32Value(0);
reflection_tester.GetMapValueViaMapReflection(
message.get(), "map_int32_foreign_message", map_key, &map_val);
Message* submsg = map_val.MutableMessageValue();
// In previous implementation, calling SerializeToString will cause syncing
// from map to repeated field, which will invalidate the submsg we previously
// got.
std::string data;
message->SerializeToString(&data);
const Reflection* submsg_reflection = submsg->GetReflection();
const Descriptor* submsg_desc = submsg->GetDescriptor();
const FieldDescriptor* submsg_field = submsg_desc->FindFieldByName("c");
submsg_reflection->SetInt32(submsg, submsg_field, 128);
message->SerializeToString(&data);
TestMap to;
to.ParseFromString(data);
EXPECT_EQ(128, to.map_int32_foreign_message().at(0).c());
}
TEST_F(MapFieldInDynamicMessageTest, MapEntryReferernceValidAfterSerialize) {
std::unique_ptr<Message> message(map_prototype_->New());
MapReflectionTester reflection_tester(map_descriptor_);
reflection_tester.SetMapFieldsViaReflection(message.get());
// Get map entry before serialization, so that we know the it is from
// repeated field.
Message* map_entry = reflection_tester.GetMapEntryViaReflection(
message.get(), "map_int32_foreign_message", 0);
const Reflection* map_entry_reflection = map_entry->GetReflection();
const Descriptor* map_entry_desc = map_entry->GetDescriptor();
const FieldDescriptor* value_field = map_entry_desc->FindFieldByName("value");
Message* submsg =
map_entry_reflection->MutableMessage(map_entry, value_field);
// In previous implementation, calling SerializeToString will cause syncing
// from repeated field to map, which will invalidate the map_entry we
// previously got.
std::string data;
message->SerializeToString(&data);
const Reflection* submsg_reflection = submsg->GetReflection();
const Descriptor* submsg_desc = submsg->GetDescriptor();
const FieldDescriptor* submsg_field = submsg_desc->FindFieldByName("c");
submsg_reflection->SetInt32(submsg, submsg_field, 128);
message->SerializeToString(&data);
TestMap to;
to.ParseFromString(data);
EXPECT_EQ(128, to.map_int32_foreign_message().at(0).c());
}
// ReflectionOps Test ===============================================
TEST(ReflectionOpsForMapFieldTest, MapSanityCheck) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
MapTestUtil::ExpectMapFieldsSet(message);
}
TEST(ReflectionOpsForMapFieldTest, MapCopy) {
UNITTEST::TestMap message, message2;
MapTestUtil::SetMapFields(&message);
ReflectionOps::Copy(message, &message2);
MapTestUtil::ExpectMapFieldsSet(message2);
// Copying from self should be a no-op.
ReflectionOps::Copy(message2, &message2);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(ReflectionOpsForMapFieldTest, MergeMap) {
// Note: Copy is implemented in terms of Merge() so technically the Copy
// test already tested most of this.
UNITTEST::TestMap message, message2;
MapTestUtil::SetMapFields(&message);
ReflectionOps::Merge(message2, &message);
MapTestUtil::ExpectMapFieldsSet(message);
}
TEST(ReflectionOpsForMapFieldTest, ClearMap) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
ReflectionOps::Clear(&message);
MapTestUtil::ExpectClear(message);
}
TEST(ReflectionOpsForMapFieldTest, MapDiscardUnknownFields) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
// Set some unknown fields in message.
message.GetReflection()->MutableUnknownFields(&message)->AddVarint(123456,
654321);
// Discard them.
ReflectionOps::DiscardUnknownFields(&message);
MapTestUtil::ExpectMapFieldsSet(message);
EXPECT_EQ(0,
message.GetReflection()->GetUnknownFields(message).field_count());
}
TEST(ReflectionOpsForMapFieldTest, IsInitialized) {
UNITTEST::TestRequiredMessageMap map_message;
// Add an uninitialized message.
(*map_message.mutable_map_field())[0];
EXPECT_FALSE(ReflectionOps::IsInitialized(map_message));
// Initialize uninitialized message
(*map_message.mutable_map_field())[0].set_a(0);
(*map_message.mutable_map_field())[0].set_b(0);
(*map_message.mutable_map_field())[0].set_c(0);
EXPECT_TRUE(ReflectionOps::IsInitialized(map_message));
}
// Wire Format Test =================================================
TEST(WireFormatForMapFieldTest, ParseMap) {
UNITTEST::TestMap source, dest;
std::string data;
// Serialize using the generated code.
MapTestUtil::SetMapFields(&source);
source.SerializeToString(&data);
// Parse using WireFormat.
io::ArrayInputStream raw_input(data.data(), data.size());
io::CodedInputStream input(&raw_input);
WireFormat::ParseAndMergePartial(&input, &dest);
// Check.
MapTestUtil::ExpectMapFieldsSet(dest);
}
TEST(WireFormatForMapFieldTest, MapByteSize) {
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
EXPECT_EQ(message.ByteSizeLong(), WireFormat::ByteSize(message));
message.Clear();
EXPECT_EQ(0, message.ByteSizeLong());
EXPECT_EQ(0, WireFormat::ByteSize(message));
}
TEST(WireFormatForMapFieldTest, SerializeMap) {
UNITTEST::TestMap message;
std::string generated_data;
std::string dynamic_data;
MapTestUtil::SetMapFields(&message);
// Serialize using the generated code.
{
message.ByteSizeLong();
io::StringOutputStream raw_output(&generated_data);
io::CodedOutputStream output(&raw_output);
message.SerializeWithCachedSizes(&output);
ASSERT_FALSE(output.HadError());
}
// Serialize using WireFormat.
{
io::StringOutputStream raw_output(&dynamic_data);
io::CodedOutputStream output(&raw_output);
size_t size = WireFormat::ByteSize(message);
WireFormat::SerializeWithCachedSizes(message, size, &output);
ASSERT_FALSE(output.HadError());
}
// Should parse to the same message.
EXPECT_TRUE(TestUtil::EqualsToSerialized(message, generated_data));
EXPECT_TRUE(TestUtil::EqualsToSerialized(message, dynamic_data));
}
TEST(WireFormatForMapFieldTest, SerializeMapDynamicMessage) {
DynamicMessageFactory factory;
std::unique_ptr<Message> dynamic_message;
dynamic_message.reset(
factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaReflection(dynamic_message.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*dynamic_message);
UNITTEST::TestMap generated_message;
MapTestUtil::SetMapFields(&generated_message);
MapTestUtil::ExpectMapFieldsSet(generated_message);
std::string generated_data;
std::string dynamic_data;
// Serialize.
generated_message.SerializeToString(&generated_data);
dynamic_message->SerializeToString(&dynamic_data);
// Because map serialization doesn't guarantee order, we just compare
// serialized size here. This is enough to tell dynamic message doesn't miss
// anything in serialization.
EXPECT_TRUE(dynamic_data.size() == generated_data.size());
}
TEST(WireFormatForMapFieldTest, MapByteSizeDynamicMessage) {
DynamicMessageFactory factory;
std::unique_ptr<Message> dynamic_message;
dynamic_message.reset(
factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaReflection(dynamic_message.get());
reflection_tester.ExpectMapFieldsSetViaReflection(*dynamic_message);
std::string expected_serialized_data;
dynamic_message->SerializeToString(&expected_serialized_data);
int expected_size = expected_serialized_data.size();
EXPECT_EQ(dynamic_message->ByteSizeLong(), expected_size);
TestMap expected_message;
expected_message.ParseFromString(expected_serialized_data);
std::unique_ptr<Message> message2;
message2.reset(factory.GetPrototype(UNITTEST::TestMap::descriptor())->New());
reflection_tester.SetMapFieldsViaMapReflection(message2.get());
const FieldDescriptor* field =
UNITTEST::TestMap::descriptor()->FindFieldByName("map_int32_int32");
const Reflection* reflection = dynamic_message->GetReflection();
// Force the map field to mark with STATE_MODIFIED_REPEATED
reflection->RemoveLast(dynamic_message.get(), field);
dynamic_message->MergeFrom(*message2);
dynamic_message->MergeFrom(*message2);
// The map field is marked as STATE_MODIFIED_REPEATED, ByteSizeLong() will use
// repeated field which have duplicate keys to calculate.
size_t duplicate_size = dynamic_message->ByteSizeLong();
EXPECT_TRUE(duplicate_size > expected_size);
std::string duplicate_serialized_data;
dynamic_message->SerializeToString(&duplicate_serialized_data);
EXPECT_EQ(dynamic_message->ByteSizeLong(), duplicate_serialized_data.size());
// Force the map field to mark with map CLEAN
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_int32_int32"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_int32_int32"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_int64_int64"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_uint32_uint32"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_uint64_uint64"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_sint32_sint32"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_sint64_sint64"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_fixed32_fixed32"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_fixed64_fixed64"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_sfixed32_sfixed32"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_sfixed64_sfixed64"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_int32_float"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_int32_double"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_bool_bool"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_string_string"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_int32_bytes"), 2);
EXPECT_EQ(reflection_tester.MapSize(
*dynamic_message, "map_int32_enum"), 2);
EXPECT_EQ(reflection_tester.MapSize(*dynamic_message, "map_int32_foreign_message"), 2);
// The map field is marked as CLEAN, ByteSizeLong() will use map which do not
// have duplicate keys to calculate.
int size = dynamic_message->ByteSizeLong();
EXPECT_EQ(expected_size, size);
// Protobuf used to have a bug for serialize when map it marked CLEAN. It used
// repeated field to calculate ByteSizeLong but use map to serialize the real
// data, thus the ByteSizeLong may bigger than real serialized size. A crash
// might be happen at SerializeToString(). Or an "unexpected end group"
// warning was raised at parse back if user use SerializeWithCachedSizes()
// which avoids size check at serialize.
std::string serialized_data;
dynamic_message->SerializeToString(&serialized_data);
EXPECT_TRUE(dynamic_message->ParseFromString(serialized_data));
}
TEST(WireFormatForMapFieldTest, MapParseHelpers) {
std::string data;
{
// Set up.
UNITTEST::TestMap message;
MapTestUtil::SetMapFields(&message);
message.SerializeToString(&data);
}
{
// Test ParseFromString.
UNITTEST::TestMap message;
EXPECT_TRUE(message.ParseFromString(data));
MapTestUtil::ExpectMapFieldsSet(message);
}
{
// Test ParseFromIstream.
UNITTEST::TestMap message;
std::stringstream stream(data);
EXPECT_TRUE(message.ParseFromIstream(&stream));
EXPECT_TRUE(stream.eof());
MapTestUtil::ExpectMapFieldsSet(message);
}
{
// Test ParseFromBoundedZeroCopyStream.
std::string data_with_junk(data);
data_with_junk.append("some junk on the end");
io::ArrayInputStream stream(data_with_junk.data(), data_with_junk.size());
UNITTEST::TestMap message;
EXPECT_TRUE(message.ParseFromBoundedZeroCopyStream(&stream, data.size()));
MapTestUtil::ExpectMapFieldsSet(message);
}
{
// Test that ParseFromBoundedZeroCopyStream fails (but doesn't crash) if
// EOF is reached before the expected number of bytes.
io::ArrayInputStream stream(data.data(), data.size());
UNITTEST::TestAllTypes message;
EXPECT_FALSE(
message.ParseFromBoundedZeroCopyStream(&stream, data.size() + 1));
}
}
// Deterministic Serialization Test ==========================================
template <typename T>
static std::string DeterministicSerializationWithSerializePartialToCodedStream(
const T& t) {
const size_t size = t.ByteSizeLong();
std::string result(size, '\0');
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
io::CodedOutputStream output_stream(&array_stream);
output_stream.SetSerializationDeterministic(true);
t.SerializePartialToCodedStream(&output_stream);
EXPECT_FALSE(output_stream.HadError());
EXPECT_EQ(size, output_stream.ByteCount());
return result;
}
template <typename T>
static std::string DeterministicSerializationWithSerializeToCodedStream(
const T& t) {
const size_t size = t.ByteSizeLong();
std::string result(size, '\0');
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
io::CodedOutputStream output_stream(&array_stream);
output_stream.SetSerializationDeterministic(true);
t.SerializeToCodedStream(&output_stream);
EXPECT_FALSE(output_stream.HadError());
EXPECT_EQ(size, output_stream.ByteCount());
return result;
}
template <typename T>
static std::string DeterministicSerialization(const T& t) {
const size_t size = t.ByteSizeLong();
std::string result(size, '\0');
io::ArrayOutputStream array_stream(::google::protobuf::string_as_array(&result), size);
{
io::CodedOutputStream output_stream(&array_stream);
output_stream.SetSerializationDeterministic(true);
t.SerializeWithCachedSizes(&output_stream);
EXPECT_FALSE(output_stream.HadError());
EXPECT_EQ(size, output_stream.ByteCount());
}
EXPECT_EQ(result, DeterministicSerializationWithSerializeToCodedStream(t));
EXPECT_EQ(result,
DeterministicSerializationWithSerializePartialToCodedStream(t));
return result;
}
// Helper for MapSerializationTest. Return a 7-bit ASCII string.
static std::string ConstructKey(uint64 n) {
std::string s(n % static_cast<uint64>(9), '\0');
if (s.empty()) {
return StrCat(n);
} else {
while (n != 0) {
s[n % s.size()] = (n >> 10) & 0x7f;
n /= 888;
}
return s;
}
}
TEST(MapSerializationTest, Deterministic) {
const int kIters = 25;
UNITTEST::TestMaps t;
UNITTEST::TestIntIntMap inner;
(*inner.mutable_m())[0] = (*inner.mutable_m())[10] =
(*inner.mutable_m())[-200] = 0;
uint64 frog = 9;
const uint64 multiplier = 0xa29cd16f;
for (int i = 0; i < kIters; i++) {
const int32 i32 = static_cast<int32>(frog & 0xffffffff);
const uint32 u32 = static_cast<uint32>(i32) * 91919;
const int64 i64 = static_cast<int64>(frog);
const uint64 u64 = frog * static_cast<uint64>(187321);
const bool b = i32 > 0;
const std::string s = ConstructKey(frog);
(*inner.mutable_m())[i] = i32;
(*t.mutable_m_int32())[i32] = (*t.mutable_m_sint32())[i32] =
(*t.mutable_m_sfixed32())[i32] = inner;
(*t.mutable_m_uint32())[u32] = (*t.mutable_m_fixed32())[u32] = inner;
(*t.mutable_m_int64())[i64] = (*t.mutable_m_sint64())[i64] =
(*t.mutable_m_sfixed64())[i64] = inner;
(*t.mutable_m_uint64())[u64] = (*t.mutable_m_fixed64())[u64] = inner;
(*t.mutable_m_bool())[b] = inner;
(*t.mutable_m_string())[s] = inner;
(*t.mutable_m_string())[s + std::string(1 << (u32 % static_cast<uint32>(9)),
b)] = inner;
inner.mutable_m()->erase(i);
frog = frog * multiplier + i;
frog ^= (frog >> 41);
}
// Verifies if two consecutive calls to deterministic serialization produce
// the same bytes. Deterministic serialization means the same serialization
// bytes in the same binary.
const std::string s1 = DeterministicSerialization(t);
const std::string s2 = DeterministicSerialization(t);
EXPECT_EQ(s1, s2);
UNITTEST::TestMaps u;
EXPECT_TRUE(u.ParseFromString(s1));
EXPECT_TRUE(util::MessageDifferencer::Equals(u, t));
}
TEST(MapSerializationTest, DeterministicSubmessage) {
UNITTEST::TestSubmessageMaps p;
UNITTEST::TestMaps t;
const std::string filename = "golden_message_maps";
std::string golden;
GOOGLE_CHECK_OK(File::GetContents(
TestUtil::GetTestDataPath("net/proto2/internal/testdata/" + filename),
&golden, true));
t.ParseFromString(golden);
*(p.mutable_m()) = t;
std::vector<std::string> v;
// Use multiple attempts to increase the chance of a failure if something is
// buggy. For example, each separate copy of a map might use a different
// randomly-chosen hash function.
const int kAttempts = 10;
for (int i = 0; i < kAttempts; i++) {
UNITTEST::TestSubmessageMaps q(p);
ASSERT_EQ(DeterministicSerialization(q), DeterministicSerialization(p));
}
}
// Text Format Test =================================================
TEST(TextFormatMapTest, SerializeAndParse) {
UNITTEST::TestMap source;
UNITTEST::TestMap dest;
MapTestUtil::SetMapFields(&source);
std::string output;
// Test compact ASCII
TextFormat::Printer printer;
printer.PrintToString(source, &output);
TextFormat::Parser parser;
EXPECT_TRUE(parser.ParseFromString(output, &dest));
MapTestUtil::ExpectMapFieldsSet(dest);
}
TEST(TextFormatMapTest, DynamicMessage) {
TestMap prototype;
DynamicMessageFactory factory;
std::unique_ptr<Message> message(
factory.GetPrototype(prototype.GetDescriptor())->New());
MapReflectionTester tester(message->GetDescriptor());
tester.SetMapFieldsViaReflection(message.get());
std::string expected_text;
GOOGLE_CHECK_OK(
File::GetContents(TestUtil::GetTestDataPath("net/proto2/internal/"
"testdata/map_test_data.txt"),
&expected_text, true));
CleanStringLineEndings(&expected_text, false);
EXPECT_EQ(message->DebugString(), expected_text);
}
TEST(TextFormatMapTest, Sorted) {
UNITTEST::TestMap message;
MapReflectionTester tester(message.GetDescriptor());
tester.SetMapFieldsViaReflection(&message);
std::string expected_text;
GOOGLE_CHECK_OK(
File::GetContents(TestUtil::GetTestDataPath("net/proto2/internal/"
"testdata/map_test_data.txt"),
&expected_text, true));
CleanStringLineEndings(&expected_text, false);
EXPECT_EQ(message.DebugString(), expected_text);
// Test again on the reverse order.
UNITTEST::TestMap message2;
tester.SetMapFieldsViaReflection(&message2);
tester.SwapMapsViaReflection(&message2);
EXPECT_EQ(message2.DebugString(), expected_text);
}
TEST(TextFormatMapTest, ParseCorruptedString) {
std::string serialized_message;
GOOGLE_CHECK_OK(
File::GetContents(TestUtil::GetTestDataPath(
"net/proto2/internal/testdata/golden_message_maps"),
&serialized_message, true));
UNITTEST::TestMaps message;
GOOGLE_CHECK(message.ParseFromString(serialized_message));
TestParseCorruptedString<UNITTEST::TestMaps, true>(message);
TestParseCorruptedString<UNITTEST::TestMaps, false>(message);
}
// Previously, serializing to text format will disable iterator from generated
// API. Now, the iterator can be still used even after serializing to text
// format.
TEST(TextFormatMapTest, NoDisableIterator) {
UNITTEST::TestMap source;
(*source.mutable_map_int32_int32())[1] = 1;
// Get iterator.
Map<int32, int32>::iterator iter = source.mutable_map_int32_int32()->find(1);
// Serialize message to text format, which will invalidate the previous
// iterator previously.
std::string output;
TextFormat::Printer printer;
printer.PrintToString(source, &output);
// Modify map via the iterator (invalidated in previous implementation.).
iter->second = 2;
// In previous implementation, the new change won't be reflected in text
// format, because the previous iterator has been invalidated.
output.clear();
printer.PrintToString(source, &output);
std::string expected =
"map_int32_int32 {\n"
" key: 1\n"
" value: 2\n"
"}\n";
EXPECT_EQ(output, expected);
}
// Previously, serializing to text format will disable iterator from reflection
// API.
TEST(TextFormatMapTest, NoDisableReflectionIterator) {
UNITTEST::TestMap source;
(*source.mutable_map_int32_int32())[1] = 1;
// Get iterator. This will also sync internal repeated field with map inside
// of MapField.
const Reflection* reflection = source.GetReflection();
const FieldDescriptor* field_desc =
source.GetDescriptor()->FindFieldByName("map_int32_int32");
RepeatedPtrField<Message>* map_field =
reflection->MutableRepeatedPtrField<Message>(&source, field_desc);
RepeatedPtrField<Message>::iterator iter = map_field->begin();
// Serialize message to text format, which will invalidate the previous
// iterator previously.
std::string output;
TextFormat::Printer printer;
printer.PrintToString(source, &output);
// Modify map via the iterator (invalidated in previous implementation.).
const Reflection* map_entry_reflection = iter->GetReflection();
const FieldDescriptor* value_field_desc =
iter->GetDescriptor()->FindFieldByName("value");
map_entry_reflection->SetInt32(&(*iter), value_field_desc, 2);
GOOGLE_LOG(INFO) << iter->DebugString();
// In previous implementation, the new change won't be reflected in text
// format, because the previous iterator has been invalidated.
output.clear();
printer.PrintToString(source, &output);
std::string expected =
"map_int32_int32 {\n"
" key: 1\n"
" value: 2\n"
"}\n";
EXPECT_EQ(output, expected);
}
// arena support =================================================
TEST(ArenaTest, ParsingAndSerializingNoHeapAllocation) {
// Allocate a large initial block to avoid mallocs during hooked test.
std::vector<char> arena_block(128 * 1024);
ArenaOptions options;
options.initial_block = &arena_block[0];
options.initial_block_size = arena_block.size();
Arena arena(options);
std::string data;
data.reserve(128 * 1024);
{
// TODO(teboring): Enable no heap check when ArenaStringPtr is used in map.
// NoHeapChecker no_heap;
UNITTEST::TestArenaMap* from =
Arena::CreateMessage<UNITTEST::TestArenaMap>(&arena);
MapTestUtil::SetArenaMapFields(from);
from->SerializeToString(&data);
UNITTEST::TestArenaMap* to =
Arena::CreateMessage<UNITTEST::TestArenaMap>(&arena);
to->ParseFromString(data);
MapTestUtil::ExpectArenaMapFieldsSet(*to);
}
}
TEST(ArenaTest, SubmessageOnSameArena) {
Arena arena;
for (Arena* arena_to_use : {&arena, static_cast<Arena*>(nullptr)}) {
ArenaHolder<UNITTEST::TestArenaMap> m(arena_to_use);
auto* subm = &(*m->mutable_map_int32_foreign_message())[0];
EXPECT_EQ(subm->GetArena(), arena_to_use);
}
}
// Use text format parsing and serializing to test reflection api.
TEST(ArenaTest, ReflectionInTextFormat) {
Arena arena;
std::string data;
TextFormat::Printer printer;
TextFormat::Parser parser;
UNITTEST::TestArenaMap* from =
Arena::CreateMessage<UNITTEST::TestArenaMap>(&arena);
UNITTEST::TestArenaMap* to =
Arena::CreateMessage<UNITTEST::TestArenaMap>(&arena);
MapTestUtil::SetArenaMapFields(from);
printer.PrintToString(*from, &data);
EXPECT_TRUE(parser.ParseFromString(data, to));
MapTestUtil::ExpectArenaMapFieldsSet(*to);
}
// Make sure the memory allocated for string in map is deallocated.
TEST(ArenaTest, StringMapNoLeak) {
Arena arena;
UNITTEST::TestArenaMap* message =
Arena::CreateMessage<UNITTEST::TestArenaMap>(&arena);
std::string data;
// String with length less than 16 will not be allocated from heap.
int original_capacity = data.capacity();
while (data.capacity() <= original_capacity) {
data.append("a");
}
(*message->mutable_map_string_string())[data] = data;
// We rely on heap checkers to detect memory leak for us.
ASSERT_FALSE(message == nullptr);
}
TEST(ArenaTest, IsInitialized) {
// Allocate a large initial polluted block.
std::vector<char> arena_block(128 * 1024);
std::fill(arena_block.begin(), arena_block.end(), '\xff');
ArenaOptions options;
options.initial_block = &arena_block[0];
options.initial_block_size = arena_block.size();
Arena arena(options);
UNITTEST::TestArenaMap* message =
Arena::CreateMessage<UNITTEST::TestArenaMap>(&arena);
EXPECT_EQ(0, (*message->mutable_map_int32_int32())[0]);
}
TEST(ArenaTest, DynamicMapFieldOnArena) {
Arena arena;
UNITTEST::TestMap message2;
DynamicMessageFactory factory;
Message* message1 =
factory.GetPrototype(UNITTEST::TestMap::descriptor())->New(&arena);
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
reflection_tester.SetMapFieldsViaReflection(message1);
reflection_tester.ExpectMapFieldsSetViaReflection(*message1);
reflection_tester.ExpectMapFieldsSetViaReflectionIterator(message1);
message2.CopyFrom(*message1);
MapTestUtil::ExpectMapFieldsSet(message2);
}
TEST(ArenaTest, DynamicMapFieldOnArenaMemoryLeak) {
auto* desc = UNITTEST::TestMap::descriptor();
auto* field = desc->FindFieldByName("map_int32_int32");
Arena arena;
DynamicMessageFactory factory;
auto* message = factory.GetPrototype(desc)->New(&arena);
auto* reflection = message->GetReflection();
reflection->AddMessage(message, field);
// Force internal syncing, which initializes the mutex.
MapReflectionTester reflection_tester(UNITTEST::TestMap::descriptor());
int size = reflection_tester.MapSize(*message, "map_int32_int32");
EXPECT_EQ(size, 1);
}
TEST(MoveTest, MoveConstructorWorks) {
Map<int32, TestAllTypes> original_map;
original_map[42].mutable_optional_nested_message()->set_bb(42);
original_map[43].mutable_optional_nested_message()->set_bb(43);
const auto* nested_msg42_ptr = &original_map[42].optional_nested_message();
const auto* nested_msg43_ptr = &original_map[43].optional_nested_message();
Map<int32, TestAllTypes> moved_to_map(std::move(original_map));
EXPECT_TRUE(original_map.empty());
EXPECT_EQ(2, moved_to_map.size());
EXPECT_EQ(42, moved_to_map[42].optional_nested_message().bb());
EXPECT_EQ(43, moved_to_map[43].optional_nested_message().bb());
// This test takes advantage of the fact that pointers are swapped, so there
// should be pointer stability.
EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message());
EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
}
TEST(MoveTest, MoveAssignmentWorks) {
Map<int32, TestAllTypes> original_map;
original_map[42].mutable_optional_nested_message()->set_bb(42);
original_map[43].mutable_optional_nested_message()->set_bb(43);
const auto* nested_msg42_ptr = &original_map[42].optional_nested_message();
const auto* nested_msg43_ptr = &original_map[43].optional_nested_message();
Map<int32, TestAllTypes> moved_to_map = std::move(original_map);
EXPECT_TRUE(original_map.empty());
EXPECT_EQ(2, moved_to_map.size());
EXPECT_EQ(42, moved_to_map[42].optional_nested_message().bb());
EXPECT_EQ(43, moved_to_map[43].optional_nested_message().bb());
// This test takes advantage of the fact that pointers are swapped, so there
// should be pointer stability.
EXPECT_EQ(nested_msg42_ptr, &moved_to_map[42].optional_nested_message());
EXPECT_EQ(nested_msg43_ptr, &moved_to_map[43].optional_nested_message());
}
} // namespace
} // namespace internal
} // namespace protobuf
} // namespace google
#include <port_undef.inc>
|