aboutsummaryrefslogtreecommitdiff
path: root/src/libs/dutil/WixToolset.DUtil/strutil.cpp
blob: a483cf54dcb29803fd2e66300701d3b6366fbd75 (plain)
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
// Copyright (c) .NET Foundation and contributors. All rights reserved. Licensed under the Microsoft Reciprocal License. See LICENSE.TXT file in the project root for full license information.

#include "precomp.h"


// Exit macros
#define StrExitOnLastError(x, s, ...) ExitOnLastErrorSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__)
#define StrExitOnLastErrorDebugTrace(x, s, ...) ExitOnLastErrorDebugTraceSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__)
#define StrExitWithLastError(x, s, ...) ExitWithLastErrorSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__)
#define StrExitOnFailure(x, s, ...) ExitOnFailureSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__)
#define StrExitOnRootFailure(x, s, ...) ExitOnRootFailureSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__)
#define StrExitOnFailureDebugTrace(x, s, ...) ExitOnFailureDebugTraceSource(DUTIL_SOURCE_STRUTIL, x, s, __VA_ARGS__)
#define StrExitOnNull(p, x, e, s, ...) ExitOnNullSource(DUTIL_SOURCE_STRUTIL, p, x, e, s, __VA_ARGS__)
#define StrExitOnNullWithLastError(p, x, s, ...) ExitOnNullWithLastErrorSource(DUTIL_SOURCE_STRUTIL, p, x, s, __VA_ARGS__)
#define StrExitOnNullDebugTrace(p, x, e, s, ...)  ExitOnNullDebugTraceSource(DUTIL_SOURCE_STRUTIL, p, x, e, s, __VA_ARGS__)
#define StrExitOnInvalidHandleWithLastError(p, x, s, ...) ExitOnInvalidHandleWithLastErrorSource(DUTIL_SOURCE_STRUTIL, p, x, s, __VA_ARGS__)
#define StrExitOnWin32Error(e, x, s, ...) ExitOnWin32ErrorSource(DUTIL_SOURCE_STRUTIL, e, x, s, __VA_ARGS__)
#define StrExitOnGdipFailure(g, x, s, ...) ExitOnGdipFailureSource(DUTIL_SOURCE_STRUTIL, g, x, s, __VA_ARGS__)

#define ARRAY_GROWTH_SIZE 5

// Forward declarations.
static HRESULT AllocHelper(
    __deref_out_ecount_part(cch, 0) LPWSTR* ppwz,
    __in SIZE_T cch,
    __in BOOL fZeroOnRealloc
    );
static HRESULT AllocStringHelper(
    __deref_out_ecount_z(cchSource + 1) LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource,
    __in BOOL fZeroOnRealloc
    );
static HRESULT AllocConcatHelper(
    __deref_out_z LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource,
    __in BOOL fZeroOnRealloc
    );
static HRESULT AllocFormattedArgsHelper(
    __deref_out_z LPWSTR* ppwz,
    __in BOOL fZeroOnRealloc,
    __in __format_string LPCWSTR wzFormat,
    __in va_list args
    );
static HRESULT StrAllocStringMapInvariant(
    __deref_out_z LPWSTR* pscz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource,
    __in DWORD dwMapFlags
    );

/********************************************************************
StrAlloc - allocates or reuses dynamic string memory

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT DAPI StrAlloc(
    __deref_out_ecount_part(cch, 0) LPWSTR* ppwz,
    __in SIZE_T cch
    )
{
    return AllocHelper(ppwz, cch, FALSE);
}

/********************************************************************
StrAllocSecure - allocates or reuses dynamic string memory
If the memory needs to reallocated, calls SecureZeroMemory on the
original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT DAPI StrAllocSecure(
    __deref_out_ecount_part(cch, 0) LPWSTR* ppwz,
    __in SIZE_T cch
    )
{
    return AllocHelper(ppwz, cch, TRUE);
}

/********************************************************************
AllocHelper - allocates or reuses dynamic string memory
If fZeroOnRealloc is true and the memory needs to reallocated, 
calls SecureZeroMemory on original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
static HRESULT AllocHelper(
    __deref_out_ecount_part(cch, 0) LPWSTR* ppwz,
    __in SIZE_T cch,
    __in BOOL fZeroOnRealloc
    )
{
    Assert(ppwz && cch);

    HRESULT hr = S_OK;
    LPWSTR pwz = NULL;

    if (cch >= MAXDWORD / sizeof(WCHAR))
    {
        hr = E_OUTOFMEMORY;
        StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch);
    }

    if (*ppwz)
    {
        if (fZeroOnRealloc)
        {
            LPVOID pvNew = NULL;
            hr = MemReAllocSecure(*ppwz, sizeof(WCHAR)* cch, FALSE, &pvNew);
            StrExitOnFailure(hr, "Failed to reallocate string");
            pwz = static_cast<LPWSTR>(pvNew);
        }
        else
        {
            pwz = static_cast<LPWSTR>(MemReAlloc(*ppwz, sizeof(WCHAR)* cch, FALSE));
        }
    }
    else
    {
        pwz = static_cast<LPWSTR>(MemAlloc(sizeof(WCHAR) * cch, TRUE));
    }

    StrExitOnNull(pwz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch);

    *ppwz = pwz;
LExit:
    return hr;
}


/********************************************************************
StrTrimCapacity - Frees any unnecessary memory associated with a string.
                  Purely used for optimization, generally only when a string
                  has been changing size, and will no longer grow.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
HRESULT DAPI StrTrimCapacity(
    __deref_out_z LPWSTR* ppwz
    )
{
    Assert(ppwz);

    HRESULT hr = S_OK;
    SIZE_T cchLen = 0;

    hr = ::StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchLen));
    StrExitOnRootFailure(hr, "Failed to calculate length of string");

    ++cchLen; // Add 1 for null-terminator

    hr = StrAlloc(ppwz, cchLen);
    StrExitOnFailure(hr, "Failed to reallocate string");

LExit:
    return hr;
}


/********************************************************************
StrTrimWhitespace - allocates or reuses dynamic string memory and copies
                    in an existing string, excluding whitespace

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
HRESULT DAPI StrTrimWhitespace(
    __deref_out_z LPWSTR* ppwz,
    __in_z LPCWSTR wzSource
    )
{
    HRESULT hr = S_OK;
    size_t i = 0;
    LPWSTR sczResult = NULL;

    // Ignore beginning whitespace
    while (L' ' == *wzSource || L'\t' == *wzSource)
    {
        wzSource++;
    }

    hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, &i);
    StrExitOnRootFailure(hr, "Failed to get length of string");

    // Overwrite ending whitespace with null characters
    if (0 < i)
    {
        // start from the last non-null-terminator character in the array
        for (i = i - 1; i > 0; --i)
        {
            if (L' ' != wzSource[i] && L'\t' != wzSource[i])
            {
                break;
            }
        }

        ++i;
    }

    hr = StrAllocString(&sczResult, wzSource, i);
    StrExitOnFailure(hr, "Failed to copy result string");

    // Output result
    *ppwz = sczResult;
    sczResult = NULL;

LExit:
    ReleaseStr(sczResult);

    return hr;
}


/********************************************************************
StrAnsiAlloc - allocates or reuses dynamic ANSI string memory

NOTE: caller is responsible for freeing ppsz even if function fails
********************************************************************/
extern "C" HRESULT DAPI StrAnsiAlloc(
    __deref_out_ecount_part(cch, 0) LPSTR* ppsz,
    __in SIZE_T cch
    )
{
    Assert(ppsz && cch);

    HRESULT hr = S_OK;
    LPSTR psz = NULL;

    if (cch >= MAXDWORD / sizeof(WCHAR))
    {
        hr = E_OUTOFMEMORY;
        StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch);
    }

    if (*ppsz)
    {
        psz = static_cast<LPSTR>(MemReAlloc(*ppsz, sizeof(CHAR) * cch, FALSE));
    }
    else
    {
        psz = static_cast<LPSTR>(MemAlloc(sizeof(CHAR) * cch, TRUE));
    }

    StrExitOnNull(psz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch);

    *ppsz = psz;
LExit:
    return hr;
}


/********************************************************************
StrAnsiTrimCapacity - Frees any unnecessary memory associated with a string.
                  Purely used for optimization, generally only when a string
                  has been changing size, and will no longer grow.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
HRESULT DAPI StrAnsiTrimCapacity(
    __deref_out_z LPSTR* ppz
    )
{
    Assert(ppz);

    HRESULT hr = S_OK;
    SIZE_T cchLen = 0;

#pragma prefast(push)
#pragma prefast(disable:25068)
    hr = ::StringCchLengthA(*ppz, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchLen));
#pragma prefast(pop)
    StrExitOnFailure(hr, "Failed to calculate length of string");

    ++cchLen; // Add 1 for null-terminator

    hr = StrAnsiAlloc(ppz, cchLen);
    StrExitOnFailure(hr, "Failed to reallocate string");

LExit:
    return hr;
}


/********************************************************************
StrAnsiTrimWhitespace - allocates or reuses dynamic string memory and copies
                    in an existing string, excluding whitespace

NOTE: caller is responsible for freeing ppz even if function fails
********************************************************************/
HRESULT DAPI StrAnsiTrimWhitespace(
    __deref_out_z LPSTR* ppz,
    __in_z LPCSTR szSource
    )
{
    HRESULT hr = S_OK;
    size_t i = 0;
    LPSTR sczResult = NULL;

    // Ignore beginning whitespace
    while (' ' == *szSource || '\t' == *szSource)
    {
        szSource++;
    }

    hr = ::StringCchLengthA(szSource, STRSAFE_MAX_CCH, &i);
    StrExitOnRootFailure(hr, "Failed to get length of string");

    // Overwrite ending whitespace with null characters
    if (0 < i)
    {
        // start from the last non-null-terminator character in the array
        for (i = i - 1; i > 0; --i)
        {
            if (L' ' != szSource[i] && L'\t' != szSource[i])
            {
                break;
            }
        }

        ++i;
    }

    hr = StrAnsiAllocStringAnsi(&sczResult, szSource, i);
    StrExitOnFailure(hr, "Failed to copy result string");

    // Output result
    *ppz = sczResult;
    sczResult = NULL;

LExit:
    ReleaseStr(sczResult);

    return hr;
}

/********************************************************************
StrAllocString - allocates or reuses dynamic string memory and copies in an existing string

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocString(
    __deref_out_ecount_z(cchSource+1) LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource
    )
{
    return AllocStringHelper(ppwz, wzSource, cchSource, FALSE);
}

/********************************************************************
StrAllocStringSecure - allocates or reuses dynamic string memory and 
copies in an existing string. If the memory needs to reallocated, 
calls SecureZeroMemory on original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocStringSecure(
    __deref_out_ecount_z(cchSource + 1) LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource
    )
{
    return AllocStringHelper(ppwz, wzSource, cchSource, TRUE);
}

/********************************************************************
AllocStringHelper - allocates or reuses dynamic string memory and copies in an existing string
If fZeroOnRealloc is true and the memory needs to reallocated, 
calls SecureZeroMemory on original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
static HRESULT AllocStringHelper(
    __deref_out_ecount_z(cchSource + 1) LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource,
    __in BOOL fZeroOnRealloc
    )
{
    Assert(ppwz && wzSource); // && *wzSource);

    HRESULT hr = S_OK;
    SIZE_T cch = 0;

    if (*ppwz)
    {
        hr = StrMaxLength(*ppwz, &cch);
        StrExitOnFailure(hr, "failed to get size of destination string");
    }

    if (0 == cchSource && wzSource)
    {
        hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, reinterpret_cast<size_t*>(&cchSource));
        StrExitOnRootFailure(hr, "failed to get length of source string");
    }

    SIZE_T cchNeeded;
    hr = ::ULongPtrAdd(cchSource, 1, &cchNeeded); // add one for the null terminator
    StrExitOnRootFailure(hr, "source string is too long");

    if (cch < cchNeeded)
    {
        cch = cchNeeded;
        hr = AllocHelper(ppwz, cch, fZeroOnRealloc);
        StrExitOnFailure(hr, "failed to allocate string from string.");
    }

    // copy everything (the NULL terminator will be included)
    hr = ::StringCchCopyNExW(*ppwz, cch, wzSource, cchSource, NULL, NULL, STRSAFE_FILL_BEHIND_NULL);

LExit:
    return hr;
}


/********************************************************************
StrAnsiAllocString - allocates or reuses dynamic ANSI string memory and copies in an existing string

NOTE: caller is responsible for freeing ppsz even if function fails
NOTE: cchSource must equal the length of wzSource (not including the NULL terminator)
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAnsiAllocString(
    __deref_out_ecount_z(cchSource+1) LPSTR* ppsz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource,
    __in UINT uiCodepage
    )
{
    Assert(ppsz && wzSource);

    HRESULT hr = S_OK;
    LPSTR psz = NULL;
    SIZE_T cch = 0;
    SIZE_T cchDest = cchSource; // at least enough

    if (*ppsz)
    {
        hr = StrMaxLengthAnsi(*ppsz, &cch);
        StrExitOnFailure(hr, "failed to get size of destination string");
    }

    if (0 == cchSource)
    {
        cchDest = ::WideCharToMultiByte(uiCodepage, 0, wzSource, -1, NULL, 0, NULL, NULL);
        if (0 == cchDest)
        {
            StrExitWithLastError(hr, "failed to get required size for conversion to ANSI: %ls", wzSource);
        }

        --cchDest; // subtract one because WideChageToMultiByte includes space for the NULL terminator that we track below
    }
    else if (L'\0' == wzSource[cchSource - 1]) // if the source already had a null terminator, don't count that in the character count because we track it below
    {
        cchDest = cchSource - 1;
    }

    if (cch < cchDest + 1)
    {
        cch = cchDest + 1;   // add one for the NULL terminator
        if (cch >= MAXDWORD / sizeof(WCHAR))
        {
            hr = E_OUTOFMEMORY;
            StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch);
        }

        if (*ppsz)
        {
            psz = static_cast<LPSTR>(MemReAlloc(*ppsz, sizeof(CHAR) * cch, TRUE));
        }
        else
        {
            psz = static_cast<LPSTR>(MemAlloc(sizeof(CHAR) * cch, TRUE));
        }
        StrExitOnNull(psz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch);

        *ppsz = psz;
    }

    if (0 == ::WideCharToMultiByte(uiCodepage, 0, wzSource, 0 == cchSource ? -1 : (int)cchSource, *ppsz, (int)cch, NULL, NULL))
    {
        StrExitWithLastError(hr, "failed to convert to ansi: %ls", wzSource);
    }
    (*ppsz)[cchDest] = L'\0';

LExit:
    return hr;
}


/********************************************************************
StrAllocStringAnsi - allocates or reuses dynamic string memory and copies in an existing ANSI string

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource must equal the length of wzSource (not including the NULL terminator)
NOTE: if cchSource == 0, length of szSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocStringAnsi(
    __deref_out_ecount_z(cchSource+1) LPWSTR* ppwz,
    __in_z LPCSTR szSource,
    __in SIZE_T cchSource,
    __in UINT uiCodepage
    )
{
    Assert(ppwz && szSource);

    HRESULT hr = S_OK;
    LPWSTR pwz = NULL;
    SIZE_T cch = 0;
    SIZE_T cchDest = cchSource;  // at least enough

    if (*ppwz)
    {
        hr = StrMaxLength(*ppwz, &cch);
        StrExitOnFailure(hr, "failed to get size of destination string");
    }

    if (0 == cchSource)
    {
        cchDest = ::MultiByteToWideChar(uiCodepage, 0, szSource, -1, NULL, 0);
        if (0 == cchDest)
        {
            StrExitWithLastError(hr, "failed to get required size for conversion to unicode: %s", szSource);
        }

        --cchDest; //subtract one because MultiByteToWideChar includes space for the NULL terminator that we track below
    }
    else if (L'\0' == szSource[cchSource - 1]) // if the source already had a null terminator, don't count that in the character count because we track it below
    {
        cchDest = cchSource - 1;
    }

    if (cch < cchDest + 1)
    {
        cch = cchDest + 1;
        if (cch >= MAXDWORD / sizeof(WCHAR))
        {
            hr = E_OUTOFMEMORY;
            StrExitOnFailure(hr, "Not enough memory to allocate string of size: %u", cch);
        }

        if (*ppwz)
        {
            pwz = static_cast<LPWSTR>(MemReAlloc(*ppwz, sizeof(WCHAR) * cch, TRUE));
        }
        else
        {
            pwz = static_cast<LPWSTR>(MemAlloc(sizeof(WCHAR) * cch, TRUE));
        }

        StrExitOnNull(pwz, hr, E_OUTOFMEMORY, "failed to allocate string, len: %u", cch);

        *ppwz = pwz;
    }

    if (0 == ::MultiByteToWideChar(uiCodepage, 0, szSource, 0 == cchSource ? -1 : (int)cchSource, *ppwz, (int)cch))
    {
        StrExitWithLastError(hr, "failed to convert to unicode: %s", szSource);
    }
    (*ppwz)[cchDest] = L'\0';

LExit:
    return hr;
}


/********************************************************************
StrAnsiAllocStringAnsi - allocates or reuses dynamic string memory and copies in an existing string

NOTE: caller is responsible for freeing ppsz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
HRESULT DAPI StrAnsiAllocStringAnsi(
    __deref_out_ecount_z(cchSource+1) LPSTR* ppsz,
    __in_z LPCSTR szSource,
    __in SIZE_T cchSource
    )
{
    Assert(ppsz && szSource); // && *szSource);

    HRESULT hr = S_OK;
    SIZE_T cch = 0;

    if (*ppsz)
    {
        hr = StrMaxLengthAnsi(*ppsz, &cch);
        StrExitOnRootFailure(hr, "failed to get size of destination string");
    }

    if (0 == cchSource && szSource)
    {
        hr = ::StringCchLengthA(szSource, STRSAFE_MAX_CCH, reinterpret_cast<size_t*>(&cchSource));
        StrExitOnRootFailure(hr, "failed to get length of source string");
    }

    SIZE_T cchNeeded;
    hr = ::ULongPtrAdd(cchSource, 1, &cchNeeded); // add one for the null terminator
    StrExitOnRootFailure(hr, "source string is too long");

    if (cch < cchNeeded)
    {
        cch = cchNeeded;
        hr = StrAnsiAlloc(ppsz, cch);
        StrExitOnFailure(hr, "failed to allocate string from string.");
    }

    // copy everything (the NULL terminator will be included)
#pragma prefast(push)
#pragma prefast(disable:25068)
    hr = ::StringCchCopyNExA(*ppsz, cch, szSource, cchSource, NULL, NULL, STRSAFE_FILL_BEHIND_NULL);
#pragma prefast(pop)

LExit:
    return hr;
}


/********************************************************************
StrAllocPrefix - allocates or reuses dynamic string memory and 
                 prefixes a string

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchPrefix does not have to equal the length of wzPrefix
NOTE: if cchPrefix == 0, length of wzPrefix is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocPrefix(
    __deref_out_z LPWSTR* ppwz,
    __in_z LPCWSTR wzPrefix,
    __in SIZE_T cchPrefix
    )
{
    Assert(ppwz && wzPrefix);

    HRESULT hr = S_OK;
    SIZE_T cch = 0;
    SIZE_T cchLen = 0;

    if (*ppwz)
    {
        hr = StrMaxLength(*ppwz, &cch);
        StrExitOnFailure(hr, "failed to get size of destination string");

        hr = ::StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchLen));
        StrExitOnFailure(hr, "Failed to calculate length of string");
    }

    Assert(cchLen <= cch);

    if (0 == cchPrefix)
    {
        hr = ::StringCchLengthW(wzPrefix, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchPrefix));
        StrExitOnFailure(hr, "Failed to calculate length of string");
    }

    if (cch - cchLen < cchPrefix + 1)
    {
        cch = cchPrefix + cchLen + 1;
        hr = StrAlloc(ppwz, cch);
        StrExitOnFailure(hr, "failed to allocate string from string: %ls", wzPrefix);
    }

    if (*ppwz)
    {
        SIZE_T cb = cch * sizeof(WCHAR);
        SIZE_T cbPrefix = cchPrefix * sizeof(WCHAR);

        memmove(*ppwz + cchPrefix, *ppwz, cb - cbPrefix);
        memcpy(*ppwz, wzPrefix, cbPrefix);
    }
    else
    {
        hr = E_UNEXPECTED;
        StrExitOnFailure(hr, "for some reason our buffer is still null");
    }

LExit:
    return hr;
}


/********************************************************************
StrAllocConcat - allocates or reuses dynamic string memory and adds an existing string

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocConcat(
    __deref_out_z LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource
    )
{
    return AllocConcatHelper(ppwz, wzSource, cchSource, FALSE);
}


/********************************************************************
StrAllocConcatSecure - allocates or reuses dynamic string memory and 
adds an existing string. If the memory needs to reallocated, calls 
SecureZeroMemory on the original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAllocConcatSecure(
    __deref_out_z LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource
    )
{
    return AllocConcatHelper(ppwz, wzSource, cchSource, TRUE);
}


/********************************************************************
AllocConcatHelper - allocates or reuses dynamic string memory and adds an existing string
If fZeroOnRealloc is true and the memory needs to reallocated, 
calls SecureZeroMemory on original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
NOTE: cchSource does not have to equal the length of wzSource
NOTE: if cchSource == 0, length of wzSource is used instead
********************************************************************/
static HRESULT AllocConcatHelper(
    __deref_out_z LPWSTR* ppwz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource,
    __in BOOL fZeroOnRealloc
    )
{
    Assert(ppwz && wzSource); // && *wzSource);

    HRESULT hr = S_OK;
    SIZE_T cch = 0;
    SIZE_T cchLen = 0;

    if (*ppwz)
    {
        hr = StrMaxLength(*ppwz, &cch);
        StrExitOnFailure(hr, "failed to get size of destination string");

        hr = ::StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchLen));
        StrExitOnFailure(hr, "Failed to calculate length of string");
    }

    Assert(cchLen <= cch);

    if (0 == cchSource)
    {
        hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchSource));
        StrExitOnFailure(hr, "Failed to calculate length of string");
    }

    if (cch - cchLen < cchSource + 1)
    {
        cch = (cchSource + cchLen + 1) * 2;
        hr = AllocHelper(ppwz, cch, fZeroOnRealloc);
        StrExitOnFailure(hr, "failed to allocate string from string: %ls", wzSource);
    }

    if (*ppwz)
    {
        hr = ::StringCchCatNExW(*ppwz, cch, wzSource, cchSource, NULL, NULL, STRSAFE_FILL_BEHIND_NULL);
    }
    else
    {
        hr = E_UNEXPECTED;
        StrExitOnFailure(hr, "for some reason our buffer is still null");
    }

LExit:
    return hr;
}


/********************************************************************
StrAnsiAllocConcat - allocates or reuses dynamic string memory and adds an existing string

NOTE: caller is responsible for freeing ppz even if function fails
NOTE: cchSource does not have to equal the length of pzSource
NOTE: if cchSource == 0, length of pzSource is used instead
********************************************************************/
extern "C" HRESULT DAPI StrAnsiAllocConcat(
    __deref_out_z LPSTR* ppz,
    __in_z LPCSTR pzSource,
    __in SIZE_T cchSource
    )
{
    Assert(ppz && pzSource); // && *pzSource);

    HRESULT hr = S_OK;
    SIZE_T cch = 0;
    SIZE_T cchLen = 0;

    if (*ppz)
    {
        hr = StrMaxLengthAnsi(*ppz, &cch);
        StrExitOnFailure(hr, "failed to get size of destination string");

#pragma prefast(push)
#pragma prefast(disable:25068)
        hr = ::StringCchLengthA(*ppz, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchLen));
#pragma prefast(pop)
        StrExitOnFailure(hr, "Failed to calculate length of string");
    }

    Assert(cchLen <= cch);

    if (0 == cchSource)
    {
#pragma prefast(push)
#pragma prefast(disable:25068)
        hr = ::StringCchLengthA(pzSource, STRSAFE_MAX_CCH, reinterpret_cast<UINT_PTR*>(&cchSource));
#pragma prefast(pop)
        StrExitOnFailure(hr, "Failed to calculate length of string");
    }

    if (cch - cchLen < cchSource + 1)
    {
        cch = (cchSource + cchLen + 1) * 2;
        hr = StrAnsiAlloc(ppz, cch);
        StrExitOnFailure(hr, "failed to allocate string from string: %hs", pzSource);
    }

    if (*ppz)
    {
#pragma prefast(push)
#pragma prefast(disable:25068)
        hr = ::StringCchCatNExA(*ppz, cch, pzSource, cchSource, NULL, NULL, STRSAFE_FILL_BEHIND_NULL);
#pragma prefast(pop)
    }
    else
    {
        hr = E_UNEXPECTED;
        StrExitOnFailure(hr, "for some reason our buffer is still null");
    }

LExit:
    return hr;
}


/********************************************************************
StrAllocFormatted - allocates or reuses dynamic string memory and formats it

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT __cdecl StrAllocFormatted(
    __deref_out_z LPWSTR* ppwz,
    __in __format_string LPCWSTR wzFormat,
    ...
    )
{
    Assert(ppwz && wzFormat && *wzFormat);

    HRESULT hr = S_OK;
    va_list args;

    va_start(args, wzFormat);
    hr = StrAllocFormattedArgs(ppwz, wzFormat, args);
    va_end(args);

    return hr;
}


/********************************************************************
StrAllocConcatFormatted - allocates or reuses dynamic string memory
and adds a formatted string

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT __cdecl StrAllocConcatFormatted(
    __deref_out_z LPWSTR* ppwz,
    __in __format_string LPCWSTR wzFormat,
    ...
    )
{
    Assert(ppwz && wzFormat && *wzFormat);

    HRESULT hr = S_OK;
    LPWSTR sczFormatted = NULL;
    va_list args;

    va_start(args, wzFormat);
    hr = StrAllocFormattedArgs(&sczFormatted, wzFormat, args);
    va_end(args);
    StrExitOnFailure(hr, "Failed to allocate formatted string");

    hr = StrAllocConcat(ppwz, sczFormatted, 0);

LExit:
    ReleaseStr(sczFormatted);

    return hr;
}


/********************************************************************
StrAllocConcatFormattedSecure - allocates or reuses dynamic string
memory and adds a formatted string. If the memory needs to be
reallocated, calls SecureZeroMemory on original block of memory after
it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT __cdecl StrAllocConcatFormattedSecure(
    __deref_out_z LPWSTR* ppwz,
    __in __format_string LPCWSTR wzFormat,
    ...
    )
{
    Assert(ppwz && wzFormat && *wzFormat);

    HRESULT hr = S_OK;
    LPWSTR sczFormatted = NULL;
    va_list args;

    va_start(args, wzFormat);
    hr = StrAllocFormattedArgsSecure(&sczFormatted, wzFormat, args);
    va_end(args);
    StrExitOnFailure(hr, "Failed to allocate formatted string");

    hr = StrAllocConcatSecure(ppwz, sczFormatted, 0);

LExit:
    ReleaseStr(sczFormatted);

    return hr;
}


/********************************************************************
StrAllocFormattedSecure - allocates or reuses dynamic string memory 
and formats it. If the memory needs to be reallocated,
calls SecureZeroMemory on original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT __cdecl StrAllocFormattedSecure(
    __deref_out_z LPWSTR* ppwz,
    __in __format_string LPCWSTR wzFormat,
    ...
    )
{
    Assert(ppwz && wzFormat && *wzFormat);

    HRESULT hr = S_OK;
    va_list args;

    va_start(args, wzFormat);
    hr = StrAllocFormattedArgsSecure(ppwz, wzFormat, args);
    va_end(args);

    return hr;
}


/********************************************************************
StrAnsiAllocFormatted - allocates or reuses dynamic ANSI string memory and formats it

NOTE: caller is responsible for freeing ppsz even if function fails
********************************************************************/
extern "C" HRESULT DAPI StrAnsiAllocFormatted(
    __deref_out_z LPSTR* ppsz,
    __in __format_string LPCSTR szFormat,
    ...
    )
{
    Assert(ppsz && szFormat && *szFormat);

    HRESULT hr = S_OK;
    va_list args;

    va_start(args, szFormat);
    hr = StrAnsiAllocFormattedArgs(ppsz, szFormat, args);
    va_end(args);

    return hr;
}


/********************************************************************
StrAllocFormattedArgs - allocates or reuses dynamic string memory 
and formats it with the passed in args

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT DAPI StrAllocFormattedArgs(
    __deref_out_z LPWSTR* ppwz,
    __in __format_string LPCWSTR wzFormat,
    __in va_list args
    )
{
    return AllocFormattedArgsHelper(ppwz, FALSE, wzFormat, args);
}


/********************************************************************
StrAllocFormattedArgsSecure - allocates or reuses dynamic string memory
and formats it with the passed in args.

If the memory needs to reallocated, calls SecureZeroMemory on the 
original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
extern "C" HRESULT DAPI StrAllocFormattedArgsSecure(
    __deref_out_z LPWSTR* ppwz,
    __in __format_string LPCWSTR wzFormat,
    __in va_list args
    )
{
    return AllocFormattedArgsHelper(ppwz, TRUE, wzFormat, args);
}


/********************************************************************
AllocFormattedArgsHelper - allocates or reuses dynamic string memory
and formats it with the passed in args.

If fZeroOnRealloc is true and the memory needs to reallocated, 
calls SecureZeroMemory on original block of memory after it is moved.

NOTE: caller is responsible for freeing ppwz even if function fails
********************************************************************/
static HRESULT AllocFormattedArgsHelper(
    __deref_out_z LPWSTR* ppwz,
    __in BOOL fZeroOnRealloc,
    __in __format_string LPCWSTR wzFormat,
    __in va_list args
    )
{
    Assert(ppwz && wzFormat && *wzFormat);

    HRESULT hr = S_OK;
    SIZE_T cch = 0;
    LPWSTR pwzOriginal = NULL;
    SIZE_T cbOriginal = 0;
    size_t cchOriginal = 0;

    if (*ppwz)
    {
        hr = StrSize(*ppwz, &cbOriginal);
        StrExitOnFailure(hr, "failed to get size of destination string");

        cch = cbOriginal / sizeof(WCHAR);  //convert the count in bytes to count in characters

        hr = ::StringCchLengthW(*ppwz, STRSAFE_MAX_CCH, &cchOriginal);
        StrExitOnRootFailure(hr, "failed to get length of original string");
    }

    if (0 == cch)   // if there is no space in the string buffer
    {
        cch = 256;

        hr = AllocHelper(ppwz, cch, fZeroOnRealloc);
        StrExitOnFailure(hr, "failed to allocate string to format: %ls", wzFormat);
    }

    // format the message (grow until it fits or there is a failure)
    do
    {
        hr = ::StringCchVPrintfW(*ppwz, cch, wzFormat, args);
        if (STRSAFE_E_INSUFFICIENT_BUFFER == hr)
        {
            if (!pwzOriginal)
            {
                // this allows you to pass the original string as a formatting argument and not crash
                // save the original string and free it after the printf is complete
                pwzOriginal = *ppwz;
                *ppwz = NULL;

                // StringCchVPrintfW starts writing to the string...
                // NOTE: this hack only works with sprintf(&pwz, "%s ...", pwz, ...);
                pwzOriginal[cchOriginal] = 0;
            }

            cch *= 2;

            hr = AllocHelper(ppwz, cch, fZeroOnRealloc);
            StrExitOnFailure(hr, "failed to allocate string to format: %ls", wzFormat);

            hr = S_FALSE;
        }
    } while (S_FALSE == hr);
    StrExitOnRootFailure(hr, "failed to format string");

LExit:
    if (pwzOriginal && fZeroOnRealloc)
    {
        SecureZeroMemory(pwzOriginal, cbOriginal);
    }

    ReleaseStr(pwzOriginal);

    return hr;
}


/********************************************************************
StrAnsiAllocFormattedArgs - allocates or reuses dynamic ANSI string memory 
and formats it with the passed in args

NOTE: caller is responsible for freeing ppsz even if function fails
********************************************************************/
extern "C" HRESULT DAPI StrAnsiAllocFormattedArgs(
    __deref_out_z LPSTR* ppsz,
    __in __format_string LPCSTR szFormat,
    __in va_list args
    )
{
    Assert(ppsz && szFormat && *szFormat);

    HRESULT hr = S_OK;
    SIZE_T cch = 0;
    LPSTR pszOriginal = NULL;
    size_t cchOriginal = 0;

    if (*ppsz)
    {
        hr = StrMaxLengthAnsi(*ppsz, &cch);
        StrExitOnFailure(hr, "failed to get size of destination string");

        hr = ::StringCchLengthA(*ppsz, STRSAFE_MAX_CCH, &cchOriginal);
        StrExitOnRootFailure(hr, "failed to get length of original string");
    }

    if (0 == cch)   // if there is no space in the string buffer
    {
        cch = 256;
        hr = StrAnsiAlloc(ppsz, cch);
        StrExitOnFailure(hr, "failed to allocate string to format: %s", szFormat);
    }

    // format the message (grow until it fits or there is a failure)
    do
    {
#pragma prefast(push)
#pragma prefast(disable:25068) // We intentionally don't use the unicode API here
        hr = ::StringCchVPrintfA(*ppsz, cch, szFormat, args);
#pragma prefast(pop)
        if (STRSAFE_E_INSUFFICIENT_BUFFER == hr)
        {
            if (!pszOriginal)
            {
                // this allows you to pass the original string as a formatting argument and not crash
                // save the original string and free it after the printf is complete
                pszOriginal = *ppsz;
                *ppsz = NULL;
                // StringCchVPrintfW starts writing to the string...
                // NOTE: this hack only works with sprintf(&pwz, "%s ...", pwz, ...);
                pszOriginal[cchOriginal] = 0;
            }
            cch *= 2;
            hr = StrAnsiAlloc(ppsz, cch);
            StrExitOnFailure(hr, "failed to allocate string to format: %hs", szFormat);
            hr = S_FALSE;
        }
    } while (S_FALSE == hr);
    StrExitOnRootFailure(hr, "failed to format string");

LExit:
    ReleaseStr(pszOriginal);

    return hr;
}


/********************************************************************
StrAllocFromError - returns the string for a particular error.

********************************************************************/
extern "C" HRESULT DAPI StrAllocFromError(
    __inout LPWSTR *ppwzMessage,
    __in HRESULT hrError,
    __in_opt HMODULE hModule,
    ...
    )
{
    HRESULT hr = S_OK;
    DWORD dwFlags = FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_MAX_WIDTH_MASK | FORMAT_MESSAGE_FROM_SYSTEM;
    LPVOID pvMessage = NULL;
    DWORD cchMessage = 0;

    if (hModule)
    {
        dwFlags |= FORMAT_MESSAGE_FROM_HMODULE;
    }

    va_list args;
    va_start(args, hModule);
    cchMessage = ::FormatMessageW(dwFlags, static_cast<LPCVOID>(hModule), hrError, 0, reinterpret_cast<LPWSTR>(&pvMessage), 0, &args);
    va_end(args);

    if (0 == cchMessage)
    {
        StrExitWithLastError(hr, "Failed to format message for error: 0x%x", hrError);
    }

    hr = StrAllocString(ppwzMessage, reinterpret_cast<LPCWSTR>(pvMessage), cchMessage);
    StrExitOnFailure(hr, "Failed to allocate string for message.");

LExit:
    if (pvMessage)
    {
        ::LocalFree(pvMessage);
    }

    return hr;
}


/********************************************************************
StrMaxLength - returns maximum number of characters that can be stored in dynamic string p

NOTE:  assumes Unicode string
********************************************************************/
extern "C" HRESULT DAPI StrMaxLength(
    __in LPCVOID p,
    __out SIZE_T* pcch
    )
{
    Assert(pcch);

    HRESULT hr = S_OK;

    if (p)
    {
        hr = StrSize(p, pcch);
        StrExitOnFailure(hr, "Failed to get size of string buffer.");

        *pcch /= sizeof(WCHAR);   // reduce to count of characters
    }
    else
    {
        *pcch = 0;
    }
    Assert(S_OK == hr);

LExit:
    return hr;
}


/********************************************************************
StrMaxLengthAnsi - returns maximum number of characters that can be stored in dynamic string p

NOTE:  assumes non-Unicode string
********************************************************************/
extern "C" HRESULT DAPI StrMaxLengthAnsi(
    __in LPCVOID p,
    __out SIZE_T* pcch
    )
{
    Assert(pcch);

    HRESULT hr = S_OK;

    if (p)
    {
        hr = StrSize(p, pcch);
        StrExitOnFailure(hr, "Failed to get size of string buffer.");

        *pcch /= sizeof(CHAR);   // reduce to count of characters
    }
    else
    {
        *pcch = 0;
    }
    Assert(S_OK == hr);

LExit:
    return hr;
}


/********************************************************************
StrSize - returns count of bytes in dynamic string p

********************************************************************/
extern "C" HRESULT DAPI StrSize(
    __in LPCVOID p,
    __out SIZE_T* pcb
    )
{
    Assert(p && pcb);

    return MemSizeChecked(p, pcb);
}

/********************************************************************
StrFree - releases dynamic string memory allocated by any StrAlloc*() functions

********************************************************************/
extern "C" HRESULT DAPI StrFree(
    __in LPVOID p
    )
{
    Assert(p);

    HRESULT hr = MemFree(p);
    StrExitOnFailure(hr, "failed to free string");

LExit:
    return hr;
}


/****************************************************************************
StrReplaceStringAll - Replaces wzOldSubString in ppOriginal with a wzNewSubString.
Replaces all instances.

****************************************************************************/
extern "C" HRESULT DAPI StrReplaceStringAll(
    __inout LPWSTR* ppwzOriginal,
    __in_z LPCWSTR wzOldSubString,
    __in_z LPCWSTR wzNewSubString
    )
{
    HRESULT hr = S_OK;
    DWORD dwStartIndex = 0;

    do
    {
        hr = StrReplaceString(ppwzOriginal, &dwStartIndex, wzOldSubString, wzNewSubString);
        StrExitOnFailure(hr, "Failed to replace substring");
    }
    while (S_OK == hr);

    hr = (0 == dwStartIndex) ? S_FALSE : S_OK;

LExit:
    return hr;
}


/****************************************************************************
StrReplaceString - Replaces wzOldSubString in ppOriginal with a wzNewSubString.
Search for old substring starts at dwStartIndex.  Does only 1 replace.

****************************************************************************/
extern "C" HRESULT DAPI StrReplaceString(
    __inout LPWSTR* ppwzOriginal,
    __inout DWORD* pdwStartIndex,
    __in_z LPCWSTR wzOldSubString,
    __in_z LPCWSTR wzNewSubString
    )
{
    Assert(ppwzOriginal && wzOldSubString && wzNewSubString);

    HRESULT hr = S_FALSE;
    LPCWSTR wzSubLocation = NULL;
    LPWSTR pwzBuffer = NULL;
    size_t cchOldSubString = 0;
    size_t cchNewSubString = 0;

    if (!*ppwzOriginal)
    {
        ExitFunction();
    }

    wzSubLocation = wcsstr(*ppwzOriginal + *pdwStartIndex, wzOldSubString);
    if (!wzSubLocation)
    {
        ExitFunction();
    }

    if (wzOldSubString)
    {
        hr = ::StringCchLengthW(wzOldSubString, STRSAFE_MAX_CCH, &cchOldSubString);
        StrExitOnRootFailure(hr, "Failed to get old string length.");
    }

    if (wzNewSubString)
    {
        hr = ::StringCchLengthW(wzNewSubString, STRSAFE_MAX_CCH, &cchNewSubString);
        StrExitOnRootFailure(hr, "Failed to get new string length.");
    }

    hr = ::PtrdiffTToDWord(wzSubLocation - *ppwzOriginal, pdwStartIndex);
    StrExitOnRootFailure(hr, "Failed to diff pointers.");

    hr = StrAllocString(&pwzBuffer, *ppwzOriginal, wzSubLocation - *ppwzOriginal);
    StrExitOnFailure(hr, "Failed to duplicate string.");

    pwzBuffer[wzSubLocation - *ppwzOriginal] = '\0';

    hr = StrAllocConcat(&pwzBuffer, wzNewSubString, 0);
    StrExitOnFailure(hr, "Failed to append new string.");

    hr = StrAllocConcat(&pwzBuffer, wzSubLocation + cchOldSubString, 0);
    StrExitOnFailure(hr, "Failed to append post string.");

    hr = StrFree(*ppwzOriginal);
    StrExitOnFailure(hr, "Failed to free original string.");

    *ppwzOriginal = pwzBuffer;
    *pdwStartIndex = *pdwStartIndex + static_cast<DWORD>(cchNewSubString);
    hr = S_OK;

LExit:
    return hr;
}


static inline BYTE HexCharToByte(
    __in WCHAR wc
    )
{
    Assert(L'0' <= wc && wc <= L'9' || L'a' <= wc && wc <= L'f' || L'A' <= wc && wc <= L'F');  // make sure wc is a hex character

    BYTE b;
    if (L'0' <= wc && wc <= L'9')
    {
        b = (BYTE)(wc - L'0');
    }
    else if ('a' <= wc && wc <= 'f')
    {
        b = (BYTE)(wc - L'0' - (L'a' - L'9' - 1));
    }
    else  // must be (L'A' <= wc && wc <= L'F')
    {
        b = (BYTE)(wc - L'0' - (L'A' - L'9' - 1));
    }

    Assert(0 <= b && b <= 15);
    return b;
}


/****************************************************************************
StrHexEncode - converts an array of bytes to a text string

NOTE: wzDest must have space for cbSource * 2 + 1 characters
****************************************************************************/
extern "C" HRESULT DAPI StrHexEncode(
    __in_ecount(cbSource) const BYTE* pbSource,
    __in SIZE_T cbSource,
    __out_ecount(cchDest) LPWSTR wzDest,
    __in SIZE_T cchDest
    )
{
    Assert(pbSource && wzDest);

    HRESULT hr = S_OK;
    DWORD i;
    BYTE b;

    if (cchDest < 2 * cbSource + 1)
    {
        ExitFunction1(hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
    }

    for (i = 0; i < cbSource; ++i)
    {
        b = (*pbSource) >> 4;
        *(wzDest++) = (WCHAR)(L'0' + b + ((b < 10) ? 0 : L'A'-L'9'-1));
        b = (*pbSource) & 0xF;
        *(wzDest++) = (WCHAR)(L'0' + b + ((b < 10) ? 0 : L'A'-L'9'-1));

        ++pbSource;
    }

    *wzDest = 0;

LExit:
    return hr;
}


/****************************************************************************
StrAllocHexEncode - converts an array of bytes to an allocated text string

****************************************************************************/
HRESULT DAPI StrAllocHexEncode(
    __in_ecount(cbSource) const BYTE* pbSource,
    __in SIZE_T cbSource,
    __deref_out_ecount_z(2*(cbSource+1)) LPWSTR* ppwzDest
    )
{
    HRESULT hr = S_OK;
    SIZE_T cchSource = sizeof(WCHAR) * (cbSource + 1);

    hr = StrAlloc(ppwzDest, cchSource);
    StrExitOnFailure(hr, "Failed to allocate hex string.");

    hr = StrHexEncode(pbSource, cbSource, *ppwzDest, cchSource);
    StrExitOnFailure(hr, "Failed to encode hex string.");

LExit:
    return hr;
}


/****************************************************************************
StrHexDecode - converts a string of text to array of bytes

NOTE: wzSource must contain even number of characters
****************************************************************************/
extern "C" HRESULT DAPI StrHexDecode(
    __in_z LPCWSTR wzSource,
    __out_bcount(cbDest) BYTE* pbDest,
    __in SIZE_T cbDest
    )
{
    Assert(wzSource && pbDest);

    HRESULT hr = S_OK;
    size_t cchSource = 0;
    size_t i = 0;
    BYTE b = 0;

    hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, &cchSource);
    StrExitOnRootFailure(hr, "Failed to get length of hex string: %ls", wzSource);

    Assert(0 == cchSource % 2);
    if (cbDest < cchSource / 2)
    {
        hr = HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
        StrExitOnRootFailure(hr, "Insufficient buffer to decode string '%ls' len: %Iu into %Iu bytes.", wzSource, cchSource, cbDest);
    }

    for (i = 0; i < cchSource / 2; ++i)
    {
        b = HexCharToByte(*wzSource++);
        (*pbDest) = b << 4;

        b = HexCharToByte(*wzSource++);
        (*pbDest) |= b & 0xF;

        ++pbDest;
    }

LExit:
    return hr;
}


/****************************************************************************
StrAllocHexDecode - allocates a byte array hex-converted from string of text

NOTE: wzSource must contain even number of characters
****************************************************************************/
extern "C" HRESULT DAPI StrAllocHexDecode(
    __in_z LPCWSTR wzSource,
    __out_bcount(*pcbDest) BYTE** ppbDest,
    __out_opt DWORD* pcbDest
    )
{
    Assert(wzSource && *wzSource && ppbDest);

    HRESULT hr = S_OK;
    size_t cch = 0;
    BYTE* pb = NULL;
    DWORD cb = 0;

    hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, &cch);
    StrExitOnFailure(hr, "Failed to calculate length of source string.");

    if (cch % 2)
    {
        hr = E_INVALIDARG;
        StrExitOnFailure(hr, "Invalid source parameter, string must be even length or it cannot be decoded.");
    }

    cb = static_cast<DWORD>(cch / 2);
    pb = static_cast<BYTE*>(MemAlloc(cb, TRUE));
    StrExitOnNull(pb, hr, E_OUTOFMEMORY, "Failed to allocate memory for hex decode.");

    hr = StrHexDecode(wzSource, pb, cb);
    StrExitOnFailure(hr, "Failed to decode source string.");

    *ppbDest = pb;
    pb = NULL;

    if (pcbDest)
    {
        *pcbDest = cb;
    }

LExit:
    ReleaseMem(pb);

    return hr;
}


/****************************************************************************
Base85 encoding/decoding data

****************************************************************************/
const WCHAR Base85EncodeTable[] = L"!%'()*+,-./0123456789:;?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[]^_abcdefghijklmnopqrstuvwxyz{|}~";

const BYTE Base85DecodeTable[256] =
{
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85,  0, 85, 85, 85,  1, 85,  2,  3,  4,  5,  6,  7,  8,  9, 10,
    11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 85, 85, 85, 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, 85, 52, 53, 54,
    85, 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,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85,
    85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85, 85
};

const UINT Base85PowerTable[4] = { 1, 85, 85*85, 85*85*85 };


/****************************************************************************
StrAllocBase85Encode - converts an array of bytes into an XML compatible string

****************************************************************************/
extern "C" HRESULT DAPI StrAllocBase85Encode(
    __in_bcount_opt(cbSource) const BYTE* pbSource,
    __in SIZE_T cbSource,
    __deref_out_z LPWSTR* pwzDest
    )
{
    HRESULT hr = S_OK;
    SIZE_T cchDest = 0;
    LPWSTR wzDest;
    DWORD_PTR iSource = 0;
    DWORD_PTR iDest = 0;

    if (!pwzDest || !pbSource)
    {
        return E_INVALIDARG;
    }

    // calc actual size of output
    cchDest = cbSource / 4;
    cchDest += cchDest * 4;
    if (cbSource & 3)
    {
        cchDest += (cbSource & 3) + 1;
    }
    ++cchDest; // add room for null terminator

    hr = StrAlloc(pwzDest, cchDest);
    StrExitOnFailure(hr, "failed to allocate destination string");

    wzDest = *pwzDest;

    // first, encode full words
    for (iSource = 0, iDest = 0; (iSource + 4 < cbSource) && (iDest + 5 < cchDest); iSource += 4, iDest += 5)
    {
        DWORD n = pbSource[iSource] + (pbSource[iSource + 1] << 8) + (pbSource[iSource + 2] << 16) + (pbSource[iSource + 3] << 24);
        DWORD k = n / 85;

        //Assert(0 <= (n - k * 85) && (n - k * 85) < countof(Base85EncodeTable));
        wzDest[iDest] = Base85EncodeTable[n - k * 85];
        n = k / 85;

        //Assert(0 <= (k - n * 85) && (k - n * 85) < countof(Base85EncodeTable));
        wzDest[iDest + 1] = Base85EncodeTable[k - n * 85];
        k = n / 85;

        //Assert(0 <= (n - k * 85) && (n - k * 85) < countof(Base85EncodeTable));
        wzDest[iDest + 2] = Base85EncodeTable[n - k * 85];
        n = k / 85;

        //Assert(0 <= (k - n * 85) && (k - n * 85) < countof(Base85EncodeTable));
        wzDest[iDest + 3] = Base85EncodeTable[k - n * 85];

        __assume(n <= DWORD_MAX / 85 / 85 / 85 / 85);

        //Assert(0 <= n && n < countof(Base85EncodeTable));
        wzDest[iDest + 4] = Base85EncodeTable[n];
    }

    // encode any remaining bytes
    if (iSource < cbSource)
    {
        DWORD n = 0;
        for (DWORD i = 0; iSource + i < cbSource; ++i)
        {
            n += pbSource[iSource + i] << (i << 3);
        }

        for (/* iSource already initialized */; iSource < cbSource && iDest < cchDest; ++iSource, ++iDest)
        {
            DWORD k = n / 85;

            //Assert(0 <= (n - k * 85) && (n - k * 85) < countof(Base85EncodeTable));
            wzDest[iDest] = Base85EncodeTable[n - k * 85];

            n = k;
        }

        wzDest[iDest] = Base85EncodeTable[n];
        ++iDest;
    }
    Assert(iSource == cbSource);
    Assert(iDest == cchDest - 1);

    wzDest[iDest] = L'\0';
    hr = S_OK;

LExit:
    return hr;
}


/****************************************************************************
StrAllocBase85Decode - converts a string of text to array of bytes

NOTE: Use MemFree() to release the allocated stream of bytes
****************************************************************************/
extern "C" HRESULT DAPI StrAllocBase85Decode(
    __in_z LPCWSTR wzSource,
    __deref_out_bcount(*pcbDest) BYTE** ppbDest,
    __out SIZE_T* pcbDest
    )
{
    HRESULT hr = S_OK;
    size_t cchSource = 0;
    DWORD_PTR i, n, k;

    BYTE* pbDest = 0;
    SIZE_T cbDest = 0;

    if (!wzSource || !ppbDest || !pcbDest)
    {
        ExitFunction1(hr = E_INVALIDARG);
    }

    hr = ::StringCchLengthW(wzSource, STRSAFE_MAX_CCH, &cchSource);
    StrExitOnRootFailure(hr, "failed to get length of base 85 string: %ls", wzSource);

    // evaluate size of output and check it
    k = cchSource / 5;
    cbDest = k << 2;
    k = cchSource - k * 5;
    if (k)
    {
        if (1 == k)
        {
            // decode error -- encoded size cannot equal 1 mod 5
            return E_UNEXPECTED;
        }

        cbDest += k - 1;
    }

    *ppbDest = static_cast<BYTE*>(MemAlloc(cbDest, FALSE));
    StrExitOnNull(*ppbDest, hr, E_OUTOFMEMORY, "failed allocate memory to decode the string");

    pbDest = *ppbDest;
    *pcbDest = cbDest;

    // decode full words first
    while (5 <= cchSource)
    {
        k = Base85DecodeTable[wzSource[0]];
        if (85 == k)
        {
            // illegal symbol
            return E_UNEXPECTED;
        }
        n = k;

        k = Base85DecodeTable[wzSource[1]];
        if (85 == k)
        {
            // illegal symbol
            return E_UNEXPECTED;
        }
        n += k * 85;

        k = Base85DecodeTable[wzSource[2]];
        if (85 == k)
        {
            // illegal symbol
            return E_UNEXPECTED;
        }
        n += k * (85 * 85);

        k = Base85DecodeTable[wzSource[3]];
        if (85 == k)
        {
            // illegal symbol
            return E_UNEXPECTED;
        }
        n += k * (85 * 85 * 85);

        k = Base85DecodeTable[wzSource[4]];
        if (85 == k)
        {
            // illegal symbol
            return E_UNEXPECTED;
        }
        k *= (85 * 85 * 85 * 85);

        // if (k + n > (1u << 32)) <=> (k > ~n) then decode error
        if (k > ~n)
        {
            // overflow
            return E_UNEXPECTED;
        }

        n += k;

        pbDest[0] = (BYTE) n;
        pbDest[1] = (BYTE) (n >> 8);
        pbDest[2] = (BYTE) (n >> 16);
        pbDest[3] = (BYTE) (n >> 24);

        wzSource += 5;
        pbDest += 4;
        cchSource -= 5;
    }

    if (cchSource)
    {
        n = 0;
        for (i = 0; i < cchSource; ++i)
        {
            k = Base85DecodeTable[wzSource[i]];
            if (85 == k)
            {
                // illegal symbol
                return E_UNEXPECTED;
            }

            n += k * Base85PowerTable[i];
        }

        for (i = 1; i < cchSource; ++i)
        {
            *pbDest++ = (BYTE)n;
            n >>= 8;
        }

        if (0 != n)
        {
            // decode error
            return E_UNEXPECTED;
        }
    }

    hr = S_OK;

LExit:
    return hr;
}


/****************************************************************************
MultiSzLen - calculates the length of a MULTISZ string including all nulls
including the double null terminator at the end of the MULTISZ.

NOTE: returns 0 if the multisz in not properly terminated with two nulls
****************************************************************************/
extern "C" HRESULT DAPI MultiSzLen(
    __in_ecount(*pcch) __nullnullterminated LPCWSTR pwzMultiSz,
    __out SIZE_T* pcch
)
{
    Assert(pcch);

    HRESULT hr = S_OK;
    LPCWSTR wz = pwzMultiSz;
    DWORD_PTR dwMaxSize = 0;

    hr = StrMaxLength(pwzMultiSz, &dwMaxSize);
    StrExitOnFailure(hr, "failed to get the max size of a string while calculating MULTISZ length");

    *pcch = 0;
    while (*pcch < dwMaxSize)
    {
        if (L'\0' == *wz && L'\0' == *(wz + 1))
        {
            break;
        }

        ++wz;
        *pcch = *pcch + 1;
    }

    // Add two for the last 2 NULLs (that we looked ahead at)
    *pcch = *pcch + 2;

    // If we've walked off the end then the length is 0
    if (*pcch > dwMaxSize)
    {
        *pcch = 0;
    }

LExit:
    return hr;
}


/****************************************************************************
MultiSzPrepend - prepends a string onto the front of a MUTLISZ

****************************************************************************/
extern "C" HRESULT DAPI MultiSzPrepend(
    __deref_inout_ecount(*pcchMultiSz) __nullnullterminated LPWSTR* ppwzMultiSz,
    __inout_opt SIZE_T* pcchMultiSz,
    __in __nullnullterminated LPCWSTR pwzInsert
    )
{
    Assert(ppwzMultiSz && pwzInsert && *pwzInsert);

    HRESULT hr =S_OK;
    LPWSTR pwzResult = NULL;
    SIZE_T cchResult = 0;
    SIZE_T cchInsert = 0;
    SIZE_T cchMultiSz = 0;

    // Get the lengths of the MULTISZ (and prime it if it's not initialized)
    if (pcchMultiSz && 0 != *pcchMultiSz)
    {
        cchMultiSz = *pcchMultiSz;
    }
    else
    {
        hr = MultiSzLen(*ppwzMultiSz, &cchMultiSz);
        StrExitOnFailure(hr, "failed to get length of multisz");
    }

    hr = ::StringCchLengthW(pwzInsert, STRSAFE_MAX_CCH, reinterpret_cast<size_t*>(&cchInsert));
    StrExitOnRootFailure(hr, "failed to get length of insert string");

    cchResult = cchInsert + cchMultiSz + 1;

    // Allocate the result buffer
    hr = StrAlloc(&pwzResult, cchResult + 1);
    StrExitOnFailure(hr, "failed to allocate result string");
 
    // Prepend
    hr = ::StringCchCopyW(pwzResult, cchResult, pwzInsert);
    StrExitOnRootFailure(hr, "failed to copy prepend string: %ls", pwzInsert);

    // If there was no MULTISZ, double null terminate our result, otherwise, copy the MULTISZ in
    if (0 == cchMultiSz)
    {
        pwzResult[cchResult] = L'\0';
        ++cchResult;
    }
    else
    {
        // Copy the rest
        ::CopyMemory(pwzResult + cchInsert + 1, *ppwzMultiSz, cchMultiSz * sizeof(WCHAR));

        // Free the old buffer
        ReleaseNullStr(*ppwzMultiSz);
    }

    // Set the result
    *ppwzMultiSz = pwzResult;

    if (pcchMultiSz)
    {
        *pcchMultiSz = cchResult;
    }

    pwzResult = NULL;

LExit:
    ReleaseNullStr(pwzResult);

    return hr;
}

/****************************************************************************
MultiSzFindSubstring - case insensitive find of a string in a MULTISZ that contains the
specified sub string and returns the index of the
string in the MULTISZ, the address, neither, or both

NOTE: returns S_FALSE if the string is not found
****************************************************************************/
extern "C" HRESULT DAPI MultiSzFindSubstring(
    __in __nullnullterminated LPCWSTR pwzMultiSz,
    __in __nullnullterminated LPCWSTR pwzSubstring,
    __out_opt DWORD_PTR* pdwIndex,
    __deref_opt_out __nullnullterminated LPCWSTR* ppwzFoundIn
    )
{
    Assert(pwzMultiSz && *pwzMultiSz && pwzSubstring && *pwzSubstring);

    HRESULT hr = S_FALSE; // Assume we won't find it (the glass is half empty)
    LPCWSTR wz = pwzMultiSz;
    DWORD_PTR dwIndex = 0;
    SIZE_T cchMultiSz = 0;
    SIZE_T cchProgress = 0;

    hr = MultiSzLen(pwzMultiSz, &cchMultiSz);
    StrExitOnFailure(hr, "failed to get the length of a MULTISZ string");

    // Find the string containing the sub string
    hr = S_OK;
    while (NULL == wcsistr(wz, pwzSubstring))
    {
        // Slide through to the end of the current string
        while (L'\0' != *wz && cchProgress < cchMultiSz)
        {
            ++wz;
            ++cchProgress;
        }

        // If we're done, we're done
        if (L'\0' == *(wz + 1) || cchProgress >= cchMultiSz)
        {
            hr = S_FALSE;
            break;
        }

        // Move on to the next string
        ++wz;
        ++dwIndex;
    }
    Assert(S_OK == hr || S_FALSE == hr);

    // If we found it give them what they want
    if (S_OK == hr)
    {
        if (pdwIndex)
        {
            *pdwIndex = dwIndex;
        }

        if (ppwzFoundIn)
        {
            *ppwzFoundIn = wz;
        }
    }

LExit:
    return hr;
}

/****************************************************************************
MultiSzFindString - finds a string in a MULTISZ and returns the index of
the string in the MULTISZ, the address or both

NOTE: returns S_FALSE if the string is not found
****************************************************************************/
extern "C" HRESULT DAPI MultiSzFindString(
    __in __nullnullterminated LPCWSTR pwzMultiSz,
    __in __nullnullterminated LPCWSTR pwzString,
    __out_opt DWORD_PTR* pdwIndex,
    __deref_opt_out __nullnullterminated LPCWSTR* ppwzFound
    )
{
    Assert(pwzMultiSz && *pwzMultiSz && pwzString && *pwzString && (pdwIndex || ppwzFound));

    HRESULT hr = S_FALSE; // Assume we won't find it
    LPCWSTR wz = pwzMultiSz;
    DWORD_PTR dwIndex = 0;
    SIZE_T cchMutliSz = 0;
    SIZE_T cchProgress = 0;

    hr = MultiSzLen(pwzMultiSz, &cchMutliSz);
    StrExitOnFailure(hr, "failed to get the length of a MULTISZ string");

    // Find the string
    hr = S_OK;
    while (0 != lstrcmpW(wz, pwzString))
    {
        // Slide through to the end of the current string
        while (L'\0' != *wz && cchProgress < cchMutliSz)
        {
            ++wz;
            ++cchProgress;
        }

        // If we're done, we're done
        if (L'\0' == *(wz + 1) || cchProgress >= cchMutliSz)
        {
            hr = S_FALSE;
            break;
        }

        // Move on to the next string
        ++wz;
        ++dwIndex;
    }
    Assert(S_OK == hr || S_FALSE == hr);

    // If we found it give them what they want
    if (S_OK == hr)
    {
        if (pdwIndex)
        {
            *pdwIndex = dwIndex;
        }

        if (ppwzFound)
        {
            *ppwzFound = wz;
        }
    }

LExit:
    return hr;
}

/****************************************************************************
MultiSzRemoveString - removes string from a MULTISZ at the specified
index

NOTE: does an in place removal without shrinking the memory allocation

NOTE: returns S_FALSE if the MULTISZ has fewer strings than dwIndex
****************************************************************************/
extern "C" HRESULT DAPI MultiSzRemoveString(
    __deref_inout __nullnullterminated LPWSTR* ppwzMultiSz,
    __in DWORD_PTR dwIndex
    )
{
    Assert(ppwzMultiSz && *ppwzMultiSz);

    HRESULT hr = S_OK;
    LPCWSTR wz = *ppwzMultiSz;
    LPCWSTR wzNext = NULL;
    DWORD_PTR dwCurrentIndex = 0;
    SIZE_T cchMultiSz = 0;
    SIZE_T cchProgress = 0;

    hr = MultiSzLen(*ppwzMultiSz, &cchMultiSz);
    StrExitOnFailure(hr, "failed to get the length of a MULTISZ string");

    // Find the index we want to remove
    hr = S_OK;
    while (dwCurrentIndex < dwIndex)
    {
        // Slide through to the end of the current string
        while (L'\0' != *wz && cchProgress < cchMultiSz)
        {
            ++wz;
            ++cchProgress;
        }

        // If we're done, we're done
        if (L'\0' == *(wz + 1) || cchProgress >= cchMultiSz)
        {
            hr = S_FALSE;
            break;
        }

        // Move on to the next string
        ++wz;
        ++cchProgress;
        ++dwCurrentIndex;
    }
    Assert(S_OK == hr || S_FALSE == hr);

    // If we found the index to be removed
    if (S_OK == hr)
    {
        wzNext = wz;

        // Slide through to the end of the current string
        while (L'\0' != *wzNext && cchProgress < cchMultiSz)
        {
            ++wzNext;
            ++cchProgress;
        }

        // Something weird has happened if we're past the end of the MULTISZ
        if (cchProgress > cchMultiSz)
        {
            hr = E_UNEXPECTED;
            StrExitOnFailure(hr, "failed to move past the string to be removed from MULTISZ");
        }

        // Move on to the next character
        ++wzNext;
        ++cchProgress;

        ::MoveMemory((LPVOID)wz, (LPVOID)wzNext, (cchMultiSz - cchProgress) * sizeof(WCHAR));
    }

LExit:
    return hr;
}

/****************************************************************************
MultiSzInsertString - inserts new string at the specified index

****************************************************************************/
extern "C" HRESULT DAPI MultiSzInsertString(
    __deref_inout __nullnullterminated LPWSTR* ppwzMultiSz,
    __inout_opt SIZE_T* pcchMultiSz,
    __in DWORD_PTR dwIndex,
    __in_z LPCWSTR pwzInsert
    )
{
    Assert(ppwzMultiSz && pwzInsert && *pwzInsert);

    HRESULT hr = S_OK;
    LPCWSTR wz = *ppwzMultiSz;
    DWORD_PTR dwCurrentIndex = 0;
    SIZE_T cchProgress = 0;
    LPWSTR pwzResult = NULL;
    SIZE_T cchResult = 0;
    SIZE_T cchString = 0;
    SIZE_T cchMultiSz = 0;

    hr = ::StringCchLengthW(pwzInsert, STRSAFE_MAX_CCH, reinterpret_cast<size_t*>(&cchString));
    StrExitOnRootFailure(hr, "failed to get length of insert string");

    if (pcchMultiSz && 0 != *pcchMultiSz)
    {
        cchMultiSz = *pcchMultiSz;
    }
    else
    {
        hr = MultiSzLen(*ppwzMultiSz, &cchMultiSz);
        StrExitOnFailure(hr, "failed to get the length of a MULTISZ string");
    }

    // Find the index we want to insert at
    hr = S_OK;
    while (dwCurrentIndex < dwIndex)
    {
        // Slide through to the end of the current string
        while (L'\0' != *wz && cchProgress < cchMultiSz)
        {
            ++wz;
            ++cchProgress;
        }

        // If we're done, we're done
        if ((dwCurrentIndex + 1 != dwIndex && L'\0' == *(wz + 1)) || cchProgress >= cchMultiSz)
        {
            hr = HRESULT_FROM_WIN32(ERROR_OBJECT_NOT_FOUND);
            StrExitOnRootFailure(hr, "requested to insert into an invalid index: %u in a MULTISZ", dwIndex);
        }

        // Move on to the next string
        ++wz;
        ++cchProgress;
        ++dwCurrentIndex;
    }

    //
    // Insert the string
    //
    cchResult = cchMultiSz + cchString + 1;

    hr = StrAlloc(&pwzResult, cchResult);
    StrExitOnFailure(hr, "failed to allocate result string for MULTISZ insert");

    // Copy the part before the insert
    ::CopyMemory(pwzResult, *ppwzMultiSz, cchProgress * sizeof(WCHAR));

    // Copy the insert part
    ::CopyMemory(pwzResult + cchProgress, pwzInsert, (cchString + 1) * sizeof(WCHAR));

    // Copy the part after the insert
    ::CopyMemory(pwzResult + cchProgress + cchString + 1, wz, (cchMultiSz - cchProgress) * sizeof(WCHAR));

    // Free the old buffer
    ReleaseNullStr(*ppwzMultiSz);

    // Set the result
    *ppwzMultiSz = pwzResult;

    // If they wanted the resulting length, let 'em have it
    if (pcchMultiSz)
    {
        *pcchMultiSz = cchResult;
    }

    pwzResult = NULL;

LExit:
    ReleaseStr(pwzResult);

    return hr;
}

/****************************************************************************
MultiSzReplaceString - replaces string at the specified index with a new one

****************************************************************************/
extern "C" HRESULT DAPI MultiSzReplaceString(
    __deref_inout __nullnullterminated LPWSTR* ppwzMultiSz,
    __in DWORD_PTR dwIndex,
    __in_z LPCWSTR pwzString
    )
{
    Assert(ppwzMultiSz && pwzString && *pwzString);

    HRESULT hr = S_OK;

    hr = MultiSzRemoveString(ppwzMultiSz, dwIndex);
    StrExitOnFailure(hr, "failed to remove string from MULTISZ at the specified index: %u", dwIndex);

    hr = MultiSzInsertString(ppwzMultiSz, NULL, dwIndex, pwzString);
    StrExitOnFailure(hr, "failed to insert string into MULTISZ at the specified index: %u", dwIndex);

LExit:
    return hr;
}


/****************************************************************************
wcsistr - case insensitive find a substring

****************************************************************************/
extern "C" LPCWSTR DAPI wcsistr(
    __in_z LPCWSTR wzString,
    __in_z LPCWSTR wzCharSet
    )
{
    LPCWSTR wzSource = wzString;
    LPCWSTR wzSearch = NULL;
    SIZE_T cchSourceIndex = 0;

    // Walk through wzString (the source string) one character at a time
    while (*wzSource)
    {
        cchSourceIndex = 0;
        wzSearch = wzCharSet;

        // Look ahead in the source string until we get a full match or we hit the end of the source
        while (L'\0' != wzSource[cchSourceIndex] && L'\0' != *wzSearch && towlower(wzSource[cchSourceIndex]) == towlower(*wzSearch))
        {
            ++cchSourceIndex;
            ++wzSearch;
        }

        // If we found it, return the point that we found it at
        if (L'\0' == *wzSearch)
        {
            return wzSource;
        }

        // Walk ahead one character
        ++wzSource;
    }

    return NULL;
}

/****************************************************************************
StrStringToInt16 - converts a string to a signed 16-bit integer.

****************************************************************************/
extern "C" HRESULT DAPI StrStringToInt16(
    __in_z LPCWSTR wzIn,
    __in DWORD cchIn,
    __out SHORT* psOut
    )
{
    HRESULT hr = S_OK;
    LONGLONG ll = 0;

    hr = StrStringToInt64(wzIn, cchIn, &ll);
    StrExitOnFailure(hr, "Failed to parse int64.");

    if (SHORT_MAX < ll || SHORT_MIN > ll)
    {
        ExitFunction1(hr = DISP_E_OVERFLOW);
    }
    *psOut = (SHORT)ll;

LExit:
    return hr;
}

/****************************************************************************
StrStringToUInt16 - converts a string to an unsigned 16-bit integer.

****************************************************************************/
extern "C" HRESULT DAPI StrStringToUInt16(
    __in_z LPCWSTR wzIn,
    __in DWORD cchIn,
    __out USHORT* pusOut
    )
{
    HRESULT hr = S_OK;
    ULONGLONG ull = 0;

    hr = StrStringToUInt64(wzIn, cchIn, &ull);
    StrExitOnFailure(hr, "Failed to parse uint64.");

    if (USHORT_MAX < ull)
    {
        ExitFunction1(hr = DISP_E_OVERFLOW);
    }
    *pusOut = (USHORT)ull;

LExit:
    return hr;
}

/****************************************************************************
StrStringToInt32 - converts a string to a signed 32-bit integer.

****************************************************************************/
extern "C" HRESULT DAPI StrStringToInt32(
    __in_z LPCWSTR wzIn,
    __in DWORD cchIn,
    __out INT* piOut
    )
{
    HRESULT hr = S_OK;
    LONGLONG ll = 0;

    hr = StrStringToInt64(wzIn, cchIn, &ll);
    StrExitOnFailure(hr, "Failed to parse int64.");

    if (INT_MAX < ll || INT_MIN > ll)
    {
        ExitFunction1(hr = DISP_E_OVERFLOW);
    }
    *piOut = (INT)ll;

LExit:
    return hr;
}

/****************************************************************************
StrStringToUInt32 - converts a string to an unsigned 32-bit integer.

****************************************************************************/
extern "C" HRESULT DAPI StrStringToUInt32(
    __in_z LPCWSTR wzIn,
    __in DWORD cchIn,
    __out UINT* puiOut
    )
{
    HRESULT hr = S_OK;
    ULONGLONG ull = 0;

    hr = StrStringToUInt64(wzIn, cchIn, &ull);
    StrExitOnFailure(hr, "Failed to parse uint64.");

    if (UINT_MAX < ull)
    {
        ExitFunction1(hr = DISP_E_OVERFLOW);
    }
    *puiOut = (UINT)ull;

LExit:
    return hr;
}

/****************************************************************************
StrStringToInt64 - converts a string to a signed 64-bit integer.

****************************************************************************/
extern "C" HRESULT DAPI StrStringToInt64(
    __in_z LPCWSTR wzIn,
    __in DWORD cchIn,
    __out LONGLONG* pllOut
    )
{
    HRESULT hr = S_OK;
    DWORD i = 0;
    INT iSign = 1;
    INT nDigit = 0;
    LARGE_INTEGER liValue = { };
    size_t cchString = 0;

    // get string length if not provided
    if (0 >= cchIn)
    {
        hr = ::StringCchLengthW(wzIn, STRSAFE_MAX_CCH, &cchString);
        StrExitOnRootFailure(hr, "Failed to get length of string.");

        cchIn = (DWORD)cchString;
        if (0 >= cchIn)
        {
            ExitFunction1(hr = E_INVALIDARG);
        }
    }

    // check sign
    if (L'-' == wzIn[0])
    {
        if (1 >= cchIn)
        {
            ExitFunction1(hr = E_INVALIDARG);
        }
        i = 1;
        iSign = -1;
    }

    // read digits
    while (i < cchIn)
    {
        nDigit = wzIn[i] - L'0';
        if (0 > nDigit || 9 < nDigit)
        {
            ExitFunction1(hr = E_INVALIDARG);
        }
        liValue.QuadPart = liValue.QuadPart * 10 + nDigit * iSign;

        if ((liValue.HighPart ^ iSign) & INT_MIN)
        {
            ExitFunction1(hr = DISP_E_OVERFLOW);
        }
        ++i;
    }

    *pllOut = liValue.QuadPart;

LExit:
    return hr;
}

/****************************************************************************
StrStringToUInt64 - converts a string to an unsigned 64-bit integer.

****************************************************************************/
extern "C" HRESULT DAPI StrStringToUInt64(
    __in_z LPCWSTR wzIn,
    __in DWORD cchIn,
    __out ULONGLONG* pullOut
    )
{
    HRESULT hr = S_OK;
    DWORD i = 0;
    DWORD nDigit = 0;
    ULONGLONG ullValue = 0;
    ULONGLONG ull = 0;
    size_t cchString = 0;

    // get string length if not provided
    if (0 >= cchIn)
    {
        hr = ::StringCchLengthW(wzIn, STRSAFE_MAX_CCH, &cchString);
        StrExitOnRootFailure(hr, "Failed to get length of string.");

        cchIn = (DWORD)cchString;
        if (0 >= cchIn)
        {
            ExitFunction1(hr = E_INVALIDARG);
        }
    }

    // read digits
    while (i < cchIn)
    {
        nDigit = wzIn[i] - L'0';
        if (0 > nDigit || 9 < nDigit)
        {
            ExitFunction1(hr = E_INVALIDARG);
        }
        ull = (ULONGLONG)(ullValue * 10 + nDigit);

        if (ull < ullValue)
        {
            ExitFunction1(hr = DISP_E_OVERFLOW);
        }
        ullValue = ull;
        ++i;
    }

    *pullOut = ullValue;

LExit:
    return hr;
}

/****************************************************************************
StrStringToUpper - alters the given string in-place to be entirely uppercase

****************************************************************************/
void DAPI StrStringToUpper(
    __inout_z LPWSTR wzIn
    )
{
    ::CharUpperBuffW(wzIn, lstrlenW(wzIn));
}

/****************************************************************************
StrStringToLower - alters the given string in-place to be entirely lowercase

****************************************************************************/
void DAPI StrStringToLower(
    __inout_z LPWSTR wzIn
    )
{
    ::CharLowerBuffW(wzIn, lstrlenW(wzIn));
}

/****************************************************************************
StrAllocStringToUpperInvariant - creates an upper-case copy of a string.

****************************************************************************/
extern "C" HRESULT DAPI StrAllocStringToUpperInvariant(
    __deref_out_z LPWSTR* pscz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource
    )
{
    return StrAllocStringMapInvariant(pscz, wzSource, cchSource, LCMAP_UPPERCASE);
}

/****************************************************************************
StrAllocStringToLowerInvariant - creates an lower-case copy of a string.

****************************************************************************/
extern "C" HRESULT DAPI StrAllocStringToLowerInvariant(
    __deref_out_z LPWSTR* pscz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource
    )
{
    return StrAllocStringMapInvariant(pscz, wzSource, cchSource, LCMAP_LOWERCASE);
}

/****************************************************************************
StrArrayAllocString - Allocates a string array.

****************************************************************************/
extern "C" HRESULT DAPI StrArrayAllocString(
    __deref_inout_ecount_opt(*pcStrArray) LPWSTR **prgsczStrArray,
    __inout LPUINT pcStrArray,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource
    )
{
    HRESULT hr = S_OK;
    UINT cNewStrArray;

    hr = ::UIntAdd(*pcStrArray, 1, &cNewStrArray);
    StrExitOnFailure(hr, "Failed to increment the string array element count.");

    hr = MemEnsureArraySize(reinterpret_cast<LPVOID*>(prgsczStrArray), cNewStrArray, sizeof(LPWSTR), ARRAY_GROWTH_SIZE);
    StrExitOnFailure(hr, "Failed to allocate memory for the string array.");

    hr = StrAllocString(&(*prgsczStrArray)[*pcStrArray], wzSource, cchSource);
    StrExitOnFailure(hr, "Failed to allocate and assign the string.");

    *pcStrArray = cNewStrArray;

LExit:
    return hr;
}

/****************************************************************************
StrArrayFree - Frees a string array.

Use ReleaseNullStrArray to nullify the arguments.

****************************************************************************/
extern "C" HRESULT DAPI StrArrayFree(
    __in_ecount(cStrArray) LPWSTR *rgsczStrArray,
    __in UINT cStrArray
    )
{
    HRESULT hr = S_OK;

    for (UINT i = 0; i < cStrArray; ++i)
    {
        if (NULL != rgsczStrArray[i])
        {
            hr = StrFree(rgsczStrArray[i]);
            StrExitOnFailure(hr, "Failed to free the string at index %u.", i);
        }
    }

    hr = MemFree(rgsczStrArray);
    StrExitOnFailure(hr, "Failed to free memory for the string array.");

LExit:
    return hr;
}

/****************************************************************************
StrSplitAllocArray - Splits a string into an array.

****************************************************************************/
extern "C" HRESULT DAPI StrSplitAllocArray(
    __deref_inout_ecount_opt(*pcStrArray) LPWSTR **prgsczStrArray,
    __inout LPUINT pcStrArray,
    __in_z LPCWSTR wzSource,
    __in_z LPCWSTR wzDelim
    )
{
    HRESULT hr = S_OK;
    LPWSTR sczCopy = NULL;
    LPWSTR wzContext = NULL;

    // Copy wzSource so it is not modified.
    hr = StrAllocString(&sczCopy, wzSource, 0);
    StrExitOnFailure(hr, "Failed to copy the source string.");

    for (LPCWSTR wzToken = ::wcstok_s(sczCopy, wzDelim, &wzContext); wzToken; wzToken = ::wcstok_s(NULL, wzDelim, &wzContext))
    {
        hr = StrArrayAllocString(prgsczStrArray, pcStrArray, wzToken, 0);
        StrExitOnFailure(hr, "Failed to add the string to the string array.");
    }

LExit:
    ReleaseStr(sczCopy);

    return hr;
}

/****************************************************************************
StrAllocStringMapInvariant - helper function for the ToUpper and ToLower.

Note: Assumes source and destination buffers will be the same.
****************************************************************************/
static HRESULT StrAllocStringMapInvariant(
    __deref_out_z LPWSTR* pscz,
    __in_z LPCWSTR wzSource,
    __in SIZE_T cchSource,
    __in DWORD dwMapFlags
    )
{
    HRESULT hr = S_OK;

    hr = StrAllocString(pscz, wzSource, cchSource);
    StrExitOnFailure(hr, "Failed to allocate a copy of the source string.");

    if (0 == cchSource)
    {
        // Need the actual string size for LCMapString. This includes the null-terminator
        // but LCMapString doesn't care either way.
        hr = ::StringCchLengthW(*pscz, INT_MAX, reinterpret_cast<size_t*>(&cchSource));
        StrExitOnRootFailure(hr, "Failed to get the length of the string.");
    }
    else if (INT_MAX < cchSource)
    {
        StrExitOnRootFailure(hr = E_INVALIDARG, "Source string is too long: %Iu", cchSource);
    }

    // Convert the copy of the string to upper or lower case in-place.
    if (0 == ::LCMapStringW(LOCALE_INVARIANT, dwMapFlags, *pscz, static_cast<int>(cchSource), *pscz, static_cast<int>(cchSource)))
    {
        StrExitWithLastError(hr, "Failed to convert the string case.");
    }

LExit:
    return hr;
}

/****************************************************************************
StrSecureZeroString - zeroes out string to the make sure the contents
don't remain in memory.

****************************************************************************/
extern "C" DAPI_(HRESULT) StrSecureZeroString(
    __in LPWSTR pwz
    )
{
    HRESULT hr = S_OK;
    SIZE_T cb = 0;

    if (pwz)
    {
        hr = StrSize(pwz, &cb);
        StrExitOnFailure(hr, "Failed to get size of string");

        SecureZeroMemory(pwz, cb);
    }

LExit:
    return hr;
}

/****************************************************************************
StrSecureZeroFreeString - zeroes out string to the make sure the contents
don't remain in memory, then frees the string.

****************************************************************************/
extern "C" DAPI_(HRESULT) StrSecureZeroFreeString(
    __in LPWSTR pwz
    )
{
    HRESULT hr = S_OK;

    hr = StrSecureZeroString(pwz);
    ReleaseStr(pwz);

    return hr;
}