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
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
|
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: String Tools
//
//===========================================================================//
// These are redefined in the project settings to prevent anyone from using them.
// We in this module are of a higher caste and thus are privileged in their use.
#ifdef strncpy
#undef strncpy
#endif
#ifdef _snprintf
#undef _snprintf
#endif
#if defined( sprintf )
#undef sprintf
#endif
#if defined( vsprintf )
#undef vsprintf
#endif
#ifdef _vsnprintf
#ifdef _WIN32
#undef _vsnprintf
#endif
#endif
#ifdef vsnprintf
#ifndef _WIN32
#undef vsnprintf
#endif
#endif
#if defined( strcat )
#undef strcat
#endif
#ifdef strncat
#undef strncat
#endif
// NOTE: I have to include stdio + stdarg first so vsnprintf gets compiled in
#include <stdio.h>
#include <stdarg.h>
#ifdef POSIX
#include <iconv.h>
#include <ctype.h>
#include <unistd.h>
#include <stdlib.h>
#define _getcwd getcwd
#elif _WIN32
#include <direct.h>
#if !defined( _X360 )
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#endif
#endif
#ifdef _WIN32
#ifndef CP_UTF8
#define CP_UTF8 65001
#endif
#endif
#include "tier0/dbg.h"
#include "tier1/strtools.h"
#include <string.h>
#include <stdlib.h>
#include <time.h>
#include "tier0/basetypes.h"
#include "tier1/utldict.h"
#include "tier1/utlbuffer.h"
#include "tier1/utlstring.h"
#include "tier1/fmtstr.h"
#if defined( _X360 )
#include "xbox/xbox_win32stubs.h"
#endif
#include "tier0/memdbgon.h"
static int FastToLower( char c )
{
int i = (unsigned char) c;
if ( i < 0x80 )
{
// Brutally fast branchless ASCII tolower():
i += (((('A'-1) - i) & (i - ('Z'+1))) >> 26) & 0x20;
}
else
{
i += isupper( i ) ? 0x20 : 0;
}
return i;
}
void _V_memset (const char* file, int line, void *dest, int fill, int count)
{
Assert( count >= 0 );
AssertValidWritePtr( dest, count );
memset(dest,fill,count);
}
void _V_memcpy (const char* file, int line, void *dest, const void *src, int count)
{
Assert( count >= 0 );
AssertValidReadPtr( src, count );
AssertValidWritePtr( dest, count );
memcpy( dest, src, count );
}
void _V_memmove(const char* file, int line, void *dest, const void *src, int count)
{
Assert( count >= 0 );
AssertValidReadPtr( src, count );
AssertValidWritePtr( dest, count );
memmove( dest, src, count );
}
int _V_memcmp (const char* file, int line, const void *m1, const void *m2, int count)
{
Assert( count >= 0 );
AssertValidReadPtr( m1, count );
AssertValidReadPtr( m2, count );
return memcmp( m1, m2, count );
}
int _V_strlen(const char* file, int line, const char *str)
{
AssertValidStringPtr(str);
return strlen( str );
}
void _V_strcpy (const char* file, int line, char *dest, const char *src)
{
AssertValidWritePtr(dest);
AssertValidStringPtr(src);
strcpy( dest, src );
}
int _V_wcslen(const char* file, int line, const wchar_t *pwch)
{
return wcslen( pwch );
}
char *_V_strrchr(const char* file, int line, const char *s, char c)
{
AssertValidStringPtr( s );
int len = V_strlen(s);
s += len;
while (len--)
if (*--s == c) return (char *)s;
return 0;
}
int _V_strcmp (const char* file, int line, const char *s1, const char *s2)
{
AssertValidStringPtr( s1 );
AssertValidStringPtr( s2 );
return strcmp( s1, s2 );
}
int _V_wcscmp (const char* file, int line, const wchar_t *s1, const wchar_t *s2)
{
AssertValidReadPtr( s1 );
AssertValidReadPtr( s2 );
while ( *s1 == *s2 )
{
if ( !*s1 )
return 0; // strings are equal
s1++;
s2++;
}
return *s1 > *s2 ? 1 : -1; // strings not equal
}
char *_V_strstr(const char* file, int line, const char *s1, const char *search )
{
AssertValidStringPtr( s1 );
AssertValidStringPtr( search );
#if defined( _X360 )
return (char *)strstr( (char *)s1, search );
#else
return (char *)strstr( s1, search );
#endif
}
wchar_t *_V_wcsupr (const char* file, int line, wchar_t *start)
{
return _wcsupr( start );
}
wchar_t *_V_wcslower (const char* file, int line, wchar_t *start)
{
return _wcslwr(start);
}
char *V_strupr( char *start )
{
unsigned char *str = (unsigned char*)start;
while( *str )
{
if ( (unsigned char)(*str - 'a') <= ('z' - 'a') )
*str -= 'a' - 'A';
else if ( (unsigned char)*str >= 0x80 ) // non-ascii, fall back to CRT
*str = toupper( *str );
str++;
}
return start;
}
char *V_strlower( char *start )
{
unsigned char *str = (unsigned char*)start;
while( *str )
{
if ( (unsigned char)(*str - 'A') <= ('Z' - 'A') )
*str += 'a' - 'A';
else if ( (unsigned char)*str >= 0x80 ) // non-ascii, fall back to CRT
*str = tolower( *str );
str++;
}
return start;
}
char *V_strnlwr(char *s, size_t count)
{
// Assert( count >= 0 ); tautology since size_t is unsigned
AssertValidStringPtr( s, count );
char* pRet = s;
if ( !s || !count )
return s;
while ( -- count > 0 )
{
if ( !*s )
return pRet; // reached end of string
*s = tolower( *s );
++s;
}
*s = 0; // null-terminate original string at "count-1"
return pRet;
}
int V_stricmp( const char *str1, const char *str2 )
{
// It is not uncommon to compare a string to itself. See
// VPanelWrapper::GetPanel which does this a lot. Since stricmp
// is expensive and pointer comparison is cheap, this simple test
// can save a lot of cycles, and cache pollution.
if ( str1 == str2 )
{
return 0;
}
const unsigned char *s1 = (const unsigned char*)str1;
const unsigned char *s2 = (const unsigned char*)str2;
for ( ; *s1; ++s1, ++s2 )
{
if ( *s1 != *s2 )
{
// in ascii char set, lowercase = uppercase | 0x20
unsigned char c1 = *s1 | 0x20;
unsigned char c2 = *s2 | 0x20;
if ( c1 != c2 || (unsigned char)(c1 - 'a') > ('z' - 'a') )
{
// if non-ascii mismatch, fall back to CRT for locale
if ( (c1 | c2) >= 0x80 ) return stricmp( (const char*)s1, (const char*)s2 );
// ascii mismatch. only use the | 0x20 value if alphabetic.
if ((unsigned char)(c1 - 'a') > ('z' - 'a')) c1 = *s1;
if ((unsigned char)(c2 - 'a') > ('z' - 'a')) c2 = *s2;
return c1 > c2 ? 1 : -1;
}
}
}
return *s2 ? -1 : 0;
}
int V_strnicmp( const char *str1, const char *str2, int n )
{
const unsigned char *s1 = (const unsigned char*)str1;
const unsigned char *s2 = (const unsigned char*)str2;
for ( ; n > 0 && *s1; --n, ++s1, ++s2 )
{
if ( *s1 != *s2 )
{
// in ascii char set, lowercase = uppercase | 0x20
unsigned char c1 = *s1 | 0x20;
unsigned char c2 = *s2 | 0x20;
if ( c1 != c2 || (unsigned char)(c1 - 'a') > ('z' - 'a') )
{
// if non-ascii mismatch, fall back to CRT for locale
if ( (c1 | c2) >= 0x80 ) return strnicmp( (const char*)s1, (const char*)s2, n );
// ascii mismatch. only use the | 0x20 value if alphabetic.
if ((unsigned char)(c1 - 'a') > ('z' - 'a')) c1 = *s1;
if ((unsigned char)(c2 - 'a') > ('z' - 'a')) c2 = *s2;
return c1 > c2 ? 1 : -1;
}
}
}
return (n > 0 && *s2) ? -1 : 0;
}
int V_strncmp( const char *s1, const char *s2, int count )
{
Assert( count >= 0 );
AssertValidStringPtr( s1, count );
AssertValidStringPtr( s2, count );
while ( count > 0 )
{
if ( *s1 != *s2 )
return (unsigned char)*s1 < (unsigned char)*s2 ? -1 : 1; // string different
if ( *s1 == '\0' )
return 0; // null terminator hit - strings the same
s1++;
s2++;
count--;
}
return 0; // count characters compared the same
}
const char *StringAfterPrefix( const char *str, const char *prefix )
{
AssertValidStringPtr( str );
AssertValidStringPtr( prefix );
do
{
if ( !*prefix )
return str;
}
while ( FastToLower( *str++ ) == FastToLower( *prefix++ ) );
return NULL;
}
const char *StringAfterPrefixCaseSensitive( const char *str, const char *prefix )
{
AssertValidStringPtr( str );
AssertValidStringPtr( prefix );
do
{
if ( !*prefix )
return str;
}
while ( *str++ == *prefix++ );
return NULL;
}
int64 V_atoi64( const char *str )
{
AssertValidStringPtr( str );
int64 val;
int64 sign;
int64 c;
Assert( str );
if (*str == '-')
{
sign = -1;
str++;
}
else if (*str == '+')
{
sign = 1;
str++;
}
else
{
sign = 1;
}
val = 0;
//
// check for hex
//
if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') )
{
str += 2;
while (1)
{
c = *str++;
if (c >= '0' && c <= '9')
val = (val<<4) + c - '0';
else if (c >= 'a' && c <= 'f')
val = (val<<4) + c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
val = (val<<4) + c - 'A' + 10;
else
return val*sign;
}
}
//
// check for character
//
if (str[0] == '\'')
{
return sign * str[1];
}
//
// assume decimal
//
while (1)
{
c = *str++;
if (c <'0' || c > '9')
return val*sign;
val = val*10 + c - '0';
}
return 0;
}
uint64 V_atoui64( const char *str )
{
AssertValidStringPtr( str );
uint64 val;
uint64 c;
Assert( str );
val = 0;
//
// check for hex
//
if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') )
{
str += 2;
while (1)
{
c = *str++;
if (c >= '0' && c <= '9')
val = (val<<4) + c - '0';
else if (c >= 'a' && c <= 'f')
val = (val<<4) + c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
val = (val<<4) + c - 'A' + 10;
else
return val;
}
}
//
// check for character
//
if (str[0] == '\'')
{
return str[1];
}
//
// assume decimal
//
while (1)
{
c = *str++;
if (c <'0' || c > '9')
return val;
val = val*10 + c - '0';
}
return 0;
}
int V_atoi( const char *str )
{
return (int)V_atoi64( str );
}
float V_atof (const char *str)
{
AssertValidStringPtr( str );
double val;
int sign;
int c;
int decimal, total;
if (*str == '-')
{
sign = -1;
str++;
}
else if (*str == '+')
{
sign = 1;
str++;
}
else
{
sign = 1;
}
val = 0;
//
// check for hex
//
if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X') )
{
str += 2;
while (1)
{
c = *str++;
if (c >= '0' && c <= '9')
val = (val*16) + c - '0';
else if (c >= 'a' && c <= 'f')
val = (val*16) + c - 'a' + 10;
else if (c >= 'A' && c <= 'F')
val = (val*16) + c - 'A' + 10;
else
return val*sign;
}
}
//
// check for character
//
if (str[0] == '\'')
{
return sign * str[1];
}
//
// assume decimal
//
decimal = -1;
total = 0;
int exponent = 0;
while (1)
{
c = *str++;
if (c == '.')
{
if ( decimal != -1 )
{
break;
}
decimal = total;
continue;
}
if (c <'0' || c > '9')
{
if ( c == 'e' || c == 'E' )
{
exponent = V_atoi(str);
}
break;
}
val = val*10 + c - '0';
total++;
}
if ( exponent != 0 )
{
val *= pow( 10.0, exponent );
}
if (decimal == -1)
return val*sign;
while (total > decimal)
{
val /= 10;
total--;
}
return val*sign;
}
//-----------------------------------------------------------------------------
// Normalizes a float string in place.
//
// (removes leading zeros, trailing zeros after the decimal point, and the decimal point itself where possible)
//-----------------------------------------------------------------------------
void V_normalizeFloatString( char* pFloat )
{
// If we have a decimal point, remove trailing zeroes:
if( strchr( pFloat,'.' ) )
{
int len = V_strlen(pFloat);
while( len > 1 && pFloat[len - 1] == '0' )
{
pFloat[len - 1] = '\0';
len--;
}
if( len > 1 && pFloat[ len - 1 ] == '.' )
{
pFloat[len - 1] = '\0';
len--;
}
}
// TODO: Strip leading zeros
}
//-----------------------------------------------------------------------------
// Finds a string in another string with a case insensitive test
//-----------------------------------------------------------------------------
char const* V_stristr( char const* pStr, char const* pSearch )
{
AssertValidStringPtr(pStr);
AssertValidStringPtr(pSearch);
if (!pStr || !pSearch)
return 0;
char const* pLetter = pStr;
// Check the entire string
while (*pLetter != 0)
{
// Skip over non-matches
if (FastToLower((unsigned char)*pLetter) == FastToLower((unsigned char)*pSearch))
{
// Check for match
char const* pMatch = pLetter + 1;
char const* pTest = pSearch + 1;
while (*pTest != 0)
{
// We've run off the end; don't bother.
if (*pMatch == 0)
return 0;
if (FastToLower((unsigned char)*pMatch) != FastToLower((unsigned char)*pTest))
break;
++pMatch;
++pTest;
}
// Found a match!
if (*pTest == 0)
return pLetter;
}
++pLetter;
}
return 0;
}
char* V_stristr( char* pStr, char const* pSearch )
{
AssertValidStringPtr( pStr );
AssertValidStringPtr( pSearch );
return (char*)V_stristr( (char const*)pStr, pSearch );
}
//-----------------------------------------------------------------------------
// Finds a string in another string with a case insensitive test w/ length validation
//-----------------------------------------------------------------------------
char const* V_strnistr( char const* pStr, char const* pSearch, int n )
{
AssertValidStringPtr(pStr);
AssertValidStringPtr(pSearch);
if (!pStr || !pSearch)
return 0;
char const* pLetter = pStr;
// Check the entire string
while (*pLetter != 0)
{
if ( n <= 0 )
return 0;
// Skip over non-matches
if (FastToLower(*pLetter) == FastToLower(*pSearch))
{
int n1 = n - 1;
// Check for match
char const* pMatch = pLetter + 1;
char const* pTest = pSearch + 1;
while (*pTest != 0)
{
if ( n1 <= 0 )
return 0;
// We've run off the end; don't bother.
if (*pMatch == 0)
return 0;
if (FastToLower(*pMatch) != FastToLower(*pTest))
break;
++pMatch;
++pTest;
--n1;
}
// Found a match!
if (*pTest == 0)
return pLetter;
}
++pLetter;
--n;
}
return 0;
}
const char* V_strnchr( const char* pStr, char c, int n )
{
char const* pLetter = pStr;
char const* pLast = pStr + n;
// Check the entire string
while ( (pLetter < pLast) && (*pLetter != 0) )
{
if (*pLetter == c)
return pLetter;
++pLetter;
}
return NULL;
}
void V_strncpy( char *pDest, char const *pSrc, int maxLen )
{
Assert( maxLen >= sizeof( *pDest ) );
AssertValidWritePtr( pDest, maxLen );
AssertValidStringPtr( pSrc );
strncpy( pDest, pSrc, maxLen );
if ( maxLen > 0 )
{
pDest[maxLen-1] = 0;
}
}
// warning C6053: Call to 'wcsncpy' might not zero-terminate string 'pDest'
// warning C6059: Incorrect length parameter in call to 'strncat'. Pass the number of remaining characters, not the buffer size of 'argument 1'
// warning C6386: Buffer overrun: accessing 'argument 1', the writable size is 'destBufferSize' bytes, but '1000' bytes might be written
// These warnings were investigated through code inspection and writing of tests and they are
// believed to all be spurious.
#ifdef _PREFAST_
#pragma warning( push )
#pragma warning( disable : 6053 6059 6386 )
#endif
void V_wcsncpy( wchar_t *pDest, wchar_t const *pSrc, int maxLenInBytes )
{
Assert( maxLenInBytes >= sizeof( *pDest ) );
AssertValidWritePtr( pDest, maxLenInBytes );
AssertValidReadPtr( pSrc );
int maxLen = maxLenInBytes / sizeof(wchar_t);
wcsncpy( pDest, pSrc, maxLen );
if( maxLen )
{
pDest[maxLen-1] = 0;
}
}
int V_snwprintf( wchar_t *pDest, int maxLen, const wchar_t *pFormat, ... )
{
Assert( maxLen > 0 );
AssertValidWritePtr( pDest, maxLen );
AssertValidReadPtr( pFormat );
va_list marker;
va_start( marker, pFormat );
#ifdef _WIN32
int len = _vsnwprintf( pDest, maxLen, pFormat, marker );
#elif POSIX
int len = vswprintf( pDest, maxLen, pFormat, marker );
#else
#error "define vsnwprintf type."
#endif
va_end( marker );
// Len > maxLen represents an overflow on POSIX, < 0 is an overflow on windows
if( len < 0 || len >= maxLen )
{
len = maxLen;
pDest[maxLen-1] = 0;
}
return len;
}
int V_vsnwprintf( wchar_t *pDest, int maxLen, const wchar_t *pFormat, va_list params )
{
Assert( maxLen > 0 );
#ifdef _WIN32
int len = _vsnwprintf( pDest, maxLen, pFormat, params );
#elif POSIX
int len = vswprintf( pDest, maxLen, pFormat, params );
#else
#error "define vsnwprintf type."
#endif
// Len < 0 represents an overflow
// Len == maxLen represents exactly fitting with no NULL termination
// Len >= maxLen represents overflow on POSIX
if ( len < 0 || len >= maxLen )
{
len = maxLen;
pDest[maxLen-1] = 0;
}
return len;
}
int V_snprintf( char *pDest, int maxLen, char const *pFormat, ... )
{
Assert( maxLen > 0 );
AssertValidWritePtr( pDest, maxLen );
AssertValidStringPtr( pFormat );
va_list marker;
va_start( marker, pFormat );
#ifdef _WIN32
int len = _vsnprintf( pDest, maxLen, pFormat, marker );
#elif POSIX
int len = vsnprintf( pDest, maxLen, pFormat, marker );
#else
#error "define vsnprintf type."
#endif
va_end( marker );
// Len > maxLen represents an overflow on POSIX, < 0 is an overflow on windows
if( len < 0 || len >= maxLen )
{
len = maxLen;
pDest[maxLen-1] = 0;
}
return len;
}
int V_vsnprintf( char *pDest, int maxLen, char const *pFormat, va_list params )
{
Assert( maxLen > 0 );
AssertValidWritePtr( pDest, maxLen );
AssertValidStringPtr( pFormat );
int len = _vsnprintf( pDest, maxLen, pFormat, params );
// Len > maxLen represents an overflow on POSIX, < 0 is an overflow on windows
if( len < 0 || len >= maxLen )
{
len = maxLen;
pDest[maxLen-1] = 0;
}
return len;
}
int V_vsnprintfRet( char *pDest, int maxLen, const char *pFormat, va_list params, bool *pbTruncated )
{
Assert( maxLen > 0 );
AssertValidWritePtr( pDest, maxLen );
AssertValidStringPtr( pFormat );
int len = _vsnprintf( pDest, maxLen, pFormat, params );
if ( pbTruncated )
{
*pbTruncated = ( len < 0 || len >= maxLen );
}
if ( len < 0 || len >= maxLen )
{
len = maxLen;
pDest[maxLen-1] = 0;
}
return len;
}
//-----------------------------------------------------------------------------
// Purpose: If COPY_ALL_CHARACTERS == max_chars_to_copy then we try to add the whole pSrc to the end of pDest, otherwise
// we copy only as many characters as are specified in max_chars_to_copy (or the # of characters in pSrc if thats's less).
// Input : *pDest - destination buffer
// *pSrc - string to append
// destBufferSize - sizeof the buffer pointed to by pDest
// max_chars_to_copy - COPY_ALL_CHARACTERS in pSrc or max # to copy
// Output : char * the copied buffer
//-----------------------------------------------------------------------------
char *V_strncat(char *pDest, const char *pSrc, size_t destBufferSize, int max_chars_to_copy )
{
size_t charstocopy = (size_t)0;
Assert( (ptrdiff_t)destBufferSize >= 0 );
AssertValidStringPtr( pDest);
AssertValidStringPtr( pSrc );
size_t len = strlen(pDest);
size_t srclen = strlen( pSrc );
if ( max_chars_to_copy <= COPY_ALL_CHARACTERS )
{
charstocopy = srclen;
}
else
{
charstocopy = (size_t)min( max_chars_to_copy, (int)srclen );
}
if ( len + charstocopy >= destBufferSize )
{
charstocopy = destBufferSize - len - 1;
}
if ( (int)charstocopy <= 0 )
{
return pDest;
}
ANALYZE_SUPPRESS( 6059 ); // warning C6059: : Incorrect length parameter in call to 'strncat'. Pass the number of remaining characters, not the buffer size of 'argument 1'
char *pOut = strncat( pDest, pSrc, charstocopy );
return pOut;
}
wchar_t *V_wcsncat( INOUT_Z_CAP(cchDest) wchar_t *pDest, const wchar_t *pSrc, size_t cchDest, int max_chars_to_copy )
{
size_t charstocopy = (size_t)0;
Assert( (ptrdiff_t)cchDest >= 0 );
size_t len = wcslen(pDest);
size_t srclen = wcslen( pSrc );
if ( max_chars_to_copy <= COPY_ALL_CHARACTERS )
{
charstocopy = srclen;
}
else
{
charstocopy = (size_t)min( max_chars_to_copy, (int)srclen );
}
if ( len + charstocopy >= cchDest )
{
charstocopy = cchDest - len - 1;
}
if ( (int)charstocopy <= 0 )
{
return pDest;
}
ANALYZE_SUPPRESS( 6059 ); // warning C6059: : Incorrect length parameter in call to 'strncat'. Pass the number of remaining characters, not the buffer size of 'argument 1'
wchar_t *pOut = wcsncat( pDest, pSrc, charstocopy );
return pOut;
}
//-----------------------------------------------------------------------------
// Purpose: Converts value into x.xx MB/ x.xx KB, x.xx bytes format, including commas
// Input : value -
// 2 -
// false -
// Output : char
//-----------------------------------------------------------------------------
#define NUM_PRETIFYMEM_BUFFERS 8
char *V_pretifymem( float value, int digitsafterdecimal /*= 2*/, bool usebinaryonek /*= false*/ )
{
static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ];
static int current;
float onekb = usebinaryonek ? 1024.0f : 1000.0f;
float onemb = onekb * onekb;
char *out = output[ current ];
current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 );
char suffix[ 8 ];
// First figure out which bin to use
if ( value > onemb )
{
value /= onemb;
V_snprintf( suffix, sizeof( suffix ), " MB" );
}
else if ( value > onekb )
{
value /= onekb;
V_snprintf( suffix, sizeof( suffix ), " KB" );
}
else
{
V_snprintf( suffix, sizeof( suffix ), " bytes" );
}
char val[ 32 ];
// Clamp to >= 0
digitsafterdecimal = max( digitsafterdecimal, 0 );
// If it's basically integral, don't do any decimals
if ( FloatMakePositive( value - (int)value ) < 0.00001 )
{
V_snprintf( val, sizeof( val ), "%i%s", (int)value, suffix );
}
else
{
char fmt[ 32 ];
// Otherwise, create a format string for the decimals
V_snprintf( fmt, sizeof( fmt ), "%%.%if%s", digitsafterdecimal, suffix );
V_snprintf( val, sizeof( val ), fmt, value );
}
// Copy from in to out
char *i = val;
char *o = out;
// Search for decimal or if it was integral, find the space after the raw number
char *dot = strstr( i, "." );
if ( !dot )
{
dot = strstr( i, " " );
}
// Compute position of dot
int pos = dot - i;
// Don't put a comma if it's <= 3 long
pos -= 3;
while ( *i )
{
// If pos is still valid then insert a comma every third digit, except if we would be
// putting one in the first spot
if ( pos >= 0 && !( pos % 3 ) )
{
// Never in first spot
if ( o != out )
{
*o++ = ',';
}
}
// Count down comma position
pos--;
// Copy rest of data as normal
*o++ = *i++;
}
// Terminate
*o = 0;
return out;
}
//-----------------------------------------------------------------------------
// Purpose: Returns a string representation of an integer with commas
// separating the 1000s (ie, 37,426,421)
// Input : value - Value to convert
// Output : Pointer to a static buffer containing the output
//-----------------------------------------------------------------------------
#define NUM_PRETIFYNUM_BUFFERS 8 // Must be a power of two
char *V_pretifynum( int64 inputValue )
{
static char output[ NUM_PRETIFYMEM_BUFFERS ][ 32 ];
static int current;
// Point to the output buffer.
char * const out = output[ current ];
// Track the output buffer end for easy calculation of bytes-remaining.
const char* const outEnd = out + sizeof( output[ current ] );
// Point to the current output location in the output buffer.
char *pchRender = out;
// Move to the next output pointer.
current = ( current + 1 ) & ( NUM_PRETIFYMEM_BUFFERS -1 );
*out = 0;
// In order to handle the most-negative int64 we need to negate it
// into a uint64.
uint64 value;
// Render the leading minus sign, if necessary
if ( inputValue < 0 )
{
V_snprintf( pchRender, 32, "-" );
value = (uint64)-inputValue;
// Advance our output pointer.
pchRender += V_strlen( pchRender );
}
else
{
value = (uint64)inputValue;
}
// Now let's find out how big our number is. The largest number we can fit
// into 63 bits is about 9.2e18. So, there could potentially be six
// three-digit groups.
// We need the initial value of 'divisor' to be big enough to divide our
// number down to 1-999 range.
uint64 divisor = 1;
// Loop more than six times to avoid integer overflow.
for ( int i = 0; i < 6; ++i )
{
// If our divisor is already big enough then stop.
if ( value < divisor * 1000 )
break;
divisor *= 1000;
}
// Print the leading batch of one to three digits.
int toPrint = value / divisor;
V_snprintf( pchRender, outEnd - pchRender, "%d", toPrint );
for (;;)
{
// Advance our output pointer.
pchRender += V_strlen( pchRender );
// Adjust our value to be printed and our divisor.
value -= toPrint * divisor;
divisor /= 1000;
if ( !divisor )
break;
// The remaining blocks of digits always include a comma and three digits.
toPrint = value / divisor;
V_snprintf( pchRender, outEnd - pchRender, ",%03d", toPrint );
}
return out;
}
//-----------------------------------------------------------------------------
// Purpose: returns true if a wide character is a "mean" space; that is,
// if it is technically a space or punctuation, but causes disruptive
// behavior when used in names, web pages, chat windows, etc.
//
// characters in this set are removed from the beginning and/or end of strings
// by Q_AggressiveStripPrecedingAndTrailingWhitespaceW()
//-----------------------------------------------------------------------------
bool Q_IsMeanSpaceW( wchar_t wch )
{
bool bIsMean = false;
switch ( wch )
{
case L'\x0082': // BREAK PERMITTED HERE
case L'\x0083': // NO BREAK PERMITTED HERE
case L'\x00A0': // NO-BREAK SPACE
case L'\x034F': // COMBINING GRAPHEME JOINER
case L'\x2000': // EN QUAD
case L'\x2001': // EM QUAD
case L'\x2002': // EN SPACE
case L'\x2003': // EM SPACE
case L'\x2004': // THICK SPACE
case L'\x2005': // MID SPACE
case L'\x2006': // SIX SPACE
case L'\x2007': // figure space
case L'\x2008': // PUNCTUATION SPACE
case L'\x2009': // THIN SPACE
case L'\x200A': // HAIR SPACE
case L'\x200B': // ZERO-WIDTH SPACE
case L'\x200C': // ZERO-WIDTH NON-JOINER
case L'\x200D': // ZERO WIDTH JOINER
case L'\x200E': // LEFT-TO-RIGHT MARK
case L'\x2028': // LINE SEPARATOR
case L'\x2029': // PARAGRAPH SEPARATOR
case L'\x202F': // NARROW NO-BREAK SPACE
case L'\x2060': // word joiner
case L'\xFEFF': // ZERO-WIDTH NO BREAK SPACE
case L'\xFFFC': // OBJECT REPLACEMENT CHARACTER
bIsMean = true;
break;
}
return bIsMean;
}
//-----------------------------------------------------------------------------
// Purpose: strips trailing whitespace; returns pointer inside string just past
// any leading whitespace.
//
// bAggresive = true causes this function to also check for "mean" spaces,
// which we don't want in persona names or chat strings as they're disruptive
// to the user experience.
//-----------------------------------------------------------------------------
static wchar_t *StripWhitespaceWorker( int cchLength, wchar_t *pwch, bool *pbStrippedWhitespace, bool bAggressive )
{
// walk backwards from the end of the string, killing any whitespace
*pbStrippedWhitespace = false;
wchar_t *pwchEnd = pwch + cchLength;
while ( --pwchEnd >= pwch )
{
if ( !iswspace( *pwchEnd ) && ( !bAggressive || !Q_IsMeanSpaceW( *pwchEnd ) ) )
break;
*pwchEnd = 0;
*pbStrippedWhitespace = true;
}
// walk forward in the string
while ( pwch < pwchEnd )
{
if ( !iswspace( *pwch ) )
break;
*pbStrippedWhitespace = true;
pwch++;
}
return pwch;
}
//-----------------------------------------------------------------------------
// Purpose: Strips all evil characters (ie. zero-width no-break space)
// from a string.
//-----------------------------------------------------------------------------
bool Q_RemoveAllEvilCharacters( char *pch )
{
// convert to unicode
int cch = Q_strlen( pch );
int cubDest = (cch + 1 ) * sizeof( wchar_t );
wchar_t *pwch = (wchar_t *)stackalloc( cubDest );
int cwch = Q_UTF8ToUnicode( pch, pwch, cubDest ) / sizeof( wchar_t );
bool bStrippedWhitespace = false;
// Walk through and skip over evil characters
int nWalk = 0;
for( int i=0; i<cwch; ++i )
{
if( !Q_IsMeanSpaceW( pwch[i] ) )
{
pwch[nWalk] = pwch[i];
++nWalk;
}
else
{
bStrippedWhitespace = true;
}
}
// Null terminate
pwch[nWalk-1] = L'\0';
// copy back, if necessary
if ( bStrippedWhitespace )
{
Q_UnicodeToUTF8( pwch, pch, cch );
}
return bStrippedWhitespace;
}
//-----------------------------------------------------------------------------
// Purpose: strips leading and trailing whitespace
//-----------------------------------------------------------------------------
bool Q_StripPrecedingAndTrailingWhitespaceW( wchar_t *pwch )
{
int cch = Q_wcslen( pwch );
// Early out and don't convert if we don't have any chars or leading/trailing ws.
if ( ( cch < 1 ) || ( !iswspace( pwch[ 0 ] ) && !iswspace( pwch[ cch - 1 ] ) ) )
return false;
// duplicate on stack
int cubDest = ( cch + 1 ) * sizeof( wchar_t );
wchar_t *pwchT = (wchar_t *)stackalloc( cubDest );
Q_wcsncpy( pwchT, pwch, cubDest );
bool bStrippedWhitespace = false;
pwchT = StripWhitespaceWorker( cch, pwch, &bStrippedWhitespace, false /* not aggressive */ );
// copy back, if necessary
if ( bStrippedWhitespace )
{
Q_wcsncpy( pwch, pwchT, cubDest );
}
return bStrippedWhitespace;
}
//-----------------------------------------------------------------------------
// Purpose: strips leading and trailing whitespace,
// and also strips punctuation and formatting characters with "clear"
// representations.
//-----------------------------------------------------------------------------
bool Q_AggressiveStripPrecedingAndTrailingWhitespaceW( wchar_t *pwch )
{
// duplicate on stack
int cch = Q_wcslen( pwch );
int cubDest = ( cch + 1 ) * sizeof( wchar_t );
wchar_t *pwchT = (wchar_t *)stackalloc( cubDest );
Q_wcsncpy( pwchT, pwch, cubDest );
bool bStrippedWhitespace = false;
pwchT = StripWhitespaceWorker( cch, pwch, &bStrippedWhitespace, true /* is aggressive */ );
// copy back, if necessary
if ( bStrippedWhitespace )
{
Q_wcsncpy( pwch, pwchT, cubDest );
}
return bStrippedWhitespace;
}
//-----------------------------------------------------------------------------
// Purpose: strips leading and trailing whitespace
//-----------------------------------------------------------------------------
bool Q_StripPrecedingAndTrailingWhitespace( char *pch )
{
int cch = Q_strlen( pch );
// Early out and don't convert if we don't have any chars or leading/trailing ws.
if ( ( cch < 1 ) || ( !isspace( (unsigned char)pch[ 0 ] ) && !isspace( (unsigned char)pch[ cch - 1 ] ) ) )
return false;
// convert to unicode
int cubDest = (cch + 1 ) * sizeof( wchar_t );
wchar_t *pwch = (wchar_t *)stackalloc( cubDest );
int cwch = Q_UTF8ToUnicode( pch, pwch, cubDest ) / sizeof( wchar_t );
bool bStrippedWhitespace = false;
pwch = StripWhitespaceWorker( cwch-1, pwch, &bStrippedWhitespace, false /* not aggressive */ );
// copy back, if necessary
if ( bStrippedWhitespace )
{
Q_UnicodeToUTF8( pwch, pch, cch );
}
return bStrippedWhitespace;
}
//-----------------------------------------------------------------------------
// Purpose: strips leading and trailing whitespace
//-----------------------------------------------------------------------------
bool Q_AggressiveStripPrecedingAndTrailingWhitespace( char *pch )
{
// convert to unicode
int cch = Q_strlen( pch );
int cubDest = (cch + 1 ) * sizeof( wchar_t );
wchar_t *pwch = (wchar_t *)stackalloc( cubDest );
int cwch = Q_UTF8ToUnicode( pch, pwch, cubDest ) / sizeof( wchar_t );
bool bStrippedWhitespace = false;
pwch = StripWhitespaceWorker( cwch-1, pwch, &bStrippedWhitespace, true /* is aggressive */ );
// copy back, if necessary
if ( bStrippedWhitespace )
{
Q_UnicodeToUTF8( pwch, pch, cch );
}
return bStrippedWhitespace;
}
//-----------------------------------------------------------------------------
// Purpose: Converts a ucs2 string to a unicode (wchar_t) one, no-op on win32
//-----------------------------------------------------------------------------
int _V_UCS2ToUnicode( const ucs2 *pUCS2, wchar_t *pUnicode, int cubDestSizeInBytes )
{
Assert( cubDestSizeInBytes >= sizeof( *pUnicode ) );
AssertValidWritePtr(pUnicode);
AssertValidReadPtr(pUCS2);
pUnicode[0] = 0;
#ifdef _WIN32
int cchResult = V_wcslen( pUCS2 );
V_memcpy( pUnicode, pUCS2, cubDestSizeInBytes );
#else
iconv_t conv_t = iconv_open( "UCS-4LE", "UCS-2LE" );
int cchResult = -1;
size_t nLenUnicde = cubDestSizeInBytes;
size_t nMaxUTF8 = cubDestSizeInBytes;
char *pIn = (char *)pUCS2;
char *pOut = (char *)pUnicode;
if ( conv_t > 0 )
{
cchResult = iconv( conv_t, &pIn, &nLenUnicde, &pOut, &nMaxUTF8 );
iconv_close( conv_t );
if ( (int)cchResult < 0 )
cchResult = 0;
else
cchResult = nMaxUTF8;
}
#endif
pUnicode[(cubDestSizeInBytes / sizeof(wchar_t)) - 1] = 0;
return cchResult;
}
#ifdef _PREFAST_
#pragma warning( pop ) // Restore the /analyze warnings
#endif
//-----------------------------------------------------------------------------
// Purpose: Converts a wchar_t string into a UCS2 string -noop on windows
//-----------------------------------------------------------------------------
int _V_UnicodeToUCS2( const wchar_t *pUnicode, int cubSrcInBytes, char *pUCS2, int cubDestSizeInBytes )
{
#ifdef _WIN32
// Figure out which buffer is smaller and convert from bytes to character
// counts.
int cchResult = min( (size_t)cubSrcInBytes/sizeof(wchar_t), cubDestSizeInBytes/sizeof(wchar_t) );
wchar_t *pDest = (wchar_t*)pUCS2;
wcsncpy( pDest, pUnicode, cchResult );
// Make sure we NULL-terminate.
pDest[ cchResult - 1 ] = 0;
#elif defined (POSIX)
iconv_t conv_t = iconv_open( "UCS-2LE", "UTF-32LE" );
size_t cchResult = -1;
size_t nLenUnicde = cubSrcInBytes;
size_t nMaxUCS2 = cubDestSizeInBytes;
char *pIn = (char*)pUnicode;
char *pOut = pUCS2;
if ( conv_t > 0 )
{
cchResult = iconv( conv_t, &pIn, &nLenUnicde, &pOut, &nMaxUCS2 );
iconv_close( conv_t );
if ( (int)cchResult < 0 )
cchResult = 0;
else
cchResult = cubSrcInBytes / sizeof( wchar_t );
}
#else
#error Must be implemented for this platform
#endif
return cchResult;
}
//-----------------------------------------------------------------------------
// Purpose: Converts a ucs-2 (windows wchar_t) string into a UTF8 (standard) string
//-----------------------------------------------------------------------------
int _V_UCS2ToUTF8( const ucs2 *pUCS2, char *pUTF8, int cubDestSizeInBytes )
{
AssertValidStringPtr(pUTF8, cubDestSizeInBytes);
AssertValidReadPtr(pUCS2);
pUTF8[0] = 0;
#ifdef _WIN32
// under win32 wchar_t == ucs2, sigh
int cchResult = WideCharToMultiByte( CP_UTF8, 0, pUCS2, -1, pUTF8, cubDestSizeInBytes, NULL, NULL );
#elif defined(POSIX)
iconv_t conv_t = iconv_open( "UTF-8", "UCS-2LE" );
size_t cchResult = -1;
// pUCS2 will be null-terminated so use that to work out the input
// buffer size. Note that we shouldn't assume iconv will stop when it
// finds a zero, and nLenUnicde should be given in bytes, so we multiply
// it by sizeof( ucs2 ) at the end.
size_t nLenUnicde = 0;
while ( pUCS2[nLenUnicde] )
{
++nLenUnicde;
}
nLenUnicde *= sizeof( ucs2 );
// Calculate number of bytes we want iconv to write, leaving space
// for the null-terminator
size_t nMaxUTF8 = cubDestSizeInBytes - 1;
char *pIn = (char *)pUCS2;
char *pOut = (char *)pUTF8;
if ( conv_t > 0 )
{
const size_t nBytesToWrite = nMaxUTF8;
cchResult = iconv( conv_t, &pIn, &nLenUnicde, &pOut, &nMaxUTF8 );
// Calculate how many bytes were actually written and use that to
// null-terminate our output string.
const size_t nBytesWritten = nBytesToWrite - nMaxUTF8;
pUTF8[nBytesWritten] = 0;
iconv_close( conv_t );
if ( (int)cchResult < 0 )
cchResult = 0;
else
cchResult = nMaxUTF8;
}
#endif
pUTF8[cubDestSizeInBytes - 1] = 0;
return cchResult;
}
//-----------------------------------------------------------------------------
// Purpose: Converts a UTF8 to ucs-2 (windows wchar_t)
//-----------------------------------------------------------------------------
int _V_UTF8ToUCS2( const char *pUTF8, int cubSrcInBytes, ucs2 *pUCS2, int cubDestSizeInBytes )
{
Assert( cubDestSizeInBytes >= sizeof(pUCS2[0]) );
AssertValidStringPtr(pUTF8, cubDestSizeInBytes);
AssertValidReadPtr(pUCS2);
pUCS2[0] = 0;
#ifdef _WIN32
// under win32 wchar_t == ucs2, sigh
int cchResult = MultiByteToWideChar( CP_UTF8, 0, pUTF8, -1, pUCS2, cubDestSizeInBytes / sizeof(wchar_t) );
#elif defined( _PS3 ) // bugbug JLB
int cchResult = 0;
Assert( 0 );
#elif defined(POSIX)
iconv_t conv_t = iconv_open( "UCS-2LE", "UTF-8" );
size_t cchResult = -1;
size_t nLenUnicde = cubSrcInBytes;
size_t nMaxUTF8 = cubDestSizeInBytes;
char *pIn = (char *)pUTF8;
char *pOut = (char *)pUCS2;
if ( conv_t > 0 )
{
cchResult = iconv( conv_t, &pIn, &nLenUnicde, &pOut, &nMaxUTF8 );
iconv_close( conv_t );
if ( (int)cchResult < 0 )
cchResult = 0;
else
cchResult = cubSrcInBytes;
}
#endif
pUCS2[ (cubDestSizeInBytes/sizeof(ucs2)) - 1] = 0;
return cchResult;
}
//-----------------------------------------------------------------------------
// Purpose: Returns the 4 bit nibble for a hex character
// Input : c -
// Output : unsigned char
//-----------------------------------------------------------------------------
unsigned char V_nibble( char c )
{
if ( ( c >= '0' ) &&
( c <= '9' ) )
{
return (unsigned char)(c - '0');
}
if ( ( c >= 'A' ) &&
( c <= 'F' ) )
{
return (unsigned char)(c - 'A' + 0x0a);
}
if ( ( c >= 'a' ) &&
( c <= 'f' ) )
{
return (unsigned char)(c - 'a' + 0x0a);
}
return '0';
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *in -
// numchars -
// *out -
// maxoutputbytes -
//-----------------------------------------------------------------------------
void V_hextobinary( char const *in, int numchars, byte *out, int maxoutputbytes )
{
int len = V_strlen( in );
numchars = min( len, numchars );
// Make sure it's even
numchars = ( numchars ) & ~0x1;
// Must be an even # of input characters (two chars per output byte)
Assert( numchars >= 2 );
memset( out, 0x00, maxoutputbytes );
byte *p;
int i;
p = out;
for ( i = 0;
( i < numchars ) && ( ( p - out ) < maxoutputbytes );
i+=2, p++ )
{
*p = ( V_nibble( in[i] ) << 4 ) | V_nibble( in[i+1] );
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *in -
// inputbytes -
// *out -
// outsize -
//-----------------------------------------------------------------------------
void V_binarytohex( const byte *in, int inputbytes, char *out, int outsize )
{
Assert( outsize >= 1 );
char doublet[10];
int i;
out[0]=0;
for ( i = 0; i < inputbytes; i++ )
{
unsigned char c = in[i];
V_snprintf( doublet, sizeof( doublet ), "%02x", c );
V_strncat( out, doublet, outsize, COPY_ALL_CHARACTERS );
}
}
// Even though \ on Posix (Linux&Mac) isn't techincally a path separator we are
// now counting it as one even Posix since so many times our filepaths aren't actual
// paths but rather text strings passed in from data files, treating \ as a pathseparator
// covers the full range of cases
bool PATHSEPARATOR( char c )
{
return c == '\\' || c == '/';
}
//-----------------------------------------------------------------------------
// Purpose: Extracts the base name of a file (no path, no extension, assumes '/' or '\' as path separator)
// Input : *in -
// *out -
// maxlen -
//-----------------------------------------------------------------------------
void V_FileBase( const char *in, char *out, int maxlen )
{
Assert( maxlen >= 1 );
Assert( in );
Assert( out );
if ( !in || !in[ 0 ] )
{
*out = 0;
return;
}
int len, start, end;
len = V_strlen( in );
// scan backward for '.'
end = len - 1;
while ( end&& in[end] != '.' && !PATHSEPARATOR( in[end] ) )
{
end--;
}
if ( in[end] != '.' ) // no '.', copy to end
{
end = len-1;
}
else
{
end--; // Found ',', copy to left of '.'
}
// Scan backward for '/'
start = len-1;
while ( start >= 0 && !PATHSEPARATOR( in[start] ) )
{
start--;
}
if ( start < 0 || !PATHSEPARATOR( in[start] ) )
{
start = 0;
}
else
{
start++;
}
// Length of new sting
len = end - start + 1;
int maxcopy = min( len + 1, maxlen );
// Copy partial string
V_strncpy( out, &in[start], maxcopy );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *ppath -
//-----------------------------------------------------------------------------
void V_StripTrailingSlash( char *ppath )
{
Assert( ppath );
int len = V_strlen( ppath );
if ( len > 0 )
{
if ( PATHSEPARATOR( ppath[ len - 1 ] ) )
{
ppath[ len - 1 ] = 0;
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *ppline -
//-----------------------------------------------------------------------------
void V_StripTrailingWhitespace( char *ppline )
{
Assert( ppline );
int len = V_strlen( ppline );
while ( len > 0 )
{
if ( !V_isspace( ppline[ len - 1 ] ) )
break;
ppline[ len - 1 ] = 0;
len--;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *ppline -
//-----------------------------------------------------------------------------
void V_StripLeadingWhitespace( char *ppline )
{
Assert( ppline );
// Skip past initial whitespace
int skip = 0;
while( V_isspace( ppline[ skip ] ) )
skip++;
// Shuffle the rest of the string back (including the NULL-terminator)
if ( skip )
{
while( ( ppline[0] = ppline[skip] ) != 0 )
ppline++;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *ppline -
//-----------------------------------------------------------------------------
void V_StripSurroundingQuotes( char *ppline )
{
Assert( ppline );
int len = V_strlen( ppline ) - 2;
if ( ( ppline[0] == '"' ) && ( len >= 0 ) && ( ppline[len+1] == '"' ) )
{
for ( int i = 0; i < len; i++ )
ppline[i] = ppline[i+1];
ppline[len] = 0;
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *in -
// *out -
// outSize -
//-----------------------------------------------------------------------------
void V_StripExtension( const char *in, char *out, int outSize )
{
// Find the last dot. If it's followed by a dot or a slash, then it's part of a
// directory specifier like ../../somedir/./blah.
// scan backward for '.'
int end = V_strlen( in ) - 1;
while ( end > 0 && in[end] != '.' && !PATHSEPARATOR( in[end] ) )
{
--end;
}
if (end > 0 && !PATHSEPARATOR( in[end] ) && end < outSize)
{
int nChars = min( end, outSize-1 );
if ( out != in )
{
memcpy( out, in, nChars );
}
out[nChars] = 0;
}
else
{
// nothing found
if ( out != in )
{
V_strncpy( out, in, outSize );
}
}
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *path -
// *extension -
// pathStringLength -
//-----------------------------------------------------------------------------
void V_DefaultExtension( char *path, const char *extension, int pathStringLength )
{
Assert( path );
Assert( pathStringLength >= 1 );
Assert( extension );
Assert( extension[0] == '.' );
char *src;
// if path doesn't have a .EXT, append extension
// (extension should include the .)
src = path + V_strlen(path) - 1;
while ( !PATHSEPARATOR( *src ) && ( src > path ) )
{
if (*src == '.')
{
// it has an extension
return;
}
src--;
}
// Concatenate the desired extension
V_strncat( path, extension, pathStringLength, COPY_ALL_CHARACTERS );
}
//-----------------------------------------------------------------------------
// Purpose: Force extension...
// Input : *path -
// *extension -
// pathStringLength -
//-----------------------------------------------------------------------------
void V_SetExtension( char *path, const char *extension, int pathStringLength )
{
V_StripExtension( path, path, pathStringLength );
// We either had an extension and stripped it, or didn't have an extension
// at all. Either way, we need to concatenate our extension now.
// extension is not required to start with '.', so if it's not there,
// then append that first.
if ( extension[0] != '.' )
{
V_strncat( path, ".", pathStringLength, COPY_ALL_CHARACTERS );
}
V_strncat( path, extension, pathStringLength, COPY_ALL_CHARACTERS );
}
//-----------------------------------------------------------------------------
// Purpose: Remove final filename from string
// Input : *path -
// Output : void V_StripFilename
//-----------------------------------------------------------------------------
void V_StripFilename (char *path)
{
int length;
length = V_strlen( path )-1;
if ( length <= 0 )
return;
while ( length > 0 &&
!PATHSEPARATOR( path[length] ) )
{
length--;
}
path[ length ] = 0;
}
#ifdef _WIN32
#define CORRECT_PATH_SEPARATOR '\\'
#define INCORRECT_PATH_SEPARATOR '/'
#elif POSIX
#define CORRECT_PATH_SEPARATOR '/'
#define INCORRECT_PATH_SEPARATOR '\\'
#endif
//-----------------------------------------------------------------------------
// Purpose: Changes all '/' or '\' characters into separator
// Input : *pname -
// separator -
//-----------------------------------------------------------------------------
void V_FixSlashes( char *pname, char separator /* = CORRECT_PATH_SEPARATOR */ )
{
while ( *pname )
{
if ( *pname == INCORRECT_PATH_SEPARATOR || *pname == CORRECT_PATH_SEPARATOR )
{
*pname = separator;
}
pname++;
}
}
//-----------------------------------------------------------------------------
// Purpose: This function fixes cases of filenames like materials\\blah.vmt or somepath\otherpath\\ and removes the extra double slash.
//-----------------------------------------------------------------------------
void V_FixDoubleSlashes( char *pStr )
{
int len = V_strlen( pStr );
for ( int i=1; i < len-1; i++ )
{
if ( (pStr[i] == '/' || pStr[i] == '\\') && (pStr[i+1] == '/' || pStr[i+1] == '\\') )
{
// This means there's a double slash somewhere past the start of the filename. That
// can happen in Hammer if they use a material in the root directory. You'll get a filename
// that looks like 'materials\\blah.vmt'
V_memmove( &pStr[i], &pStr[i+1], len - i );
--len;
}
}
}
//-----------------------------------------------------------------------------
// Purpose: Strip off the last directory from dirName
// Input : *dirName -
// maxlen -
// Output : Returns true on success, false on failure.
//-----------------------------------------------------------------------------
bool V_StripLastDir( char *dirName, int maxlen )
{
if( dirName[0] == 0 ||
!V_stricmp( dirName, "./" ) ||
!V_stricmp( dirName, ".\\" ) )
return false;
int len = V_strlen( dirName );
Assert( len < maxlen );
// skip trailing slash
if ( PATHSEPARATOR( dirName[len-1] ) )
{
len--;
}
while ( len > 0 )
{
if ( PATHSEPARATOR( dirName[len-1] ) )
{
dirName[len] = 0;
V_FixSlashes( dirName, CORRECT_PATH_SEPARATOR );
return true;
}
len--;
}
// Allow it to return an empty string and true. This can happen if something like "tf2/" is passed in.
// The correct behavior is to strip off the last directory ("tf2") and return true.
if( len == 0 )
{
V_snprintf( dirName, maxlen, ".%c", CORRECT_PATH_SEPARATOR );
return true;
}
return true;
}
//-----------------------------------------------------------------------------
// Purpose: Returns a pointer to the beginning of the unqualified file name
// (no path information)
// Input: in - file name (may be unqualified, relative or absolute path)
// Output: pointer to unqualified file name
//-----------------------------------------------------------------------------
const char * V_UnqualifiedFileName( const char * in )
{
// back up until the character after the first path separator we find,
// or the beginning of the string
const char * out = in + strlen( in ) - 1;
while ( ( out > in ) && ( !PATHSEPARATOR( *( out-1 ) ) ) )
out--;
return out;
}
//-----------------------------------------------------------------------------
// Purpose: Composes a path and filename together, inserting a path separator
// if need be
// Input: path - path to use
// filename - filename to use
// dest - buffer to compose result in
// destSize - size of destination buffer
//-----------------------------------------------------------------------------
void V_ComposeFileName( const char *path, const char *filename, char *dest, int destSize )
{
V_strncpy( dest, path, destSize );
V_FixSlashes( dest );
V_AppendSlash( dest, destSize );
V_strncat( dest, filename, destSize, COPY_ALL_CHARACTERS );
V_FixSlashes( dest );
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *path -
// *dest -
// destSize -
// Output : void V_ExtractFilePath
//-----------------------------------------------------------------------------
bool V_ExtractFilePath (const char *path, char *dest, int destSize )
{
Assert( destSize >= 1 );
if ( destSize < 1 )
{
return false;
}
// Last char
int len = V_strlen(path);
const char *src = path + (len ? len-1 : 0);
// back up until a \ or the start
while ( src != path && !PATHSEPARATOR( *(src-1) ) )
{
src--;
}
int copysize = min( (int)((ptrdiff_t)src - (ptrdiff_t)path), destSize - 1 );
memcpy( dest, path, copysize );
dest[copysize] = 0;
return copysize != 0 ? true : false;
}
//-----------------------------------------------------------------------------
// Purpose:
// Input : *path -
// *dest -
// destSize -
// Output : void V_ExtractFileExtension
//-----------------------------------------------------------------------------
void V_ExtractFileExtension( const char *path, char *dest, int destSize )
{
*dest = NULL;
const char * extension = V_GetFileExtension( path );
if ( NULL != extension )
V_strncpy( dest, extension, destSize );
}
//-----------------------------------------------------------------------------
// Purpose: Returns a pointer to the file extension within a file name string
// Input: in - file name
// Output: pointer to beginning of extension (after the "."), or NULL
// if there is no extension
//-----------------------------------------------------------------------------
const char * V_GetFileExtension( const char * path )
{
const char *src;
src = path + strlen(path) - 1;
//
// back up until a . or the start
//
while (src != path && *(src-1) != '.' )
src--;
// check to see if the '.' is part of a pathname
if (src == path || PATHSEPARATOR( *src ) )
{
return NULL; // no extension
}
return src;
}
//-----------------------------------------------------------------------------
// Purpose: Returns a pointer to the filename part of a path string
// Input: in - file name
// Output: pointer to beginning of filename (after the "/"). If there were no /,
// output is identical to input
//-----------------------------------------------------------------------------
const char * V_GetFileName( const char * path )
{
return V_UnqualifiedFileName( path );
}
bool V_RemoveDotSlashes( char *pFilename, char separator, bool bRemoveDoubleSlashes /* = true */ )
{
char *pIn = pFilename;
char *pOut = pFilename;
bool bRetVal = true;
bool bBoundary = true;
while ( *pIn )
{
if ( bBoundary && pIn[0] == '.' && pIn[1] == '.' && ( PATHSEPARATOR( pIn[2] ) || !pIn[2] ) )
{
// Get rid of /../ or trailing /.. by backing pOut up to previous separator
// Eat the last separator (or repeated separators) we wrote out
while ( pOut != pFilename && pOut[-1] == separator )
{
--pOut;
}
while ( true )
{
if ( pOut == pFilename )
{
bRetVal = false; // backwards compat. return value, even though we continue handling
break;
}
--pOut;
if ( *pOut == separator )
{
break;
}
}
// Skip the '..' but not the slash, next loop iteration will handle separator
pIn += 2;
bBoundary = ( pOut == pFilename );
}
else if ( bBoundary && pIn[0] == '.' && ( PATHSEPARATOR( pIn[1] ) || !pIn[1] ) )
{
// Handle "./" by simply skipping this sequence. bBoundary is unchanged.
if ( PATHSEPARATOR( pIn[1] ) )
{
pIn += 2;
}
else
{
// Special case: if trailing "." is preceded by separator, eg "path/.",
// then the final separator should also be stripped. bBoundary may then
// be in an incorrect state, but we are at the end of processing anyway
// so we don't really care (the processing loop is about to terminate).
if ( pOut != pFilename && pOut[-1] == separator )
{
--pOut;
}
pIn += 1;
}
}
else if ( PATHSEPARATOR( pIn[0] ) )
{
*pOut = separator;
pOut += 1 - (bBoundary & bRemoveDoubleSlashes & (pOut != pFilename));
pIn += 1;
bBoundary = true;
}
else
{
if ( pOut != pIn )
{
*pOut = *pIn;
}
pOut += 1;
pIn += 1;
bBoundary = false;
}
}
*pOut = 0;
return bRetVal;
}
void V_AppendSlash( char *pStr, int strSize )
{
int len = V_strlen( pStr );
if ( len > 0 && !PATHSEPARATOR(pStr[len-1]) )
{
if ( len+1 >= strSize )
Error( "V_AppendSlash: ran out of space on %s.", pStr );
pStr[len] = CORRECT_PATH_SEPARATOR;
pStr[len+1] = 0;
}
}
void V_MakeAbsolutePath( char *pOut, int outLen, const char *pPath, const char *pStartingDir )
{
if ( V_IsAbsolutePath( pPath ) )
{
// pPath is not relative.. just copy it.
V_strncpy( pOut, pPath, outLen );
}
else
{
// Make sure the starting directory is absolute..
if ( pStartingDir && V_IsAbsolutePath( pStartingDir ) )
{
V_strncpy( pOut, pStartingDir, outLen );
}
else
{
if ( !_getcwd( pOut, outLen ) )
Error( "V_MakeAbsolutePath: _getcwd failed." );
if ( pStartingDir )
{
V_AppendSlash( pOut, outLen );
V_strncat( pOut, pStartingDir, outLen, COPY_ALL_CHARACTERS );
}
}
// Concatenate the paths.
V_AppendSlash( pOut, outLen );
V_strncat( pOut, pPath, outLen, COPY_ALL_CHARACTERS );
}
if ( !V_RemoveDotSlashes( pOut ) )
Error( "V_MakeAbsolutePath: tried to \"..\" past the root." );
//V_FixSlashes( pOut ); - handled by V_RemoveDotSlashes
}
//-----------------------------------------------------------------------------
// Makes a relative path
//-----------------------------------------------------------------------------
bool V_MakeRelativePath( const char *pFullPath, const char *pDirectory, char *pRelativePath, int nBufLen )
{
pRelativePath[0] = 0;
const char *pPath = pFullPath;
const char *pDir = pDirectory;
// Strip out common parts of the path
const char *pLastCommonPath = NULL;
const char *pLastCommonDir = NULL;
while ( *pPath && ( FastToLower( *pPath ) == FastToLower( *pDir ) ||
( PATHSEPARATOR( *pPath ) && ( PATHSEPARATOR( *pDir ) || (*pDir == 0) ) ) ) )
{
if ( PATHSEPARATOR( *pPath ) )
{
pLastCommonPath = pPath + 1;
pLastCommonDir = pDir + 1;
}
if ( *pDir == 0 )
{
--pLastCommonDir;
break;
}
++pDir; ++pPath;
}
// Nothing in common
if ( !pLastCommonPath )
return false;
// For each path separator remaining in the dir, need a ../
int nOutLen = 0;
bool bLastCharWasSeparator = true;
for ( ; *pLastCommonDir; ++pLastCommonDir )
{
if ( PATHSEPARATOR( *pLastCommonDir ) )
{
pRelativePath[nOutLen++] = '.';
pRelativePath[nOutLen++] = '.';
pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR;
bLastCharWasSeparator = true;
}
else
{
bLastCharWasSeparator = false;
}
}
// Deal with relative paths not specified with a trailing slash
if ( !bLastCharWasSeparator )
{
pRelativePath[nOutLen++] = '.';
pRelativePath[nOutLen++] = '.';
pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR;
}
// Copy the remaining part of the relative path over, fixing the path separators
for ( ; *pLastCommonPath; ++pLastCommonPath )
{
if ( PATHSEPARATOR( *pLastCommonPath ) )
{
pRelativePath[nOutLen++] = CORRECT_PATH_SEPARATOR;
}
else
{
pRelativePath[nOutLen++] = *pLastCommonPath;
}
// Check for overflow
if ( nOutLen == nBufLen - 1 )
break;
}
pRelativePath[nOutLen] = 0;
return true;
}
//-----------------------------------------------------------------------------
// small helper function shared by lots of modules
//-----------------------------------------------------------------------------
bool V_IsAbsolutePath( const char *pStr )
{
bool bIsAbsolute = ( pStr[0] && pStr[1] == ':' ) || pStr[0] == '/' || pStr[0] == '\\';
if ( IsX360() && !bIsAbsolute )
{
bIsAbsolute = ( V_stristr( pStr, ":" ) != NULL );
}
return bIsAbsolute;
}
// Copies at most nCharsToCopy bytes from pIn into pOut.
// Returns false if it would have overflowed pOut's buffer.
static bool CopyToMaxChars( char *pOut, int outSize, const char *pIn, int nCharsToCopy )
{
if ( outSize == 0 )
return false;
int iOut = 0;
while ( *pIn && nCharsToCopy > 0 )
{
if ( iOut == (outSize-1) )
{
pOut[iOut] = 0;
return false;
}
pOut[iOut] = *pIn;
++iOut;
++pIn;
--nCharsToCopy;
}
pOut[iOut] = 0;
return true;
}
//-----------------------------------------------------------------------------
// Fixes up a file name, removing dot slashes, fixing slashes, converting to lowercase, etc.
//-----------------------------------------------------------------------------
void V_FixupPathName( char *pOut, size_t nOutLen, const char *pPath )
{
V_strncpy( pOut, pPath, nOutLen );
V_RemoveDotSlashes( pOut, CORRECT_PATH_SEPARATOR, true );
#ifdef WIN32
V_strlower( pOut );
#endif
}
// Returns true if it completed successfully.
// If it would overflow pOut, it fills as much as it can and returns false.
bool V_StrSubst(
const char *pIn,
const char *pMatch,
const char *pReplaceWith,
char *pOut,
int outLen,
bool bCaseSensitive
)
{
int replaceFromLen = strlen( pMatch );
int replaceToLen = strlen( pReplaceWith );
const char *pInStart = pIn;
char *pOutPos = pOut;
pOutPos[0] = 0;
while ( 1 )
{
int nRemainingOut = outLen - (pOutPos - pOut);
const char *pTestPos = ( bCaseSensitive ? strstr( pInStart, pMatch ) : V_stristr( pInStart, pMatch ) );
if ( pTestPos )
{
// Found an occurence of pMatch. First, copy whatever leads up to the string.
int copyLen = pTestPos - pInStart;
if ( !CopyToMaxChars( pOutPos, nRemainingOut, pInStart, copyLen ) )
return false;
// Did we hit the end of the output string?
if ( copyLen > nRemainingOut-1 )
return false;
pOutPos += strlen( pOutPos );
nRemainingOut = outLen - (pOutPos - pOut);
// Now add the replacement string.
if ( !CopyToMaxChars( pOutPos, nRemainingOut, pReplaceWith, replaceToLen ) )
return false;
pInStart += copyLen + replaceFromLen;
pOutPos += replaceToLen;
}
else
{
// We're at the end of pIn. Copy whatever remains and get out.
int copyLen = strlen( pInStart );
V_strncpy( pOutPos, pInStart, nRemainingOut );
return ( copyLen <= nRemainingOut-1 );
}
}
}
char* AllocString( const char *pStr, int nMaxChars )
{
int allocLen;
if ( nMaxChars == -1 )
allocLen = strlen( pStr ) + 1;
else
allocLen = min( (int)strlen(pStr), nMaxChars ) + 1;
char *pOut = new char[allocLen];
V_strncpy( pOut, pStr, allocLen );
return pOut;
}
void V_SplitString2( const char *pString, const char **pSeparators, int nSeparators, CUtlVector<char*> &outStrings )
{
outStrings.Purge();
const char *pCurPos = pString;
while ( 1 )
{
int iFirstSeparator = -1;
const char *pFirstSeparator = 0;
for ( int i=0; i < nSeparators; i++ )
{
const char *pTest = V_stristr( pCurPos, pSeparators[i] );
if ( pTest && (!pFirstSeparator || pTest < pFirstSeparator) )
{
iFirstSeparator = i;
pFirstSeparator = pTest;
}
}
if ( pFirstSeparator )
{
// Split on this separator and continue on.
int separatorLen = strlen( pSeparators[iFirstSeparator] );
if ( pFirstSeparator > pCurPos )
{
outStrings.AddToTail( AllocString( pCurPos, pFirstSeparator-pCurPos ) );
}
pCurPos = pFirstSeparator + separatorLen;
}
else
{
// Copy the rest of the string
if ( strlen( pCurPos ) )
{
outStrings.AddToTail( AllocString( pCurPos, -1 ) );
}
return;
}
}
}
void V_SplitString( const char *pString, const char *pSeparator, CUtlVector<char*> &outStrings )
{
V_SplitString2( pString, &pSeparator, 1, outStrings );
}
bool V_GetCurrentDirectory( char *pOut, int maxLen )
{
return _getcwd( pOut, maxLen ) == pOut;
}
bool V_SetCurrentDirectory( const char *pDirName )
{
return _chdir( pDirName ) == 0;
}
// This function takes a slice out of pStr and stores it in pOut.
// It follows the Python slice convention:
// Negative numbers wrap around the string (-1 references the last character).
// Numbers are clamped to the end of the string.
void V_StrSlice( const char *pStr, int firstChar, int lastCharNonInclusive, char *pOut, int outSize )
{
if ( outSize == 0 )
return;
int length = strlen( pStr );
// Fixup the string indices.
if ( firstChar < 0 )
{
firstChar = length - (-firstChar % length);
}
else if ( firstChar >= length )
{
pOut[0] = 0;
return;
}
if ( lastCharNonInclusive < 0 )
{
lastCharNonInclusive = length - (-lastCharNonInclusive % length);
}
else if ( lastCharNonInclusive > length )
{
lastCharNonInclusive %= length;
}
if ( lastCharNonInclusive <= firstChar )
{
pOut[0] = 0;
return;
}
int copyLen = lastCharNonInclusive - firstChar;
if ( copyLen <= (outSize-1) )
{
memcpy( pOut, &pStr[firstChar], copyLen );
pOut[copyLen] = 0;
}
else
{
memcpy( pOut, &pStr[firstChar], outSize-1 );
pOut[outSize-1] = 0;
}
}
void V_StrLeft( const char *pStr, int nChars, char *pOut, int outSize )
{
if ( nChars == 0 )
{
if ( outSize != 0 )
pOut[0] = 0;
return;
}
V_StrSlice( pStr, 0, nChars, pOut, outSize );
}
void V_StrRight( const char *pStr, int nChars, char *pOut, int outSize )
{
int len = strlen( pStr );
if ( nChars >= len )
{
V_strncpy( pOut, pStr, outSize );
}
else
{
V_StrSlice( pStr, -nChars, strlen( pStr ), pOut, outSize );
}
}
//-----------------------------------------------------------------------------
// Convert multibyte to wchar + back
//-----------------------------------------------------------------------------
void V_strtowcs( const char *pString, int nInSize, wchar_t *pWString, int nOutSizeInBytes )
{
Assert( nOutSizeInBytes >= sizeof(pWString[0]) );
#ifdef _WIN32
int nOutSizeInChars = nOutSizeInBytes / sizeof(pWString[0]);
int result = MultiByteToWideChar( CP_UTF8, 0, pString, nInSize, pWString, nOutSizeInChars );
// If the string completely fails to fit then MultiByteToWideChar will return 0.
// If the string exactly fits but with no room for a null-terminator then MultiByteToWideChar
// will happily fill the buffer and omit the null-terminator, returning nOutSizeInChars.
// Either way we need to return an empty string rather than a bogus and possibly not
// null-terminated result.
if ( result <= 0 || result >= nOutSizeInChars )
{
// If nInSize includes the null-terminator then a result of nOutSizeInChars is
// legal. We check this by seeing if the last character in the output buffer is
// a zero.
if ( result == nOutSizeInChars && pWString[ nOutSizeInChars - 1 ] == 0)
{
// We're okay! Do nothing.
}
else
{
// The string completely to fit. Null-terminate the buffer.
*pWString = L'\0';
}
}
else
{
// We have successfully converted our string. Now we need to null-terminate it, because
// MultiByteToWideChar will only do that if nInSize includes the source null-terminator!
pWString[ result ] = 0;
}
#elif POSIX
if ( mbstowcs( pWString, pString, nOutSizeInBytes / sizeof(pWString[0]) ) <= 0 )
{
*pWString = 0;
}
#endif
}
void V_wcstostr( const wchar_t *pWString, int nInSize, char *pString, int nOutSizeInChars )
{
#ifdef _WIN32
int result = WideCharToMultiByte( CP_UTF8, 0, pWString, nInSize, pString, nOutSizeInChars, NULL, NULL );
// If the string completely fails to fit then MultiByteToWideChar will return 0.
// If the string exactly fits but with no room for a null-terminator then MultiByteToWideChar
// will happily fill the buffer and omit the null-terminator, returning nOutSizeInChars.
// Either way we need to return an empty string rather than a bogus and possibly not
// null-terminated result.
if ( result <= 0 || result >= nOutSizeInChars )
{
// If nInSize includes the null-terminator then a result of nOutSizeInChars is
// legal. We check this by seeing if the last character in the output buffer is
// a zero.
if ( result == nOutSizeInChars && pWString[ nOutSizeInChars - 1 ] == 0)
{
// We're okay! Do nothing.
}
else
{
*pString = '\0';
}
}
else
{
// We have successfully converted our string. Now we need to null-terminate it, because
// MultiByteToWideChar will only do that if nInSize includes the source null-terminator!
pString[ result ] = '\0';
}
#elif POSIX
if ( wcstombs( pString, pWString, nOutSizeInChars ) <= 0 )
{
*pString = '\0';
}
#endif
}
//--------------------------------------------------------------------------------
// backslashification
//--------------------------------------------------------------------------------
static char s_BackSlashMap[]="\tt\nn\rr\"\"\\\\";
char *V_AddBackSlashesToSpecialChars( char const *pSrc )
{
// first, count how much space we are going to need
int nSpaceNeeded = 0;
for( char const *pScan = pSrc; *pScan; pScan++ )
{
nSpaceNeeded++;
for(char const *pCharSet=s_BackSlashMap; *pCharSet; pCharSet += 2 )
{
if ( *pCharSet == *pScan )
nSpaceNeeded++; // we need to store a bakslash
}
}
char *pRet = new char[ nSpaceNeeded + 1 ]; // +1 for null
char *pOut = pRet;
for( char const *pScan = pSrc; *pScan; pScan++ )
{
bool bIsSpecial = false;
for(char const *pCharSet=s_BackSlashMap; *pCharSet; pCharSet += 2 )
{
if ( *pCharSet == *pScan )
{
*( pOut++ ) = '\\';
*( pOut++ ) = pCharSet[1];
bIsSpecial = true;
break;
}
}
if (! bIsSpecial )
{
*( pOut++ ) = *pScan;
}
}
*( pOut++ ) = 0;
return pRet;
}
//-----------------------------------------------------------------------------
// Purpose: Helper for converting a numeric value to a hex digit, value should be 0-15.
//-----------------------------------------------------------------------------
char cIntToHexDigit( int nValue )
{
Assert( nValue >= 0 && nValue <= 15 );
return "0123456789ABCDEF"[ nValue & 15 ];
}
//-----------------------------------------------------------------------------
// Purpose: Helper for converting a hex char value to numeric, return -1 if the char
// is not a valid hex digit.
//-----------------------------------------------------------------------------
int iHexCharToInt( char cValue )
{
int32 iValue = cValue;
if ( (uint32)( iValue - '0' ) < 10 )
return iValue - '0';
iValue |= 0x20;
if ( (uint32)( iValue - 'a' ) < 6 )
return iValue - 'a' + 10;
return -1;
}
//-----------------------------------------------------------------------------
// Purpose: Internal implementation of encode, works in the strict RFC manner, or
// with spaces turned to + like HTML form encoding.
//-----------------------------------------------------------------------------
void Q_URLEncodeInternal( char *pchDest, int nDestLen, const char *pchSource, int nSourceLen, bool bUsePlusForSpace )
{
if ( nDestLen < 3*nSourceLen )
{
pchDest[0] = '\0';
AssertMsg( false, "Target buffer for Q_URLEncode needs to be 3 times larger than source to guarantee enough space\n" );
return;
}
int iDestPos = 0;
for ( int i=0; i < nSourceLen; ++i )
{
// We allow only a-z, A-Z, 0-9, period, underscore, and hyphen to pass through unescaped.
// These are the characters allowed by both the original RFC 1738 and the latest RFC 3986.
// Current specs also allow '~', but that is forbidden under original RFC 1738.
if ( !( pchSource[i] >= 'a' && pchSource[i] <= 'z' ) && !( pchSource[i] >= 'A' && pchSource[i] <= 'Z' ) && !(pchSource[i] >= '0' && pchSource[i] <= '9' )
&& pchSource[i] != '-' && pchSource[i] != '_' && pchSource[i] != '.'
)
{
if ( bUsePlusForSpace && pchSource[i] == ' ' )
{
pchDest[iDestPos++] = '+';
}
else
{
pchDest[iDestPos++] = '%';
uint8 iValue = pchSource[i];
if ( iValue == 0 )
{
pchDest[iDestPos++] = '0';
pchDest[iDestPos++] = '0';
}
else
{
char cHexDigit1 = cIntToHexDigit( iValue % 16 );
iValue /= 16;
char cHexDigit2 = cIntToHexDigit( iValue );
pchDest[iDestPos++] = cHexDigit2;
pchDest[iDestPos++] = cHexDigit1;
}
}
}
else
{
pchDest[iDestPos++] = pchSource[i];
}
}
// Null terminate
pchDest[iDestPos++] = 0;
}
//-----------------------------------------------------------------------------
// Purpose: Internal implementation of decode, works in the strict RFC manner, or
// with spaces turned to + like HTML form encoding.
//
// Returns the amount of space used in the output buffer.
//-----------------------------------------------------------------------------
size_t Q_URLDecodeInternal( char *pchDecodeDest, int nDecodeDestLen, const char *pchEncodedSource, int nEncodedSourceLen, bool bUsePlusForSpace )
{
if ( nDecodeDestLen < nEncodedSourceLen )
{
AssertMsg( false, "Q_URLDecode needs a dest buffer at least as large as the source" );
return 0;
}
int iDestPos = 0;
for( int i=0; i < nEncodedSourceLen; ++i )
{
if ( bUsePlusForSpace && pchEncodedSource[i] == '+' )
{
pchDecodeDest[ iDestPos++ ] = ' ';
}
else if ( pchEncodedSource[i] == '%' )
{
// Percent signifies an encoded value, look ahead for the hex code, convert to numeric, and use that
// First make sure we have 2 more chars
if ( i < nEncodedSourceLen - 2 )
{
char cHexDigit1 = pchEncodedSource[i+1];
char cHexDigit2 = pchEncodedSource[i+2];
// Turn the chars into a hex value, if they are not valid, then we'll
// just place the % and the following two chars direct into the string,
// even though this really shouldn't happen, who knows what bad clients
// may do with encoding.
bool bValid = false;
int iValue = iHexCharToInt( cHexDigit1 );
if ( iValue != -1 )
{
iValue *= 16;
int iValue2 = iHexCharToInt( cHexDigit2 );
if ( iValue2 != -1 )
{
iValue += iValue2;
pchDecodeDest[ iDestPos++ ] = iValue;
bValid = true;
}
}
if ( !bValid )
{
pchDecodeDest[ iDestPos++ ] = '%';
pchDecodeDest[ iDestPos++ ] = cHexDigit1;
pchDecodeDest[ iDestPos++ ] = cHexDigit2;
}
}
// Skip ahead
i += 2;
}
else
{
pchDecodeDest[ iDestPos++ ] = pchEncodedSource[i];
}
}
// We may not have extra room to NULL terminate, since this can be used on raw data, but if we do
// go ahead and do it as this can avoid bugs.
if ( iDestPos < nDecodeDestLen )
{
pchDecodeDest[iDestPos] = 0;
}
return (size_t)iDestPos;
}
//-----------------------------------------------------------------------------
// Purpose: Encodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
// This version of the call isn't a strict RFC implementation, but uses + for space as is
// the standard in HTML form encoding, despite it not being part of the RFC.
//
// Dest buffer should be at least as large as source buffer to guarantee room for decode.
//-----------------------------------------------------------------------------
void Q_URLEncode( char *pchDest, int nDestLen, const char *pchSource, int nSourceLen )
{
return Q_URLEncodeInternal( pchDest, nDestLen, pchSource, nSourceLen, true );
}
//-----------------------------------------------------------------------------
// Purpose: Decodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
// This version of the call isn't a strict RFC implementation, but uses + for space as is
// the standard in HTML form encoding, despite it not being part of the RFC.
//
// Dest buffer should be at least as large as source buffer to guarantee room for decode.
// Dest buffer being the same as the source buffer (decode in-place) is explicitly allowed.
//-----------------------------------------------------------------------------
size_t Q_URLDecode( char *pchDecodeDest, int nDecodeDestLen, const char *pchEncodedSource, int nEncodedSourceLen )
{
return Q_URLDecodeInternal( pchDecodeDest, nDecodeDestLen, pchEncodedSource, nEncodedSourceLen, true );
}
//-----------------------------------------------------------------------------
// Purpose: Encodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
// This version will not encode space as + (which HTML form encoding uses despite not being part of the RFC)
//
// Dest buffer should be at least as large as source buffer to guarantee room for decode.
//-----------------------------------------------------------------------------
void Q_URLEncodeRaw( char *pchDest, int nDestLen, const char *pchSource, int nSourceLen )
{
return Q_URLEncodeInternal( pchDest, nDestLen, pchSource, nSourceLen, false );
}
//-----------------------------------------------------------------------------
// Purpose: Decodes a string (or binary data) from URL encoding format, see rfc1738 section 2.2.
// This version will not recognize + as a space (which HTML form encoding uses despite not being part of the RFC)
//
// Dest buffer should be at least as large as source buffer to guarantee room for decode.
// Dest buffer being the same as the source buffer (decode in-place) is explicitly allowed.
//-----------------------------------------------------------------------------
size_t Q_URLDecodeRaw( char *pchDecodeDest, int nDecodeDestLen, const char *pchEncodedSource, int nEncodedSourceLen )
{
return Q_URLDecodeInternal( pchDecodeDest, nDecodeDestLen, pchEncodedSource, nEncodedSourceLen, false );
}
#if defined( LINUX ) || defined( _PS3 )
extern "C" void qsort_s( void *base, size_t num, size_t width, int (*compare )(void *, const void *, const void *), void * context );
#endif
void V_qsort_s( void *base, size_t num, size_t width, int ( __cdecl *compare )(void *, const void *, const void *), void * context )
{
#if defined OSX
// the arguments are swapped 'round on the mac - awesome, huh?
return qsort_r( base, num, width, context, compare );
#else
return qsort_s( base, num, width, compare, context );
#endif
}
//-----------------------------------------------------------------------------
// Purpose: format the time and/or date with the user's current locale
// If timeVal is 0, gets the current time
//
// This is generally for use with chatroom dialogs, etc. which need to be
// able to say "Last message received: %date% at %time%"
//
// Note that this uses time_t because RTime32 is not hooked-up on the client
//-----------------------------------------------------------------------------
bool BGetLocalFormattedDateAndTime( time_t timeVal, char *pchDate, int cubDate, char *pchTime, int cubTime )
{
if ( 0 == timeVal || timeVal < 0 )
{
// get the current time
time( &timeVal );
}
if ( timeVal )
{
// Convert it to our local time
struct tm tmStruct;
struct tm tmToDisplay = *( Plat_localtime( ( const time_t* )&timeVal, &tmStruct ) );
#ifdef POSIX
if ( pchDate != NULL )
{
pchDate[ 0 ] = 0;
if ( 0 == strftime( pchDate, cubDate, "%A %b %d", &tmToDisplay ) )
return false;
}
if ( pchTime != NULL )
{
pchTime[ 0 ] = 0;
if ( 0 == strftime( pchTime, cubTime - 6, "%I:%M ", &tmToDisplay ) )
return false;
// append am/pm in lower case (since strftime doesn't have a lowercase formatting option)
if (tmToDisplay.tm_hour >= 12)
{
Q_strcat( pchTime, "p.m.", cubTime );
}
else
{
Q_strcat( pchTime, "a.m.", cubTime );
}
}
#else // WINDOWS
// convert time_t to a SYSTEMTIME
SYSTEMTIME st;
st.wHour = tmToDisplay.tm_hour;
st.wMinute = tmToDisplay.tm_min;
st.wSecond = tmToDisplay.tm_sec;
st.wDay = tmToDisplay.tm_mday;
st.wMonth = tmToDisplay.tm_mon + 1;
st.wYear = tmToDisplay.tm_year + 1900;
st.wDayOfWeek = tmToDisplay.tm_wday;
st.wMilliseconds = 0;
WCHAR rgwch[ MAX_PATH ];
if ( pchDate != NULL )
{
pchDate[ 0 ] = 0;
if ( !GetDateFormatW( LOCALE_USER_DEFAULT, DATE_LONGDATE, &st, NULL, rgwch, MAX_PATH ) )
return false;
Q_strncpy( pchDate, CStrAutoEncode( rgwch ).ToString(), cubDate );
}
if ( pchTime != NULL )
{
pchTime[ 0 ] = 0;
if ( !GetTimeFormatW( LOCALE_USER_DEFAULT, TIME_NOSECONDS, &st, NULL, rgwch, MAX_PATH ) )
return false;
Q_strncpy( pchTime, CStrAutoEncode( rgwch ).ToString(), cubTime );
}
#endif
return true;
}
return false;
}
// And a couple of helpers so people don't have to remember the order of the parameters in the above function
bool BGetLocalFormattedDate( time_t timeVal, char *pchDate, int cubDate )
{
return BGetLocalFormattedDateAndTime( timeVal, pchDate, cubDate, NULL, 0 );
}
bool BGetLocalFormattedTime( time_t timeVal, char *pchTime, int cubTime )
{
return BGetLocalFormattedDateAndTime( timeVal, NULL, 0, pchTime, cubTime );
}
// Prints out a memory dump where stuff that's ascii is human readable, etc.
void V_LogMultiline( bool input, char const *label, const char *data, size_t len, CUtlString &output )
{
static const char HEX[] = "0123456789abcdef";
const char * direction = (input ? " << " : " >> ");
const size_t LINE_SIZE = 24;
char hex_line[LINE_SIZE * 9 / 4 + 2], asc_line[LINE_SIZE + 1];
while (len > 0)
{
V_memset(asc_line, ' ', sizeof(asc_line));
V_memset(hex_line, ' ', sizeof(hex_line));
size_t line_len = MIN(len, LINE_SIZE);
for (size_t i=0; i<line_len; ++i) {
unsigned char ch = static_cast<unsigned char>(data[i]);
asc_line[i] = ( V_isprint(ch) && !V_iscntrl(ch) ) ? data[i] : '.';
hex_line[i*2 + i/4] = HEX[ch >> 4];
hex_line[i*2 + i/4 + 1] = HEX[ch & 0xf];
}
asc_line[sizeof(asc_line)-1] = 0;
hex_line[sizeof(hex_line)-1] = 0;
output += CFmtStr( "%s %s %s %s\n", label, direction, asc_line, hex_line );
data += line_len;
len -= line_len;
}
}
#ifdef WIN32
// Win32 CRT doesn't support the full range of UChar32, has no extended planes
inline int V_iswspace( int c ) { return ( c <= 0xFFFF ) ? iswspace( (wint_t)c ) : 0; }
#else
#define V_iswspace(x) iswspace(x)
#endif
//-----------------------------------------------------------------------------
// Purpose: Slightly modified strtok. Does not modify the input string. Does
// not skip over more than one separator at a time. This allows parsing
// strings where tokens between separators may or may not be present:
//
// Door01,,,0 would be parsed as "Door01" "" "" "0"
// Door01,Open,,0 would be parsed as "Door01" "Open" "" "0"
//
// Input : token - Returns with a token, or zero length if the token was missing.
// str - String to parse.
// sep - Character to use as separator. UNDONE: allow multiple separator chars
// Output : Returns a pointer to the next token to be parsed.
//-----------------------------------------------------------------------------
const char *nexttoken(char *token, size_t nMaxTokenLen, const char *str, char sep)
{
if (nMaxTokenLen < 1)
{
Assert(nMaxTokenLen > 0);
return NULL;
}
if ((str == NULL) || (*str == '\0'))
{
*token = '\0';
return(NULL);
}
char *pTokenLast = token + nMaxTokenLen - 1;
//
// Copy everything up to the first separator into the return buffer.
// Do not include separators in the return buffer.
//
while ((*str != sep) && (*str != '\0') && (token < pTokenLast))
{
*token++ = *str++;
}
*token = '\0';
//
// Advance the pointer unless we hit the end of the input string.
//
if (*str == '\0')
{
return(str);
}
return(++str);
}
int V_StrTrim( char *pStr )
{
char *pSource = pStr;
char *pDest = pStr;
// skip white space at the beginning
while ( *pSource != 0 && V_isspace( *pSource ) )
{
pSource++;
}
// copy everything else
char *pLastWhiteBlock = NULL;
char *pStart = pDest;
while ( *pSource != 0 )
{
*pDest = *pSource++;
if ( V_isspace( *pDest ) )
{
if ( pLastWhiteBlock == NULL )
pLastWhiteBlock = pDest;
}
else
{
pLastWhiteBlock = NULL;
}
pDest++;
}
*pDest = 0;
// did we end in a whitespace block?
if ( pLastWhiteBlock != NULL )
{
// yep; shorten the string
pDest = pLastWhiteBlock;
*pLastWhiteBlock = 0;
}
return pDest - pStart;
}
#ifdef _WIN32
int64 V_strtoi64( const char *nptr, char **endptr, int base )
{
return _strtoi64( nptr, endptr, base );
}
uint64 V_strtoui64( const char *nptr, char **endptr, int base )
{
return _strtoui64( nptr, endptr, base );
}
#elif POSIX
int64 V_strtoi64( const char *nptr, char **endptr, int base )
{
return strtoll( nptr, endptr, base );
}
uint64 V_strtoui64( const char *nptr, char **endptr, int base )
{
return strtoull( nptr, endptr, base );
}
#endif
struct HtmlEntity_t
{
unsigned short uCharCode;
const char *pchEntity;
int nEntityLength;
};
const static HtmlEntity_t g_BasicHTMLEntities[] = {
{ '"', """, 6 },
{ '\'', "'", 6 },
{ '<', "<", 4 },
{ '>', ">", 4 },
{ '&', "&", 5 },
{ 0, NULL, 0 } // sentinel for end of array
};
const static HtmlEntity_t g_WhitespaceEntities[] = {
{ ' ', " ", 6 },
{ '\n', "<br>", 4 },
{ 0, NULL, 0 } // sentinel for end of array
};
struct Tier1FullHTMLEntity_t
{
uchar32 uCharCode;
const char *pchEntity;
int nEntityLength;
};
#pragma warning( push )
#pragma warning( disable : 4428 ) // universal-character-name encountered in source
const Tier1FullHTMLEntity_t g_Tier1_FullHTMLEntities[] =
{
{ L'"', """, 6 },
{ L'\'', "'", 6 },
{ L'&', "&", 5 },
{ L'<', "<", 4 },
{ L'>', ">", 4 },
{ L' ', " ", 6 },
{ L'\u2122', "™", 7 },
{ L'\u00A9', "©", 6 },
{ L'\u00AE', "®", 5 },
{ L'\u2013', "–", 7 },
{ L'\u2014', "—", 7 },
{ L'\u20AC', "€", 6 },
{ L'\u00A1', "¡", 7 },
{ L'\u00A2', "¢", 6 },
{ L'\u00A3', "£", 7 },
{ L'\u00A4', "¤", 8 },
{ L'\u00A5', "¥", 5 },
{ L'\u00A6', "¦", 8 },
{ L'\u00A7', "§", 6 },
{ L'\u00A8', "¨", 5 },
{ L'\u00AA', "ª", 6 },
{ L'\u00AB', "«", 7 },
{ L'\u00AC', "¬", 8 },
{ L'\u00AD', "­", 5 },
{ L'\u00AF', "¯", 6 },
{ L'\u00B0', "°", 5 },
{ L'\u00B1', "±", 8 },
{ L'\u00B2', "²", 6 },
{ L'\u00B3', "³", 6 },
{ L'\u00B4', "´", 7 },
{ L'\u00B5', "µ", 7 },
{ L'\u00B6', "¶", 6 },
{ L'\u00B7', "·", 8 },
{ L'\u00B8', "¸", 7 },
{ L'\u00B9', "¹", 6 },
{ L'\u00BA', "º", 6 },
{ L'\u00BB', "»", 7 },
{ L'\u00BC', "¼", 8 },
{ L'\u00BD', "½", 8 },
{ L'\u00BE', "¾", 8 },
{ L'\u00BF', "¿", 8 },
{ L'\u00D7', "×", 7 },
{ L'\u00F7', "÷", 8 },
{ L'\u00C0', "À", 8 },
{ L'\u00C1', "Á", 8 },
{ L'\u00C2', "Â", 7 },
{ L'\u00C3', "Ã", 8 },
{ L'\u00C4', "Ä", 6 },
{ L'\u00C5', "Å", 7 },
{ L'\u00C6', "Æ", 7 },
{ L'\u00C7', "Ç", 8 },
{ L'\u00C8', "È", 8 },
{ L'\u00C9', "É", 8 },
{ L'\u00CA', "Ê", 7 },
{ L'\u00CB', "Ë", 6 },
{ L'\u00CC', "Ì", 8 },
{ L'\u00CD', "Í", 8 },
{ L'\u00CE', "Î", 7 },
{ L'\u00CF', "Ï", 6 },
{ L'\u00D0', "Ð", 5 },
{ L'\u00D1', "Ñ", 8 },
{ L'\u00D2', "Ò", 8 },
{ L'\u00D3', "Ó", 8 },
{ L'\u00D4', "Ô", 7 },
{ L'\u00D5', "Õ", 8 },
{ L'\u00D6', "Ö", 6 },
{ L'\u00D8', "Ø", 8 },
{ L'\u00D9', "Ù", 8 },
{ L'\u00DA', "Ú", 8 },
{ L'\u00DB', "Û", 7 },
{ L'\u00DC', "Ü", 6 },
{ L'\u00DD', "Ý", 8 },
{ L'\u00DE', "Þ", 7 },
{ L'\u00DF', "ß", 7 },
{ L'\u00E0', "à", 8 },
{ L'\u00E1', "á", 8 },
{ L'\u00E2', "â", 7 },
{ L'\u00E3', "ã", 8 },
{ L'\u00E4', "ä", 6 },
{ L'\u00E5', "å", 7 },
{ L'\u00E6', "æ", 7 },
{ L'\u00E7', "ç", 8 },
{ L'\u00E8', "è", 8 },
{ L'\u00E9', "é", 8 },
{ L'\u00EA', "ê", 7 },
{ L'\u00EB', "ë", 6 },
{ L'\u00EC', "ì", 8 },
{ L'\u00ED', "í", 8 },
{ L'\u00EE', "î", 7 },
{ L'\u00EF', "ï", 6 },
{ L'\u00F0', "ð", 5 },
{ L'\u00F1', "ñ", 8 },
{ L'\u00F2', "ò", 8 },
{ L'\u00F3', "ó", 8 },
{ L'\u00F4', "ô", 7 },
{ L'\u00F5', "õ", 8 },
{ L'\u00F6', "ö", 6 },
{ L'\u00F8', "ø", 8 },
{ L'\u00F9', "ù", 8 },
{ L'\u00FA', "ú", 8 },
{ L'\u00FB', "û", 7 },
{ L'\u00FC', "ü", 6 },
{ L'\u00FD', "ý", 8 },
{ L'\u00FE', "þ", 7 },
{ L'\u00FF', "ÿ", 6 },
{ 0, NULL, 0 } // sentinel for end of array
};
#pragma warning( pop )
bool V_BasicHtmlEntityEncode( char *pDest, const int nDestSize, char const *pIn, const int nInSize, bool bPreserveWhitespace /*= false*/ )
{
Assert( nDestSize == 0 || pDest != NULL );
int iOutput = 0;
for ( int iInput = 0; iInput < nInSize; ++iInput )
{
bool bReplacementDone = false;
// See if the current char matches any of the basic entities
for ( int i = 0; g_BasicHTMLEntities[ i ].uCharCode != 0; ++i )
{
if ( pIn[ iInput ] == g_BasicHTMLEntities[ i ].uCharCode )
{
bReplacementDone = true;
for ( int j = 0; j < g_BasicHTMLEntities[ i ].nEntityLength; ++j )
{
if ( iOutput >= nDestSize - 1 )
{
pDest[ nDestSize - 1 ] = 0;
return false;
}
pDest[ iOutput++ ] = g_BasicHTMLEntities[ i ].pchEntity[ j ];
}
}
}
if ( bPreserveWhitespace && !bReplacementDone )
{
// See if the current char matches any of the basic entities
for ( int i = 0; g_WhitespaceEntities[ i ].uCharCode != 0; ++i )
{
if ( pIn[ iInput ] == g_WhitespaceEntities[ i ].uCharCode )
{
bReplacementDone = true;
for ( int j = 0; j < g_WhitespaceEntities[ i ].nEntityLength; ++j )
{
if ( iOutput >= nDestSize - 1 )
{
pDest[ nDestSize - 1 ] = 0;
return false;
}
pDest[ iOutput++ ] = g_WhitespaceEntities[ i ].pchEntity[ j ];
}
}
}
}
if ( !bReplacementDone )
{
pDest[ iOutput++ ] = pIn[ iInput ];
}
}
// Null terminate the output
pDest[ iOutput ] = 0;
return true;
}
bool V_HtmlEntityDecodeToUTF8( char *pDest, const int nDestSize, char const *pIn, const int nInSize )
{
Assert( nDestSize == 0 || pDest != NULL );
int iOutput = 0;
for ( int iInput = 0; iInput < nInSize && iOutput < nDestSize; ++iInput )
{
bool bReplacementDone = false;
if ( pIn[ iInput ] == '&' )
{
bReplacementDone = true;
uchar32 wrgchReplacement[ 2 ] = { 0, 0 };
char rgchReplacement[ 8 ];
rgchReplacement[ 0 ] = 0;
const char *pchEnd = Q_strstr( pIn + iInput + 1, ";" );
if ( pchEnd )
{
if ( iInput + 1 < nInSize && pIn[ iInput + 1 ] == '#' )
{
// Numeric
int iBase = 10;
int iOffset = 2;
if ( iInput + 3 < nInSize && pIn[ iInput + 2 ] == 'x' )
{
iBase = 16;
iOffset = 3;
}
wrgchReplacement[ 0 ] = (uchar32)V_strtoi64( pIn + iInput + iOffset, NULL, iBase );
if ( !Q_UTF32ToUTF8( wrgchReplacement, rgchReplacement, sizeof( rgchReplacement ) ) )
{
rgchReplacement[ 0 ] = 0;
}
}
else
{
// Lookup in map
const Tier1FullHTMLEntity_t *pFullEntities = g_Tier1_FullHTMLEntities;
for ( int i = 0; pFullEntities[ i ].uCharCode != 0; ++i )
{
if ( nInSize - iInput - 1 >= pFullEntities[ i ].nEntityLength )
{
if ( Q_memcmp( pIn + iInput, pFullEntities[ i ].pchEntity, pFullEntities[ i ].nEntityLength ) == 0 )
{
wrgchReplacement[ 0 ] = pFullEntities[ i ].uCharCode;
if ( !Q_UTF32ToUTF8( wrgchReplacement, rgchReplacement, sizeof( rgchReplacement ) ) )
{
rgchReplacement[ 0 ] = 0;
}
break;
}
}
}
}
// make sure we found a replacement. If not, skip
int cchReplacement = V_strlen( rgchReplacement );
if ( cchReplacement > 0 )
{
if ( (int)cchReplacement + iOutput < nDestSize )
{
for ( int i = 0; rgchReplacement[ i ] != 0; ++i )
{
pDest[ iOutput++ ] = rgchReplacement[ i ];
}
}
// Skip extra space that we passed
iInput += pchEnd - ( pIn + iInput );
}
else
{
bReplacementDone = false;
}
}
}
if ( !bReplacementDone )
{
pDest[ iOutput++ ] = pIn[ iInput ];
}
}
// Null terminate the output
if ( iOutput < nDestSize )
{
pDest[ iOutput ] = 0;
}
else
{
pDest[ nDestSize - 1 ] = 0;
}
return true;
}
static const char *g_pszSimpleBBCodeReplacements[] = {
"[b]", "<b>",
"[/b]", "</b>",
"[i]", "<i>",
"[/i]", "</i>",
"[u]", "<u>",
"[/u]", "</u>",
"[s]", "<s>",
"[/s]", "</s>",
"[code]", "<pre>",
"[/code]", "</pre>",
"[h1]", "<h1>",
"[/h1]", "</h1>",
"[list]", "<ul>",
"[/list]", "</ul>",
"[*]", "<li>",
"[/url]", "</a>",
"[img]", "<img src=\"",
"[/img]", "\"></img>",
};
// Converts BBCode tags to HTML tags
bool V_BBCodeToHTML( OUT_Z_CAP( nDestSize ) char *pDest, const int nDestSize, char const *pIn, const int nInSize )
{
Assert( nDestSize == 0 || pDest != NULL );
int iOutput = 0;
for ( int iInput = 0; iInput < nInSize && iOutput < nDestSize && pIn[ iInput ]; ++iInput )
{
if ( pIn[ iInput ] == '[' )
{
// check simple replacements
bool bFoundReplacement = false;
for ( int r = 0; r < ARRAYSIZE( g_pszSimpleBBCodeReplacements ); r += 2 )
{
int nBBCodeLength = V_strlen( g_pszSimpleBBCodeReplacements[ r ] );
if ( !V_strnicmp( &pIn[ iInput ], g_pszSimpleBBCodeReplacements[ r ], nBBCodeLength ) )
{
int nHTMLReplacementLength = V_strlen( g_pszSimpleBBCodeReplacements[ r + 1 ] );
for ( int c = 0; c < nHTMLReplacementLength && iOutput < nDestSize; c++ )
{
pDest[ iOutput ] = g_pszSimpleBBCodeReplacements[ r + 1 ][ c ];
iOutput++;
}
iInput += nBBCodeLength - 1;
bFoundReplacement = true;
break;
}
}
// check URL replacement
if ( !bFoundReplacement && !V_strnicmp( &pIn[ iInput ], "[url=", 5 ) && nDestSize - iOutput > 9 )
{
iInput += 5;
pDest[ iOutput++ ] = '<';
pDest[ iOutput++ ] = 'a';
pDest[ iOutput++ ] = ' ';
pDest[ iOutput++ ] = 'h';
pDest[ iOutput++ ] = 'r';
pDest[ iOutput++ ] = 'e';
pDest[ iOutput++ ] = 'f';
pDest[ iOutput++ ] = '=';
pDest[ iOutput++ ] = '\"';
// copy all characters up to the closing square bracket
while ( pIn[ iInput ] != ']' && iInput < nInSize && iOutput < nDestSize )
{
pDest[ iOutput++ ] = pIn[ iInput++ ];
}
if ( pIn[ iInput ] == ']' && nDestSize - iOutput > 2 )
{
pDest[ iOutput++ ] = '\"';
pDest[ iOutput++ ] = '>';
}
bFoundReplacement = true;
}
// otherwise, skip over everything up to the closing square bracket
if ( !bFoundReplacement )
{
while ( pIn[ iInput ] != ']' && iInput < nInSize )
{
iInput++;
}
}
}
else if ( pIn[ iInput ] == '\r' && pIn[ iInput + 1 ] == '\n' )
{
// convert carriage return and newline to a <br>
if ( nDestSize - iOutput > 4 )
{
pDest[ iOutput++ ] = '<';
pDest[ iOutput++ ] = 'b';
pDest[ iOutput++ ] = 'r';
pDest[ iOutput++ ] = '>';
}
iInput++;
}
else if ( pIn[ iInput ] == '\n' )
{
// convert newline to a <br>
if ( nDestSize - iOutput > 4 )
{
pDest[ iOutput++ ] = '<';
pDest[ iOutput++ ] = 'b';
pDest[ iOutput++ ] = 'r';
pDest[ iOutput++ ] = '>';
}
}
else
{
// copy character to destination
pDest[ iOutput++ ] = pIn[ iInput ];
}
}
// always terminate string
if ( iOutput >= nDestSize )
{
iOutput = nDestSize - 1;
}
pDest[ iOutput ] = 0;
return true;
}
//-----------------------------------------------------------------------------
// Purpose: returns true if a wide character is a "mean" space; that is,
// if it is technically a space or punctuation, but causes disruptive
// behavior when used in names, web pages, chat windows, etc.
//
// characters in this set are removed from the beginning and/or end of strings
// by Q_AggressiveStripPrecedingAndTrailingWhitespaceW()
//-----------------------------------------------------------------------------
bool V_IsMeanUnderscoreW( wchar_t wch )
{
bool bIsMean = false;
switch ( wch )
{
case L'\x005f': // low line (normal underscore)
case L'\xff3f': // fullwidth low line
case L'\x0332': // combining low line
bIsMean = true;
break;
default:
break;
}
return bIsMean;
}
//-----------------------------------------------------------------------------
// Purpose: returns true if a wide character is a "mean" space; that is,
// if it is technically a space or punctuation, but causes disruptive
// behavior when used in names, web pages, chat windows, etc.
//
// characters in this set are removed from the beginning and/or end of strings
// by Q_AggressiveStripPrecedingAndTrailingWhitespaceW()
//-----------------------------------------------------------------------------
bool V_IsMeanSpaceW( wchar_t wch )
{
bool bIsMean = false;
switch ( wch )
{
case L'\x0080': // PADDING CHARACTER
case L'\x0081': // HIGH OCTET PRESET
case L'\x0082': // BREAK PERMITTED HERE
case L'\x0083': // NO BREAK PERMITTED HERE
case L'\x0084': // INDEX
case L'\x0085': // NEXT LINE
case L'\x0086': // START OF SELECTED AREA
case L'\x0087': // END OF SELECTED AREA
case L'\x0088': // CHARACTER TABULATION SET
case L'\x0089': // CHARACTER TABULATION WITH JUSTIFICATION
case L'\x008A': // LINE TABULATION SET
case L'\x008B': // PARTIAL LINE FORWARD
case L'\x008C': // PARTIAL LINE BACKWARD
case L'\x008D': // REVERSE LINE FEED
case L'\x008E': // SINGLE SHIFT 2
case L'\x008F': // SINGLE SHIFT 3
case L'\x0090': // DEVICE CONTROL STRING
case L'\x0091': // PRIVATE USE
case L'\x0092': // PRIVATE USE
case L'\x0093': // SET TRANSMIT STATE
case L'\x0094': // CANCEL CHARACTER
case L'\x0095': // MESSAGE WAITING
case L'\x0096': // START OF PROTECTED AREA
case L'\x0097': // END OF PROTECED AREA
case L'\x0098': // START OF STRING
case L'\x0099': // SINGLE GRAPHIC CHARACTER INTRODUCER
case L'\x009A': // SINGLE CHARACTER INTRODUCER
case L'\x009B': // CONTROL SEQUENCE INTRODUCER
case L'\x009C': // STRING TERMINATOR
case L'\x009D': // OPERATING SYSTEM COMMAND
case L'\x009E': // PRIVACY MESSAGE
case L'\x009F': // APPLICATION PROGRAM COMMAND
case L'\x00A0': // NO-BREAK SPACE
case L'\x034F': // COMBINING GRAPHEME JOINER
case L'\x2000': // EN QUAD
case L'\x2001': // EM QUAD
case L'\x2002': // EN SPACE
case L'\x2003': // EM SPACE
case L'\x2004': // THICK SPACE
case L'\x2005': // MID SPACE
case L'\x2006': // SIX SPACE
case L'\x2007': // figure space
case L'\x2008': // PUNCTUATION SPACE
case L'\x2009': // THIN SPACE
case L'\x200A': // HAIR SPACE
case L'\x200B': // ZERO-WIDTH SPACE
case L'\x200C': // ZERO-WIDTH NON-JOINER
case L'\x200D': // ZERO WIDTH JOINER
case L'\x2028': // LINE SEPARATOR
case L'\x2029': // PARAGRAPH SEPARATOR
case L'\x202F': // NARROW NO-BREAK SPACE
case L'\x2060': // word joiner
case L'\xFEFF': // ZERO-WIDTH NO BREAK SPACE
case L'\xFFFC': // OBJECT REPLACEMENT CHARACTER
bIsMean = true;
break;
}
return bIsMean;
}
//-----------------------------------------------------------------------------
// Purpose: tell us if a Unicode character is deprecated
//
// See Unicode Technical Report #20: http://www.unicode.org/reports/tr20/
//
// Some characters are difficult or unreliably rendered. These characters eventually
// fell out of the Unicode standard, but are abusable by users. For example,
// setting "RIGHT-TO-LEFT OVERRIDE" without popping or undoing the action causes
// the layout instruction to bleed into following characters in HTML renderings,
// or upset layout calculations in vgui panels.
//
// Many games don't cope with these characters well, and end up providing opportunities
// for griefing others. For example, a user might join a game with a malformed player
// name and it turns out that player name can't be selected or typed into the admin
// console or UI to mute, kick, or ban the disruptive player.
//
// Ideally, we'd perfectly support these end-to-end but we never realistically will.
// The benefit of doing so far outweighs the cost, anyway.
//-----------------------------------------------------------------------------
bool V_IsDeprecatedW( wchar_t wch )
{
bool bIsDeprecated = false;
switch ( wch )
{
case L'\x202A': // LEFT-TO-RIGHT EMBEDDING
case L'\x202B': // RIGHT-TO-LEFT EMBEDDING
case L'\x202C': // POP DIRECTIONAL FORMATTING
case L'\x202D': // LEFT-TO-RIGHT OVERRIDE
case L'\x202E': // RIGHT-TO-LEFT OVERRIDE
case L'\x206A': // INHIBIT SYMMETRIC SWAPPING
case L'\x206B': // ACTIVATE SYMMETRIC SWAPPING
case L'\x206C': // INHIBIT ARABIC FORM SHAPING
case L'\x206D': // ACTIVATE ARABIC FORM SHAPING
case L'\x206E': // NATIONAL DIGIT SHAPES
case L'\x206F': // NOMINAL DIGIT SHAPES
bIsDeprecated = true;
}
return bIsDeprecated;
}
//-----------------------------------------------------------------------------
// returns true if the character is allowed in a DNS doman name, false otherwise
//-----------------------------------------------------------------------------
bool V_IsValidDomainNameCharacter( const char *pch, int *pAdvanceBytes )
{
if ( pAdvanceBytes )
*pAdvanceBytes = 0;
// We allow unicode in Domain Names without the an encoding unless it corresponds to
// a whitespace or control sequence or something we think is an underscore looking thing.
// If this character is the start of a UTF-8 sequence, try decoding it.
unsigned char ch = (unsigned char)*pch;
if ( ( ch & 0xC0 ) == 0xC0 )
{
uchar32 rgch32Buf;
bool bError = false;
int iAdvance = Q_UTF8ToUChar32( pch, rgch32Buf, bError );
if ( bError || iAdvance == 0 )
{
// Invalid UTF8 sequence, lets consider that invalid
return false;
}
if ( pAdvanceBytes )
*pAdvanceBytes = iAdvance;
if ( iAdvance )
{
// Ick. Want uchar32 versions of unicode character classification functions.
// Really would like Q_IsWhitespace32 and Q_IsNonPrintable32, but this is OK.
if ( rgch32Buf < 0x10000 && ( V_IsMeanSpaceW( (wchar_t)rgch32Buf ) || V_IsDeprecatedW( (wchar_t)rgch32Buf ) || V_IsMeanUnderscoreW( (wchar_t)rgch32Buf ) ) )
{
return false;
}
return true;
}
else
{
// Unreachable but would be invalid utf8
return false;
}
}
else
{
// Was not unicode
if ( pAdvanceBytes )
*pAdvanceBytes = 1;
// The only allowable non-unicode chars are a-z A-Z 0-9 and -
if ( ( ch >= 'a' && ch <= 'z' ) || ( ch >= 'A' && ch <= 'Z' ) || ( ch >= '0' && ch <= '9' ) || ch == '-' || ch == '.' )
return true;
return false;
}
}
//-----------------------------------------------------------------------------
// returns true if the character is allowed in a URL, false otherwise
//-----------------------------------------------------------------------------
bool V_IsValidURLCharacter( const char *pch, int *pAdvanceBytes )
{
if ( pAdvanceBytes )
*pAdvanceBytes = 0;
// We allow unicode in URLs unless it corresponds to a whitespace or control sequence.
// If this character is the start of a UTF-8 sequence, try decoding it.
unsigned char ch = (unsigned char)*pch;
if ( ( ch & 0xC0 ) == 0xC0 )
{
uchar32 rgch32Buf;
bool bError = false;
int iAdvance = Q_UTF8ToUChar32( pch, rgch32Buf, bError );
if ( bError || iAdvance == 0 )
{
// Invalid UTF8 sequence, lets consider that invalid
return false;
}
if ( pAdvanceBytes )
*pAdvanceBytes = iAdvance;
if ( iAdvance )
{
// Ick. Want uchar32 versions of unicode character classification functions.
// Really would like Q_IsWhitespace32 and Q_IsNonPrintable32, but this is OK.
if ( rgch32Buf < 0x10000 && ( V_IsMeanSpaceW( (wchar_t)rgch32Buf ) || V_IsDeprecatedW( (wchar_t)rgch32Buf ) ) )
{
return false;
}
return true;
}
else
{
// Unreachable but would be invalid utf8
return false;
}
}
else
{
// Was not unicode
if ( pAdvanceBytes )
*pAdvanceBytes = 1;
// Spaces, control characters, quotes, and angle brackets are not legal URL characters.
if ( ch <= 32 || ch == 127 || ch == '"' || ch == '<' || ch == '>' )
return false;
return true;
}
}
//-----------------------------------------------------------------------------
// Purpose: helper function to get a domain from a url
// Checks both standard url and steam://openurl/<url>
//-----------------------------------------------------------------------------
bool V_ExtractDomainFromURL( const char *pchURL, char *pchDomain, int cchDomain )
{
pchDomain[ 0 ] = 0;
static const char *k_pchSteamOpenUrl = "steam://openurl/";
static const char *k_pchSteamOpenUrlExt = "steam://openurl_external/";
const char *pchOpenUrlSuffix = StringAfterPrefix( pchURL, k_pchSteamOpenUrl );
if ( pchOpenUrlSuffix == NULL )
pchOpenUrlSuffix = StringAfterPrefix( pchURL, k_pchSteamOpenUrlExt );
if ( pchOpenUrlSuffix )
pchURL = pchOpenUrlSuffix;
if ( !pchURL || pchURL[ 0 ] == '\0' )
return false;
const char *pchDoubleSlash = strstr( pchURL, "//" );
// Put the domain and everything after into pchDomain.
// We'll find where to terminate it later.
if ( pchDoubleSlash )
{
// Skip the slashes
pchDoubleSlash += 2;
// If that's all there was, then there's no domain here. Bail.
if ( *pchDoubleSlash == '\0' )
{
return false;
}
// Skip any extra slashes
// ex: http:///steamcommunity.com/
while ( *pchDoubleSlash == '/' )
{
pchDoubleSlash++;
}
Q_strncpy( pchDomain, pchDoubleSlash, cchDomain );
}
else
{
// No double slash, so pchURL has no protocol.
Q_strncpy( pchDomain, pchURL, cchDomain );
}
// First character has to be valid
if ( *pchDomain == '?' || *pchDomain == '\0' )
{
return false;
}
// terminate the domain after the first non domain char
int iAdvance = 0;
int iStrLen = 0;
char cLast = 0;
while ( pchDomain[ iStrLen ] )
{
if ( !V_IsValidDomainNameCharacter( pchDomain + iStrLen, &iAdvance ) || ( pchDomain[ iStrLen ] == '.' && cLast == '.' ) )
{
pchDomain[ iStrLen ] = 0;
break;
}
cLast = pchDomain[ iStrLen ];
iStrLen += iAdvance;
}
return ( pchDomain[ 0 ] != 0 );
}
//-----------------------------------------------------------------------------
// Purpose: helper function to get a domain from a url
//-----------------------------------------------------------------------------
bool V_URLContainsDomain( const char *pchURL, const char *pchDomain )
{
char rgchExtractedDomain[ 2048 ];
if ( V_ExtractDomainFromURL( pchURL, rgchExtractedDomain, sizeof( rgchExtractedDomain ) ) )
{
// see if the last part of the domain matches what we extracted
int cchExtractedDomain = V_strlen( rgchExtractedDomain );
if ( pchDomain[ 0 ] == '.' )
{
++pchDomain; // If the domain has a leading '.', skip it. The test below assumes there is none.
}
int cchDomain = V_strlen( pchDomain );
if ( cchDomain > cchExtractedDomain )
{
return false;
}
else if ( cchExtractedDomain >= cchDomain )
{
// If the actual domain is longer than what we're searching for, the character previous
// to the domain we're searching for must be a period
if ( cchExtractedDomain > cchDomain && rgchExtractedDomain[ cchExtractedDomain - cchDomain - 1 ] != '.' )
return false;
if ( 0 == V_stricmp( rgchExtractedDomain + cchExtractedDomain - cchDomain, pchDomain ) )
return true;
}
}
return false;
}
//-----------------------------------------------------------------------------
// Purpose: Strips all HTML tags not specified in rgszPreserveTags
// Does some additional formatting, like turning <li> into * when not preserving that tag,
// and auto-closing unclosed tags if they aren't specified in rgszNoCloseTags
//-----------------------------------------------------------------------------
void V_StripAndPreserveHTMLCore( CUtlBuffer *pbuffer, const char *pchHTML, const char **rgszPreserveTags, uint cPreserveTags, const char **rgszNoCloseTags, uint cNoCloseTags, uint cMaxResultSize )
{
uint cHTMLCur = 0;
bool bStripNewLines = true;
if ( cPreserveTags > 0 )
{
for ( uint i = 0; i < cPreserveTags; ++i )
{
if ( !Q_stricmp( rgszPreserveTags[ i ], "\n" ) )
bStripNewLines = false;
}
}
//state-
bool bInStrippedTag = false;
bool bInStrippedContentTag = false;
bool bInPreservedTag = false;
bool bInListItemTag = false;
bool bLastCharWasWhitespace = true; //set to true to strip leading whitespace
bool bInComment = false;
bool bInDoubleQuote = false;
bool bInSingleQuote = false;
int nPreTagDepth = 0;
CUtlVector< const char* > vecTagStack;
for ( int iContents = 0; pchHTML[ iContents ] != '\0' && cHTMLCur < cMaxResultSize; iContents++ )
{
char c = pchHTML[ iContents ];
// If we are entering a comment, flag as such and skip past the begin comment tag
const char *pchCur = &pchHTML[ iContents ];
if ( !Q_strnicmp( pchCur, "<!--", 4 ) )
{
bInComment = true;
iContents += 3;
continue;
}
// If we are in a comment, check if we are exiting
if ( bInComment )
{
if ( !Q_strnicmp( pchCur, "-->", 3 ) )
{
bInComment = false;
iContents += 2;
continue;
}
else
{
continue;
}
}
if ( bInStrippedTag || bInPreservedTag )
{
// we're inside a tag, keep stripping/preserving until we get to a >
if ( bInPreservedTag )
pbuffer->PutChar( c );
// While inside a tag, ignore ending > properties if they are inside a property value in "" or ''
if ( c == '"' )
{
if ( bInDoubleQuote )
bInDoubleQuote = false;
else
bInDoubleQuote = true;
}
if ( c == '\'' )
{
if ( bInSingleQuote )
bInSingleQuote = false;
else
bInSingleQuote = true;
}
if ( !bInDoubleQuote && !bInSingleQuote && c == '>' )
{
if ( bInPreservedTag )
bLastCharWasWhitespace = false;
bInPreservedTag = false;
bInStrippedTag = false;
}
}
else if ( bInStrippedContentTag )
{
if ( c == '<' && !Q_strnicmp( pchCur, "</script>", 9 ) )
{
bInStrippedContentTag = false;
iContents += 8;
continue;
}
else
{
continue;
}
}
else if ( c & 0x80 && !bInStrippedContentTag )
{
// start/continuation of a multibyte sequence, copy to output.
int nMultibyteRemaining = 0;
if ( ( c & 0xF8 ) == 0xF0 ) // first 5 bits are 11110
nMultibyteRemaining = 3;
else if ( ( c & 0xF0 ) == 0xE0 ) // first 4 bits are 1110
nMultibyteRemaining = 2;
else if ( ( c & 0xE0 ) == 0xC0 ) // first 3 bits are 110
nMultibyteRemaining = 1;
// cHTMLCur is in characters, so just +1
cHTMLCur++;
pbuffer->Put( pchCur, 1 + nMultibyteRemaining );
iContents += nMultibyteRemaining;
// Need to determine if we just added whitespace or not
wchar_t rgwch[ 3 ] = { 0 };
Q_UTF8CharsToWString( pchCur, 1, rgwch, sizeof( rgwch ) );
if ( !V_iswspace( rgwch[ 0 ] ) )
bLastCharWasWhitespace = false;
else
bLastCharWasWhitespace = true;
}
else
{
//not in a multibyte sequence- do our parsing/stripping
if ( c == '<' )
{
if ( !rgszPreserveTags || cPreserveTags == 0 )
{
//not preserving any tags, just strip it
bInStrippedTag = true;
}
else
{
//look ahead, is this our kind of tag?
bool bPreserve = false;
bool bEndTag = false;
const char *szTagStart = &pchHTML[ iContents + 1 ];
// if it's a close tag, skip the /
if ( *szTagStart == '/' )
{
bEndTag = true;
szTagStart++;
}
if ( Q_strnicmp( "script", szTagStart, 6 ) == 0 )
{
bInStrippedTag = true;
bInStrippedContentTag = true;
}
else
{
//see if this tag is one we want to preserve
for ( uint iTag = 0; iTag < cPreserveTags; iTag++ )
{
const char *szTag = rgszPreserveTags[ iTag ];
int cchTag = Q_strlen( szTag );
//make sure characters match, and are followed by some non-alnum char
// so "i" can match <i> or <i class=...>, but not <img>
if ( Q_strnicmp( szTag, szTagStart, cchTag ) == 0 && !V_isalnum( szTagStart[ cchTag ] ) )
{
bPreserve = true;
if ( bEndTag )
{
// ending a paragraph tag is optional. If we were expecting to find one, and didn't, skip
if ( Q_stricmp( szTag, "p" ) != 0 )
{
while ( vecTagStack.Count() > 0 && Q_stricmp( vecTagStack[ vecTagStack.Count() - 1 ], "p" ) == 0 )
{
vecTagStack.Remove( vecTagStack.Count() - 1 );
}
}
if ( vecTagStack.Count() > 0 && vecTagStack[ vecTagStack.Count() - 1 ] == szTag )
{
vecTagStack.Remove( vecTagStack.Count() - 1 );
if ( Q_stricmp( szTag, "pre" ) == 0 )
{
nPreTagDepth--;
if ( nPreTagDepth < 0 )
{
nPreTagDepth = 0;
}
}
}
else
{
// don't preserve this unbalanced tag. All open tags will be closed at the end of the blurb
bPreserve = false;
}
}
else
{
bool bNoCloseTag = false;
for ( uint iNoClose = 0; iNoClose < cNoCloseTags; iNoClose++ )
{
if ( Q_stricmp( szTag, rgszNoCloseTags[ iNoClose ] ) == 0 )
{
bNoCloseTag = true;
break;
}
}
if ( !bNoCloseTag )
{
vecTagStack.AddToTail( szTag );
if ( Q_stricmp( szTag, "pre" ) == 0 )
{
nPreTagDepth++;
}
}
}
break;
}
}
if ( !bPreserve )
{
bInStrippedTag = true;
}
else
{
bInPreservedTag = true;
pbuffer->PutChar( c );
}
}
}
if ( bInStrippedTag )
{
const char *szTagStart = &pchHTML[ iContents ];
if ( Q_strnicmp( szTagStart, "<li>", Q_strlen( "<li>" ) ) == 0 )
{
if ( bInListItemTag )
{
pbuffer->PutChar( ';' );
cHTMLCur++;
bInListItemTag = false;
}
if ( !bLastCharWasWhitespace )
{
pbuffer->PutChar( ' ' );
cHTMLCur++;
}
pbuffer->PutChar( '*' );
pbuffer->PutChar( ' ' );
cHTMLCur += 2;
bInListItemTag = true;
}
else if ( !bLastCharWasWhitespace )
{
if ( bInListItemTag )
{
char cLastChar = ' ';
if ( pbuffer->TellPut() > 0 )
{
cLastChar = ( ( (char*)pbuffer->Base() ) + pbuffer->TellPut() - 1 )[ 0 ];
}
if ( cLastChar != '.' && cLastChar != '?' && cLastChar != '!' )
{
pbuffer->PutChar( ';' );
cHTMLCur++;
}
bInListItemTag = false;
}
//we're decided to remove a tag, simulate a space in the original text
pbuffer->PutChar( ' ' );
cHTMLCur++;
}
bLastCharWasWhitespace = true;
}
}
else
{
//just a normal character, nothin' special.
if ( nPreTagDepth == 0 && V_isspace( c ) && ( bStripNewLines || c != '\n' ) )
{
if ( !bLastCharWasWhitespace )
{
//replace any block of whitespace with a single space
cHTMLCur++;
pbuffer->PutChar( ' ' );
bLastCharWasWhitespace = true;
}
// don't put anything for whitespace if the previous character was whitespace
// (effectively trimming all blocks of whitespace down to a single ' ')
}
else
{
cHTMLCur++;
pbuffer->PutChar( c );
bLastCharWasWhitespace = false;
}
}
}
}
if ( cHTMLCur >= cMaxResultSize )
{
// we terminated because the blurb was full. Add a '...' to the end
pbuffer->Put( "...", 3 );
}
//close any preserved tags that were open at the end.
FOR_EACH_VEC_BACK( vecTagStack, iTagStack )
{
pbuffer->PutChar( '<' );
pbuffer->PutChar( '/' );
pbuffer->Put( vecTagStack[ iTagStack ], Q_strlen( vecTagStack[ iTagStack ] ) );
pbuffer->PutChar( '>' );
}
// Null terminate
pbuffer->PutChar( '\0' );
}
//-----------------------------------------------------------------------------
// Purpose: Strips all HTML tags not specified in rgszPreserveTags
// Does some additional formatting, like turning <li> into * when not preserving that tag
//-----------------------------------------------------------------------------
void V_StripAndPreserveHTML( CUtlBuffer *pbuffer, const char *pchHTML, const char **rgszPreserveTags, uint cPreserveTags, uint cMaxResultSize )
{
const char *rgszNoCloseTags[] = { "br", "img" };
V_StripAndPreserveHTMLCore( pbuffer, pchHTML, rgszPreserveTags, cPreserveTags, rgszNoCloseTags, V_ARRAYSIZE( rgszNoCloseTags ), cMaxResultSize );
}
|