summaryrefslogtreecommitdiff
path: root/src/utilcode/stgpool.cpp
blob: e62aab7698915be2dd54272517b982139adb1b4f (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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//*****************************************************************************
// StgPool.cpp
//

// 
// Pools are used to reduce the amount of data actually required in the database.
// This allows for duplicate string and binary values to be folded into one
// copy shared by the rest of the database.  Strings are tracked in a hash
// table when insert/changing data to find duplicates quickly.  The strings
// are then persisted consecutively in a stream in the database format.
//
//*****************************************************************************
#include "stdafx.h"                     // Standard include.
#include <stgpool.h>                    // Our interface definitions.
#include <posterror.h>                  // Error handling.
#include <safemath.h>                   // CLRSafeInt integer overflow checking
#include "../md/inc/streamutil.h"

#include "ex.h"

#ifdef FEATURE_PREJIT
#include <corcompile.h>
#endif

using namespace StreamUtil;

#define MAX_CHAIN_LENGTH 20             // Max chain length before rehashing.

//
//
// StgPool
//
//


//*****************************************************************************
// Free any memory we allocated.
//*****************************************************************************
StgPool::~StgPool()
{
    WRAPPER_NO_CONTRACT;

    Uninit();
} // StgPool::~StgPool()


//*****************************************************************************
// Init the pool for use.  This is called for both the create empty case.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::InitNew(
    ULONG cbSize,       // Estimated size.
    ULONG cItems)       // Estimated item count.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY);
    }
    CONTRACTL_END

    // Make sure we aren't stomping anything and are properly initialized.
    _ASSERTE(m_pSegData == m_zeros);
    _ASSERTE(m_pNextSeg == 0);
    _ASSERTE(m_pCurSeg == this);
    _ASSERTE(m_cbCurSegOffset == 0);
    _ASSERTE(m_cbSegSize == 0);
    _ASSERTE(m_cbSegNext == 0);
    
    m_bReadOnly = false;
    m_bFree = false;
    
    return S_OK;
} // StgPool::InitNew

//*****************************************************************************
// Init the pool from existing data.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::InitOnMem(
    void *pData,        // Predefined data.
    ULONG iSize,        // Size of data.
    int   bReadOnly)    // true if append is forbidden.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    // Make sure we aren't stomping anything and are properly initialized.
    _ASSERTE(m_pSegData == m_zeros);
    _ASSERTE(m_pNextSeg == 0);
    _ASSERTE(m_pCurSeg == this);
    _ASSERTE(m_cbCurSegOffset == 0);

    // Create case requires no further action.
    if (!pData)
        return (E_INVALIDARG);

    // Might we be extending this heap?
    m_bReadOnly = bReadOnly;


    m_pSegData = reinterpret_cast<BYTE*>(pData);
    m_cbSegSize = iSize;
    m_cbSegNext = iSize;
    
    m_bFree = false;
    
    return (S_OK);
} // StgPool::InitOnMem

//*****************************************************************************
// Called when the pool must stop accessing memory passed to InitOnMem().
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::TakeOwnershipOfInitMem()
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    // If the pool doesn't have a pointer to non-owned memory, done.
    if (m_bFree)
        return (S_OK);

    // If the pool doesn't have a pointer to memory at all, done.
    if (m_pSegData == m_zeros)
    {
        _ASSERTE(m_cbSegSize == 0);
        return (S_OK);
    }

    // Get some memory to keep.
    BYTE *pData = new (nothrow) BYTE[m_cbSegSize+4];
    if (pData == 0)
        return (PostError(OutOfMemory()));

    // Copy the old data to the new memory.
    memcpy(pData, m_pSegData, m_cbSegSize);
    m_pSegData = pData;
    m_bFree = true;

    return (S_OK);
} // StgPool::TakeOwnershipOfInitMem

//*****************************************************************************
// Clear out this pool.  Cannot use until you call InitNew.
//*****************************************************************************
void StgPool::Uninit()
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
    }
    CONTRACTL_END

    // Free base segment, if appropriate.
    if (m_bFree && (m_pSegData != m_zeros))
    {
        delete [] m_pSegData;
        m_bFree = false;
    }

    // Free chain, if any.
    StgPoolSeg  *pSeg = m_pNextSeg;
    while (pSeg)
    {
        StgPoolSeg *pNext = pSeg->m_pNextSeg;
        delete [] (BYTE*)pSeg;
        pSeg = pNext;
    }

    // Clear vars.
    m_pSegData = (BYTE*)m_zeros;
    m_cbSegSize = m_cbSegNext = 0;
    m_pNextSeg = 0;
    m_pCurSeg = this;
    m_cbCurSegOffset = 0;
} // StgPool::Uninit

//*****************************************************************************
// Called to copy the pool to writable memory, reset the r/o bit.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::ConvertToRW()
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    HRESULT     hr;                     // A result.
    IfFailRet(TakeOwnershipOfInitMem());

    IfFailRet(SetHash(true));

    m_bReadOnly = false;

    return S_OK;
} // StgPool::ConvertToRW

//*****************************************************************************
// Turn hashing off or on.  Real implementation as required in subclass.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::SetHash(int bHash)
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    return S_OK;
} // StgPool::SetHash

//*****************************************************************************
// Trim any empty final segment.
//*****************************************************************************
void StgPool::Trim()
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
    }
    CONTRACTL_END

    // If no chained segments, nothing to do.
    if (m_pNextSeg == 0)
        return;

    // Handle special case for a segment that was completely unused.
    if (m_pCurSeg->m_cbSegNext == 0)
    {
        // Find the segment which points to the empty segment.
        StgPoolSeg *pPrev;
        for (pPrev = this; pPrev && pPrev->m_pNextSeg != m_pCurSeg; pPrev = pPrev->m_pNextSeg);
        _ASSERTE(pPrev && pPrev->m_pNextSeg == m_pCurSeg);

        // Free the empty segment.
        delete [] (BYTE*) m_pCurSeg;
        
        // Fix the pCurSeg pointer.
        pPrev->m_pNextSeg = 0;
        m_pCurSeg = pPrev;

        // Adjust the base offset, because the PREVIOUS seg is now current.
        _ASSERTE(m_pCurSeg->m_cbSegNext <= m_cbCurSegOffset);
        m_cbCurSegOffset = m_cbCurSegOffset - m_pCurSeg->m_cbSegNext;
    }
} // StgPool::Trim

//*****************************************************************************
// Allocate memory if we don't have any, or grow what we have.  If successful,
// then at least iRequired bytes will be allocated.
//*****************************************************************************
bool StgPool::Grow(         // true if successful.
    ULONG iRequired)        // Min required bytes to allocate.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return FALSE;);
    }
    CONTRACTL_END

    ULONG       iNewSize;               // New size we want.
    StgPoolSeg  *pNew;                  // Temp pointer for malloc.

    _ASSERTE(!m_bReadOnly);

    // Would this put the pool over 2GB?
    if ((m_cbCurSegOffset + iRequired) > INT_MAX)
        return (false);

    // Adjust grow size as a ratio to avoid too many reallocs.
    if ((m_pCurSeg->m_cbSegNext + m_cbCurSegOffset) / m_ulGrowInc >= 3)
        m_ulGrowInc *= 2;

    // NOTE: MD\DataSource\RemoteMDInternalRWSource has taken a dependency that there
    // won't be more than 1000 segments. Given the current exponential growth algorithm
    // we'll never get anywhere close to that, but if the algorithm changes to allow for
    // many segments, please update that source as well.

    // If first time, handle specially.
    if (m_pSegData == m_zeros)
    {
        // Allocate the buffer.
        iNewSize = max(m_ulGrowInc, iRequired);
        BYTE *pSegData = new (nothrow) BYTE[iNewSize + 4];
        if (pSegData == NULL)
            return false;
        m_pSegData = pSegData;

        // Will need to delete it.
        m_bFree = true;

        // How big is this initial segment?
        m_cbSegSize = iNewSize;

        // Do some validation of var fields.
        _ASSERTE(m_cbSegNext == 0);
        _ASSERTE(m_pCurSeg == this);
        _ASSERTE(m_pNextSeg == NULL);

        return true;
    }

    // Allocate the new space enough for header + data.
    iNewSize = (ULONG)(max(m_ulGrowInc, iRequired) + sizeof(StgPoolSeg));
    pNew = (StgPoolSeg *)new (nothrow) BYTE[iNewSize+4];
    if (pNew == NULL)
        return false;

    // Set the fields in the new segment.
    pNew->m_pSegData = reinterpret_cast<BYTE*>(pNew) + sizeof(StgPoolSeg);
    _ASSERTE(ALIGN4BYTE(reinterpret_cast<ULONG_PTR>(pNew->m_pSegData)) == reinterpret_cast<ULONG_PTR>(pNew->m_pSegData));
    pNew->m_pNextSeg = 0;
    pNew->m_cbSegSize = iNewSize - sizeof(StgPoolSeg);
    pNew->m_cbSegNext = 0;

    // Calculate the base offset of the new segment.
    m_cbCurSegOffset = m_cbCurSegOffset + m_pCurSeg->m_cbSegNext;

    // Handle special case for a segment that was completely unused.
    //<TODO>@todo: Trim();</TODO>
    if (m_pCurSeg->m_cbSegNext == 0)
    {
        // Find the segment which points to the empty segment.
        StgPoolSeg *pPrev;
        for (pPrev = this; pPrev && pPrev->m_pNextSeg != m_pCurSeg; pPrev = pPrev->m_pNextSeg);
        _ASSERTE(pPrev && pPrev->m_pNextSeg == m_pCurSeg);

        // Free the empty segment.
        delete [] (BYTE *) m_pCurSeg;
        
        // Link in the new segment.
        pPrev->m_pNextSeg = pNew;
        m_pCurSeg = pNew;

        return true;
    }

    // Fix the size of the old segment.
    m_pCurSeg->m_cbSegSize = m_pCurSeg->m_cbSegNext;

    // Link the new segment into the chain.
    m_pCurSeg->m_pNextSeg = pNew;
    m_pCurSeg = pNew;

    return true;
} // StgPool::Grow

//*****************************************************************************
// Add a segment to the chain of segments.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::AddSegment(
    const void *pData,      // The data.
    ULONG       cbData,     // Size of the data.
    bool        bCopy)      // If true, make a copy of the data.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END
    
    StgPoolSeg *pNew;   // Temp pointer for malloc.
    
    
    // If we need to copy the data, just grow the heap by enough to take the
    //  the new data, and copy it in.
    if (bCopy)
    {
        void *pDataToAdd = new (nothrow) BYTE[cbData];
        IfNullRet(pDataToAdd);
        memcpy(pDataToAdd, pData, cbData);
        pData = pDataToAdd;
    }
    
    // If first time, handle specially.
    if (m_pSegData == m_zeros)
    {   // Data was passed in.
        m_pSegData = reinterpret_cast<BYTE*>(const_cast<void*>(pData));
        m_cbSegSize = cbData;
        m_cbSegNext = cbData;
        _ASSERTE(m_pNextSeg == NULL);
        
        // Will not delete it.
        m_bFree = false;
        
        return S_OK;
    }
    
    // Not first time.  Handle a completely empty tail segment.
    Trim();
    
    // Abandon any space past the end of the current live data.
    _ASSERTE(m_pCurSeg->m_cbSegSize >= m_pCurSeg->m_cbSegNext);
    m_pCurSeg->m_cbSegSize = m_pCurSeg->m_cbSegNext;
    
    // Allocate a new segment header.
    pNew = (StgPoolSeg *) new (nothrow) BYTE[sizeof(StgPoolSeg)];
    IfNullRet(pNew);
    
    // Set the fields in the new segment.
    pNew->m_pSegData = reinterpret_cast<BYTE*>(const_cast<void*>(pData));
    pNew->m_pNextSeg = NULL;
    pNew->m_cbSegSize = cbData;
    pNew->m_cbSegNext = cbData;
    
    // Calculate the base offset of the new segment.
    m_cbCurSegOffset = m_cbCurSegOffset + m_pCurSeg->m_cbSegNext;
    
    // Link the segment into the chain.
    _ASSERTE(m_pCurSeg->m_pNextSeg == NULL);
    m_pCurSeg->m_pNextSeg = pNew;
    m_pCurSeg = pNew;
    
    return S_OK;
} // StgPool::AddSegment

#ifndef DACCESS_COMPILE
//*****************************************************************************
// The entire string pool is written to the given stream. The stream is aligned
// to a 4 byte boundary.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::PersistToStream(
    IStream *pIStream)      // The stream to write to.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY);
    }
    CONTRACTL_END

    HRESULT     hr = S_OK;
    ULONG       cbTotal;                // Total bytes written.
    StgPoolSeg  *pSeg;                  // A segment being written.

    _ASSERTE(m_pSegData != m_zeros);

    // Start with the base segment.
    pSeg = this;
    cbTotal = 0;

    EX_TRY
    {
        // As long as there is data, write it.
        while (pSeg != NULL)
        {
            // If there is data in the segment . . .
            if (pSeg->m_cbSegNext)
            {   // . . . write and count the data.
                if (FAILED(hr = pIStream->Write(pSeg->m_pSegData, pSeg->m_cbSegNext, 0)))
                    break;
                cbTotal += pSeg->m_cbSegNext;
            }
    
            // Get the next segment.
            pSeg = pSeg->m_pNextSeg;
        }

        if (SUCCEEDED(hr))
        {
            // Align to variable (0-4 byte) boundary.
            UINT32 cbTotalAligned;
            if (FAILED(Align(cbTotal, &cbTotalAligned)))
            {
                hr = COR_E_BADIMAGEFORMAT;
            }
            else
            {
                if (cbTotalAligned > cbTotal)
                {
                    _ASSERTE(sizeof(hr) >= 3);
                    hr = 0;
                    hr = pIStream->Write(&hr, cbTotalAligned - cbTotal, 0);
                }
            }
        }
    }
    EX_CATCH
    {
        hr = E_FAIL;
    }
    EX_END_CATCH(SwallowAllExceptions);
    
    return hr;
} // StgPool::PersistToStream
#endif //!DACCESS_COMPILE

//*****************************************************************************
// The entire string pool is written to the given stream. The stream is aligned
// to a 4 byte boundary.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::PersistPartialToStream(
    IStream *pIStream,      // The stream to write to.
    ULONG    iOffset)       // Starting offset.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY);
    }
    CONTRACTL_END

    HRESULT     hr = S_OK;              // A result.
    ULONG       cbTotal;                // Total bytes written.
    StgPoolSeg  *pSeg;                  // A segment being written.

    _ASSERTE(m_pSegData != m_zeros);

    // Start with the base segment.
    pSeg = this;
    cbTotal = 0;

    // As long as there is data, write it.
    while (pSeg != NULL)
    {
        // If there is data in the segment . . .
        if (pSeg->m_cbSegNext)
        {   // If this data should be skipped...
            if (iOffset >= pSeg->m_cbSegNext)
            {   // Skip it
                iOffset -= pSeg->m_cbSegNext;
            }
            else
            {   // At least some data should be written, so write and count the data.
                IfFailRet(pIStream->Write(pSeg->m_pSegData+iOffset, pSeg->m_cbSegNext-iOffset, 0));
                cbTotal += pSeg->m_cbSegNext-iOffset;
                iOffset = 0;
            }
        }

        // Get the next segment.
        pSeg = pSeg->m_pNextSeg;
    }
    
    // Align to variable (0-4 byte) boundary.
    UINT32 cbTotalAligned;
    if (FAILED(Align(cbTotal, &cbTotalAligned)))
    {
        return COR_E_BADIMAGEFORMAT;
    }
    if (cbTotalAligned > cbTotal)
    {
        _ASSERTE(sizeof(hr) >= 3);
        hr = 0;
        hr = pIStream->Write(&hr, cbTotalAligned - cbTotal, 0);
    }
    
    return hr;
} // StgPool::PersistPartialToStream

// Copies data from pSourcePool starting at index nStartSourceIndex.
__checkReturn 
HRESULT 
StgPool::CopyPool(
    UINT32         nStartSourceIndex, 
    const StgPool *pSourcePool)
{
    HRESULT hr;
    UINT32 cbDataSize;
    BYTE  *pbData = NULL;
    
    if (nStartSourceIndex == pSourcePool->GetRawSize())
    {   // There's nothing to copy
        return S_OK;
    }
    if (nStartSourceIndex > pSourcePool->GetRawSize())
    {   // Invalid input
        Debug_ReportInternalError("The caller should not pass invalid start index in the pool.");
        IfFailGo(METADATA_E_INDEX_NOTFOUND);
    }
    
    // Allocate new segment
    cbDataSize = pSourcePool->GetRawSize() - nStartSourceIndex;
    pbData = new (nothrow) BYTE[cbDataSize];
    IfNullGo(pbData);
    
    // Copy data to the new segment
    UINT32 cbCopiedDataSize;
    IfFailGo(pSourcePool->CopyData(
        nStartSourceIndex, 
        pbData, 
        cbDataSize, 
        &cbCopiedDataSize));
    // Check that we copied everything
    if (cbDataSize != cbCopiedDataSize)
    {
        Debug_ReportInternalError("It is expected to copy everything from the source pool.");
        IfFailGo(E_FAIL);
    }
    
    // Add the newly allocated segment to the pool
    IfFailGo(AddSegment(
        pbData, 
        cbDataSize, 
        false));        // fCopyData
    
ErrExit:
    if (FAILED(hr))
    {
        if (pbData != NULL)
        {
            delete [] pbData;
        }
    }
    return hr;
} // StgPool::CopyPool

// Copies data from the pool into a buffer. It will correctly walk all segments for the copy.
__checkReturn 
HRESULT 
StgPool::CopyData(
    UINT32  nOffset, 
    BYTE   *pBuffer, 
    UINT32  cbBuffer, 
    UINT32 *pcbWritten) const
{
    CONTRACTL
    {
        NOTHROW;
        PRECONDITION(CheckPointer(pBuffer));
        PRECONDITION(CheckPointer(pcbWritten));
    }
    CONTRACTL_END
    
    HRESULT           hr = S_OK;
    const StgPoolSeg *pSeg;     // A segment being written.
    
    _ASSERTE(m_pSegData != m_zeros);
    
    // Start with the base segment.
    pSeg = this;
    *pcbWritten = 0;
    
    // As long as there is data, write it.
    while (pSeg != NULL)
    {
        // If there is data in the segment . . .
        if (pSeg->m_cbSegNext)
        {   // If this data should be skipped...
            if (nOffset >= pSeg->m_cbSegNext)
            {   // Skip it
                nOffset -= pSeg->m_cbSegNext;
            }
            else
            {
                ULONG nNumBytesToCopy = pSeg->m_cbSegNext - nOffset;
                if (nNumBytesToCopy > (cbBuffer - *pcbWritten))
                {
                    _ASSERTE(!"Buffer isn't big enough to copy everything!");
                    nNumBytesToCopy = cbBuffer - *pcbWritten;
                }
                
                memcpy(pBuffer + *pcbWritten, pSeg->m_pSegData+nOffset, nNumBytesToCopy);
                
                *pcbWritten += nNumBytesToCopy;
                nOffset = 0;
            }
        }
        
        // Get the next segment.
        pSeg = pSeg->m_pNextSeg;
    }
    
    return hr;
} // StgPool::CopyData

//*****************************************************************************
// Get a pointer to the data at some offset.  May require traversing the
//  chain of extensions.  It is the caller's responsibility not to attempt
//  to access data beyond the end of a segment.
// This is an internal accessor, and should only be called when the data
//  is not in the base segment.
//*****************************************************************************
__checkReturn 
HRESULT 
StgPool::GetData_i(
    UINT32              nOffset, 
    MetaData::DataBlob *pData)
{
    LIMITED_METHOD_CONTRACT;
    
    // Shouldn't be called on base segment.
    _ASSERTE(nOffset >= m_cbSegNext);
    StgPoolSeg *pSeg = this;
    
    while ((nOffset > 0) && (nOffset >= pSeg->m_cbSegNext))
    {
        // On to next segment.
        nOffset -= pSeg->m_cbSegNext;
        pSeg = pSeg->m_pNextSeg;
        
        // Is there a next?
        if (pSeg == NULL)
        {
            Debug_ReportError("Invalid offset passed - reached end of pool.");
            pData->Clear();
            return CLDB_E_INDEX_NOTFOUND;
        }
    }
    
    // For the case where we want to read the first item and the pool is empty.
    if (nOffset == pSeg->m_cbSegNext)
    {   // Can only be if both == 0
        Debug_ReportError("Invalid offset passed - it is at the end of pool.");
        pData->Clear();
        return CLDB_E_INDEX_NOTFOUND;
    }
    
    pData->Init(pSeg->m_pSegData + nOffset, pSeg->m_cbSegNext - nOffset);
    
    return S_OK;
} // StgPool::GetData_i

//
//
// StgStringPool
//
//


//*****************************************************************************
// Create a new, empty string pool.
//*****************************************************************************
__checkReturn 
HRESULT 
StgStringPool::InitNew(
    ULONG cbSize,       // Estimated size.
    ULONG cItems)       // Estimated item count.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY);
    }
    CONTRACTL_END
    
    HRESULT hr;
    UINT32  nEmptyStringOffset;
    
    // Let base class intialize.
    IfFailRet(StgPool::InitNew());
    
    // Set initial table sizes, if specified.
    if (cbSize > 0)
    {
        if (!Grow(cbSize))
        {
            return E_OUTOFMEMORY;
        }
    }
    if (cItems > 0)
    {
        m_Hash.SetBuckets(cItems);
    }
    
    // Init with empty string.
    IfFailRet(AddString("", &nEmptyStringOffset));
    // Empty string had better be at offset 0.
    _ASSERTE(nEmptyStringOffset == 0);
    
    return hr;
} // StgStringPool::InitNew

//*****************************************************************************
// Load a string heap from persisted memory.  If a copy of the data is made
// (so that it may be updated), then a new hash table is generated which can
// be used to elminate duplicates with new strings.
//*****************************************************************************
__checkReturn 
HRESULT 
StgStringPool::InitOnMem(
    void *pData,        // Predefined data.
    ULONG iSize,        // Size of data.
    int   bReadOnly)    // true if append is forbidden.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY);
    }
    CONTRACTL_END
    
    HRESULT hr = S_OK;
    
    // There may be up to three extra '\0' characters appended for padding.  Trim them.
    char *pchData = reinterpret_cast<char*>(pData);
    while (iSize > 1 && pchData[iSize-1] == 0 && pchData[iSize-2] == 0)
        --iSize;
    
    // Let base class init our memory structure.
    IfFailRet(StgPool::InitOnMem(pData, iSize, bReadOnly));
    
    //<TODO>@todo: defer this until we hand out a pointer.</TODO>
    if (!bReadOnly)
    {
        IfFailRet(TakeOwnershipOfInitMem());
        IfFailRet(RehashStrings());
    }
    
    return hr;
} // StgStringPool::InitOnMem

//*****************************************************************************
// Clears the hash table then calls the base class.
//*****************************************************************************
void StgStringPool::Uninit()
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
    }
    CONTRACTL_END

    // Clear the hash table.
    m_Hash.Clear();

    // Let base class clean up.
    StgPool::Uninit();
} // StgStringPool::Uninit

//*****************************************************************************
// Turn hashing off or on.  If you turn hashing on, then any existing data is
// thrown away and all data is rehashed during this call.
//*****************************************************************************
__checkReturn 
HRESULT 
StgStringPool::SetHash(int bHash)
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    HRESULT     hr = S_OK;

    // If turning on hash again, need to rehash all strings.
    if (bHash)
        hr = RehashStrings();

    m_bHash = bHash;
    return (hr);
} // StgStringPool::SetHash

//*****************************************************************************
// The string will be added to the pool.  The offset of the string in the pool
// is returned in *piOffset.  If the string is already in the pool, then the
// offset will be to the existing copy of the string.
//*****************************************************************************
__checkReturn 
HRESULT 
StgStringPool::AddString(
    LPCSTR  szString,       // The string to add to pool.
    UINT32 *pnOffset)       // Return offset of string here.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    STRINGHASH *pHash;                  // Hash item for add.
    ULONG       iLen;                   // To handle non-null strings.
    LPSTR       pData;                  // Pointer to location for new string.
    HRESULT     hr;
    
    _ASSERTE(!m_bReadOnly);

    // Null pointer is an error.
    if (szString == 0)
        return (PostError(E_INVALIDARG));

    // Find the real length we need in buffer.
    iLen = (ULONG)(strlen(szString) + 1);
    
    // Where to put the new string?
    if (iLen > GetCbSegAvailable())
    {
        if (!Grow(iLen))
            return (PostError(OutOfMemory()));
    }
    pData = reinterpret_cast<LPSTR>(GetNextLocation());
    
    // Copy the data into the buffer.
    strcpy_s(pData, iLen, szString);
    
    // If the hash table is to be kept built (default).
    if (m_bHash)
    {
        // Find or add the entry.
        pHash = m_Hash.Find(pData, true);
        if (!pHash)
            return (PostError(OutOfMemory()));

        // If the entry was new, keep the new string.
        if (pHash->iOffset == 0xffffffff)
        {
            *pnOffset = pHash->iOffset = GetNextOffset();
            SegAllocate(iLen);
            
            // Check for hash chains that are too long.
            if (m_Hash.MaxChainLength() > MAX_CHAIN_LENGTH)
            {
                IfFailRet(RehashStrings());
            }
        }
        // Else use the old one.
        else
        {
            *pnOffset = pHash->iOffset;
        }
    }
    // Probably an import which defers the hash table for speed.
    else
    {
        *pnOffset = GetNextOffset();
        SegAllocate(iLen);
    }
    return S_OK;
} // StgStringPool::AddString

//*****************************************************************************
// Add a string to the pool with Unicode to UTF8 conversion.
//*****************************************************************************
__checkReturn 
HRESULT 
StgStringPool::AddStringW(
    LPCWSTR szString,           // The string to add to pool.
    UINT32 *pnOffset)           // Return offset of string here.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    STRINGHASH  *pHash;                 // Hash item for add.
    ULONG       iLen;                   // Correct length after conversion.
    LPSTR       pData;                  // Pointer to location for new string.

    _ASSERTE(!m_bReadOnly);
    
    // Null pointer is an error.
    if (szString == 0)
        return (PostError(E_INVALIDARG));

    // Special case empty string.
    if (*szString == '\0')
    {
        *pnOffset = 0;
        return (S_OK);
    }

    // How many bytes will be required in the heap?
    iLen = ::WszWideCharToMultiByte(
        CP_UTF8, 
        0, 
        szString, 
        -1,     // null-terminated string
        NULL, 
        0, 
        NULL, 
        NULL);
    // WCTMB includes trailing 0 if (when passing parameter #4 (length) -1.
    
    // Check for room.
    if (iLen > GetCbSegAvailable())
    {
        if (!Grow(iLen))
            return (PostError(OutOfMemory()));
    }
    pData = reinterpret_cast<LPSTR>(GetNextLocation());

    // Convert the data in place to the correct location.
    iLen = ::WszWideCharToMultiByte(
        CP_UTF8, 
        0, 
        szString, 
        -1, 
        pData, 
        GetCbSegAvailable(), 
        NULL, 
        NULL);
    if (iLen == 0)
        return (BadError(HRESULT_FROM_NT(GetLastError())));
    
    // If the hash table is to be kept built (default).
    if (m_bHash)
    {
        // Find or add the entry.
        pHash = m_Hash.Find(pData, true);
        if (!pHash)
            return (PostError(OutOfMemory()));

        // If the entry was new, keep the new string.
        if (pHash->iOffset == 0xffffffff)
        {
            *pnOffset = pHash->iOffset = GetNextOffset();
            SegAllocate(iLen);
        }
        // Else use the old one.
        else
        {
            *pnOffset = pHash->iOffset;
        }
    }
    // Probably an import which defers the hash table for speed.
    else
    {
        *pnOffset = GetNextOffset();
        SegAllocate(iLen);
    }
    return (S_OK);
} // StgStringPool::AddStringW


//*****************************************************************************
// Clears out the existing hash table used to eliminate duplicates.  Then
// rebuilds the hash table from scratch based on the current data.
//*****************************************************************************
__checkReturn 
HRESULT 
StgStringPool::RehashStrings()
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    ULONG       iOffset;                // Loop control.
    ULONG       iMax;                   // End of loop.
    ULONG       iSeg;                   // Location within segment.
    StgPoolSeg  *pSeg = this;           // To loop over segments.
    STRINGHASH  *pHash;                 // Hash item for add.
    LPCSTR      pString;                // A string;
    ULONG       iLen;                   // The string's length.
    int         iBuckets;               // Buckets in the hash.
    int         iCount;                 // Items in the hash.
    int         iNewBuckets;            // New count of buckets in the hash.

    // Determine the new bucket size.
    iBuckets = m_Hash.Buckets();
    iCount = m_Hash.Count();
    iNewBuckets = max(iCount, iBuckets+iBuckets/2+1);
        
    // Remove any stale data.
    m_Hash.Clear();
    m_Hash.SetBuckets(iNewBuckets);

    // How far should the loop go.
    iMax = GetNextOffset();

    // Go through each string, skipping initial empty string.
    for (iSeg=iOffset=1;  iOffset < iMax;  )
    {
        // Get the string from the pool.
        pString = reinterpret_cast<LPCSTR>(pSeg->m_pSegData + iSeg);
        // Add the string to the hash table.
        if ((pHash = m_Hash.Add(pString)) == 0)
            return (PostError(OutOfMemory()));
        pHash->iOffset = iOffset;

        // Move to next string.
        iLen = (ULONG)(strlen(pString) + 1);
        iOffset += iLen;
        iSeg += iLen;
        if (iSeg >= pSeg->m_cbSegNext)
        {
            pSeg = pSeg->m_pNextSeg;
            iSeg = 0;
        }
    }
    return (S_OK);
} // StgStringPool::RehashStrings

//
//
// StgGuidPool
//
//

__checkReturn 
HRESULT 
StgGuidPool::InitNew(
    ULONG cbSize,       // Estimated size.
    ULONG cItems)       // Estimated item count.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    HRESULT     hr;                     // A result.

    if (FAILED(hr = StgPool::InitNew()))
        return (hr);

    // Set initial table sizes, if specified.
    if (cbSize)
        if (!Grow(cbSize))
            return E_OUTOFMEMORY;
    if (cItems)
        m_Hash.SetBuckets(cItems);

    return (S_OK);
} // StgGuidPool::InitNew

//*****************************************************************************
// Load a Guid heap from persisted memory.  If a copy of the data is made
// (so that it may be updated), then a new hash table is generated which can
// be used to elminate duplicates with new Guids.
//*****************************************************************************
__checkReturn 
HRESULT 
StgGuidPool::InitOnMem(
    void *pData,        // Predefined data.
    ULONG iSize,        // Size of data.
    int   bReadOnly)    // true if append is forbidden.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    HRESULT     hr;

    // Let base class init our memory structure.
    IfFailRet(StgPool::InitOnMem(pData, iSize, bReadOnly));
    
    // For init on existing mem case.
    if (pData && iSize)
    {
        // If we cannot update, then we don't need a hash table.
        if (bReadOnly)
            return S_OK;

        //<TODO>@todo: defer this until we hand out a pointer.</TODO>
        IfFailRet(TakeOwnershipOfInitMem());
        
        // Build the hash table on the data.
        if (FAILED(hr = RehashGuids()))
        {
            Uninit();
            return hr;
        }
    }
    
    return S_OK;
} // StgGuidPool::InitOnMem

//*****************************************************************************
// Clears the hash table then calls the base class.
//*****************************************************************************
void StgGuidPool::Uninit()
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
    }
    CONTRACTL_END

    // Clear the hash table.
    m_Hash.Clear();

    // Let base class clean up.
    StgPool::Uninit();
} // StgGuidPool::Uninit

//*****************************************************************************
// Add a segment to the chain of segments.
//*****************************************************************************
__checkReturn 
HRESULT 
StgGuidPool::AddSegment(
    const void *pData,      // The data.
    ULONG       cbData,     // Size of the data.
    bool        bCopy)      // If true, make a copy of the data.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    // Want an integeral number of GUIDs.
    _ASSERTE((cbData % sizeof(GUID)) == 0);

    return StgPool::AddSegment(pData, cbData, bCopy);

} // StgGuidPool::AddSegment

//*****************************************************************************
// Turn hashing off or on.  If you turn hashing on, then any existing data is
// thrown away and all data is rehashed during this call.
//*****************************************************************************
__checkReturn 
HRESULT 
StgGuidPool::SetHash(int bHash)
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    HRESULT     hr = S_OK;

    // If turning on hash again, need to rehash all guids.
    if (bHash)
        hr = RehashGuids();

    m_bHash = bHash;
    return (hr);
} // StgGuidPool::SetHash

//*****************************************************************************
// The Guid will be added to the pool.  The index of the Guid in the pool
// is returned in *piIndex.  If the Guid is already in the pool, then the
// index will be to the existing copy of the Guid.
//*****************************************************************************
__checkReturn 
HRESULT 
StgGuidPool::AddGuid(
    const GUID *pGuid,          // The Guid to add to pool.
    UINT32     *pnIndex)        // Return 1-based index of Guid here.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END
    
    GUIDHASH *pHash = NULL;                  // Hash item for add.
    
    GUID guid = *pGuid;
    SwapGuid(&guid);
    
    // Special case for GUID_NULL
    if (guid == GUID_NULL)
    {
        *pnIndex = 0;
        return S_OK;
    }
    
    // If the hash table is to be kept built (default).
    if (m_bHash)
    {
        // Find or add the entry.
        pHash = m_Hash.Find(&guid, true);
        if (!pHash)
            return (PostError(OutOfMemory()));
        
        // If the guid was found, just use it.
        if (pHash->iIndex != 0xffffffff)
        {   // Return 1-based index.
            *pnIndex = pHash->iIndex;
            return S_OK;
        }
    }
    
    // Space on heap for new guid?
    if (sizeof(GUID) > GetCbSegAvailable())
    {
        if (!Grow(sizeof(GUID)))
            return (PostError(OutOfMemory()));
    }
    
    // Copy the guid to the heap.
    *reinterpret_cast<GUID*>(GetNextLocation()) = guid;
    
    // Give the 1-based index back to caller.
    *pnIndex = (GetNextOffset() / sizeof(GUID)) + 1;

    // If hashing, save the 1-based index in the hash.
    if (m_bHash)
        pHash->iIndex = *pnIndex;
    
    // Update heap counters.
    SegAllocate(sizeof(GUID));
    
    return S_OK;
} // StgGuidPool::AddGuid

//*****************************************************************************
// Recompute the hashes for the pool.
//*****************************************************************************
__checkReturn 
HRESULT 
StgGuidPool::RehashGuids()
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    ULONG       iOffset;                // Loop control.
    ULONG       iMax;                   // End of loop.
    ULONG       iSeg;                   // Location within segment.
    StgPoolSeg  *pSeg = this;           // To loop over segments.
    GUIDHASH    *pHash;                 // Hash item for add.
    GUID        *pGuid;                 // A guid;

    // Remove any stale data.
    m_Hash.Clear();

    // How far should the loop go.
    iMax = GetNextOffset();

    // Go through each guid.
    for (iSeg=iOffset=0;  iOffset < iMax;  )
    {
        // Get a pointer to the guid.
        pGuid = reinterpret_cast<GUID*>(pSeg->m_pSegData + iSeg);
        // Add the guid to the hash table.
        if ((pHash = m_Hash.Add(pGuid)) == 0)
            return (PostError(OutOfMemory()));
        pHash->iIndex = iOffset / sizeof(GUID);

        // Move to next Guid.
        iOffset += sizeof(GUID);
        iSeg += sizeof(GUID);
        if (iSeg > pSeg->m_cbSegNext)
        {
            pSeg = pSeg->m_pNextSeg;
            iSeg = 0;
        }
    }
    return (S_OK);
} // StgGuidPool::RehashGuids

//
//
// StgBlobPool
//
//



//*****************************************************************************
// Create a new, empty blob pool.
//*****************************************************************************
__checkReturn 
HRESULT 
StgBlobPool::InitNew(
    ULONG cbSize,           // Estimated size.
    ULONG cItems,           // Estimated item count.
    BOOL  fAddEmptryItem)   // Should we add an empty item at offset 0
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    HRESULT hr;
    
    // Let base class intialize.
    IfFailRet(StgPool::InitNew());
    
    // Set initial table sizes, if specified.
    if (cbSize > 0)
    {
        if (!Grow(cbSize))
            return E_OUTOFMEMORY;
    }
    if (cItems > 0)
        m_Hash.SetBuckets(cItems);
    
    // Init with empty blob.
    
    // Normally must do this, regardless if we currently have anything in the pool.
    // If we don't do this, the first blob that gets added to the pool will
    // have an offset of 0. This will cause this blob to have a token of
    // 0x70000000, which is considered a nil string token.
    //
    // By inserting a zero length blob into the pool the being with, we're
    // assured that the first blob added to the pool will have an offset
    // of 1 and a token of 0x70000001, which is a valid token.
    //
    // The only time we wouldn't want to do this is if we're reading in a delta metadata.
    // Then, we don't care if the first string is at offset 0... when the delta gets applied,
    // the string will get moved to the appropriate offset.
    if (fAddEmptryItem)
    {
        MetaData::DataBlob emptyBlob(NULL, 0);
        UINT32 nIndex_Ignore;
        IfFailRet(AddBlob(&emptyBlob, &nIndex_Ignore));
        // Empty blob better be at offset 0.
        _ASSERTE(nIndex_Ignore == 0);
    }
    return hr;
} // StgBlobPool::InitNew

//*****************************************************************************
// Init the blob pool for use.  This is called for both create and read case.
// If there is existing data and bCopyData is true, then the data is rehashed
// to eliminate dupes in future adds.
//*****************************************************************************
__checkReturn 
HRESULT 
StgBlobPool::InitOnMem(
    void *pBuf,             // Predefined data.
    ULONG iBufSize,         // Size of data.
    int   bReadOnly)        // true if append is forbidden.
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END
    
    HRESULT hr;
    
    // Let base class init our memory structure.
    IfFailRet(StgPool::InitOnMem(pBuf, iBufSize, bReadOnly));
    
    // Init hash table from existing data.
    // If we cannot update, we don't need a hash table.
    if (bReadOnly)
    {
        return S_OK;
    }
    
    //<TODO>@todo: defer this until we hand out a pointer.</TODO>
    IfFailRet(TakeOwnershipOfInitMem());
    
    UINT32 nMaxOffset = GetNextOffset();
    for (UINT32 nOffset = 0; nOffset < nMaxOffset; )
    {
        MetaData::DataBlob blob;
        BLOBHASH          *pHash;
        
        IfFailRet(GetBlobWithSizePrefix(nOffset, &blob));
        
        // Add the blob to the hash table.
        if ((pHash = m_Hash.Add(blob.GetDataPointer())) == NULL)
        {
            Uninit();
            return E_OUTOFMEMORY;
        }
        pHash->iOffset = nOffset;
        
        nOffset += blob.GetSize();
    }
    return S_OK;
} // StgBlobPool::InitOnMem

//*****************************************************************************
// Clears the hash table then calls the base class.
//*****************************************************************************
void StgBlobPool::Uninit()
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
    }
    CONTRACTL_END

    // Clear the hash table.
    m_Hash.Clear();

    // Let base class clean up.
    StgPool::Uninit();
} // StgBlobPool::Uninit


//*****************************************************************************
// The blob will be added to the pool.  The offset of the blob in the pool
// is returned in *piOffset.  If the blob is already in the pool, then the
// offset will be to the existing copy of the blob.
//*****************************************************************************
__checkReturn 
HRESULT 
StgBlobPool::AddBlob(
    const MetaData::DataBlob *pData, 
    UINT32                   *pnOffset)  // Return offset of blob here.
{
    BLOBHASH *pHash;            // Hash item for add.
    void     *pBytes;           // Working pointer.
    BYTE     *pStartLoc;        // Location to write real blob
    ULONG     iRequired;        // How much buffer for this blob?
    ULONG     iFillerLen;       // space to fill to make byte-aligned
    HRESULT   hr;
    
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    // Can we handle this blob?
    if (pData->GetSize() > CPackedLen::MAX_LEN)
        return (PostError(CLDB_E_TOO_BIG));

    // worst case is we need three more bytes to ensure byte-aligned, hence the 3
    iRequired = pData->GetSize() + CPackedLen::Size(pData->GetSize()) + 3;
    if (iRequired > GetCbSegAvailable())
    {
        if (!Grow(iRequired))
            return (PostError(OutOfMemory()));
    }
    
    // unless changed due to alignment, the location of the blob is just
    // the value returned by GetNextLocation(), which is also a iFillerLen of
    // 0
    
    pStartLoc = (BYTE *)GetNextLocation();
    iFillerLen = 0;
    
    // technichally, only the data portion must be DWORD-aligned.  So, if the
    // data length is zero, we don't need to worry about alignment.
    
    // Pack in the length at pStartLoc (the start location)
    pBytes = CPackedLen::PutLength(pStartLoc, pData->GetSize());
    
    // Put the bytes themselves.
    memcpy(pBytes, pData->GetDataPointer(), pData->GetSize());
    
    // Find or add the entry.
    if ((pHash = m_Hash.Find(GetNextLocation() + iFillerLen, true)) == NULL)
        return (PostError(OutOfMemory()));
    
    // If the entry was new, keep the new blob.
    if (pHash->iOffset == 0xffffffff)
    {
        // this blob's offset is increased by iFillerLen bytes
        pHash->iOffset = *pnOffset = GetNextOffset() + iFillerLen;
        // only SegAllocate what we actually used, rather than what we requested
        SegAllocate(pData->GetSize() + CPackedLen::Size(pData->GetSize()) + iFillerLen);
        
        // Check for hash chains that are too long.
        if (m_Hash.MaxChainLength() > MAX_CHAIN_LENGTH)
        {
            IfFailRet(RehashBlobs());
        }
    }
    // Else use the old one.
    else
    {
        *pnOffset = pHash->iOffset;
    }
    
    return S_OK;
} // StgBlobPool::AddBlob

//*****************************************************************************
// Return a pointer to a blob, and the size of the blob.
//*****************************************************************************
__checkReturn 
HRESULT 
StgBlobPool::GetBlob(
    UINT32              nOffset,    // Offset of blob in pool.
    MetaData::DataBlob *pData)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FORBID_FAULT;
    
    HRESULT hr;
    
    if (nOffset == 0)
    {
        // TODO: It would be nice to remove it, but people read behind the end of buffer, 
        // e.g. VBC reads 2 zeros even though the size is 0 when it's storing string in the blob.
        // Nice to have: Move this to the public API only as a compat layer.
        pData->Init((BYTE *)m_zeros, 0);
        return S_OK;
    }
    
    IfFailGo(StgPool::GetData(nOffset, pData));
    
    UINT32 cbBlobContentSize;
    if (!pData->GetCompressedU(&cbBlobContentSize))
    {
        IfFailGo(COR_E_BADIMAGEFORMAT);
    }
    if (!pData->TruncateToExactSize(cbBlobContentSize))
    {
        IfFailGo(COR_E_BADIMAGEFORMAT);
    }
    
    return S_OK;
ErrExit:
    pData->Clear();
    return hr;
} // StgBlobPool::GetBlob

//*****************************************************************************
// Return a pointer to a blob, and the size of the blob.
//*****************************************************************************
__checkReturn 
HRESULT 
StgBlobPool::GetBlobWithSizePrefix(
    UINT32              nOffset,    // Offset of blob in pool.
    MetaData::DataBlob *pData)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FORBID_FAULT;
    
    HRESULT hr;
    
    if (nOffset == 0)
    {
        // TODO: Should be a static empty blob once we get rid of m_zeros
        pData->Init((BYTE *)m_zeros, 1);
        return S_OK;
    }
    
    IfFailGo(StgPool::GetData(nOffset, pData));
    
    UINT32  cbBlobContentSize;
    UINT32  cbBlobSizePrefixSize;
    if (!pData->PeekCompressedU(&cbBlobContentSize, &cbBlobSizePrefixSize))
    {
        IfFailGo(COR_E_BADIMAGEFORMAT);
    }
    //_ASSERTE(cbBlobSizePrefixSize <= 4);
    //_ASSERTE(cbBlobContentSize <= CompressedInteger::const_Max);
    
    // Cannot overflow, because previous asserts hold (in comments)
    UINT32 cbBlobSize;
    cbBlobSize = cbBlobContentSize + cbBlobSizePrefixSize;
    if (!pData->TruncateToExactSize(cbBlobSize))
    {
        IfFailGo(COR_E_BADIMAGEFORMAT);
    }
    
    return S_OK;
ErrExit:
    pData->Clear();
    return hr;
} // StgBlobPool::GetBlob

//*****************************************************************************
// Turn hashing off or on.  If you turn hashing on, then any existing data is
// thrown away and all data is rehashed during this call.
//*****************************************************************************
__checkReturn 
HRESULT 
StgBlobPool::SetHash(int bHash)
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    HRESULT     hr = S_OK;

    // If turning on hash again, need to rehash all Blobs.
    if (bHash)
        hr = RehashBlobs();

    //<TODO>@todo: m_bHash = bHash;</TODO>
    return (hr);
} // StgBlobPool::SetHash

//*****************************************************************************
// Clears out the existing hash table used to eliminate duplicates.  Then
// rebuilds the hash table from scratch based on the current data.
//*****************************************************************************
__checkReturn 
HRESULT 
StgBlobPool::RehashBlobs()
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    void const  *pBlob;                 // Pointer to a given blob.
    ULONG       cbBlob;                 // Length of a blob.
    int         iSizeLen = 0;           // Size of an encoded length.
    ULONG       iOffset;                // Location within iteration.
    ULONG       iMax;                   // End of loop.
    ULONG       iSeg;                   // Location within segment.
    StgPoolSeg  *pSeg = this;           // To loop over segments.
    BLOBHASH    *pHash;                 // Hash item for add.
    int         iBuckets;               // Buckets in the hash.
    int         iCount;                 // Items in the hash.
    int         iNewBuckets;            // New count of buckets in the hash.

    // Determine the new bucket size.
    iBuckets = m_Hash.Buckets();
    iCount = m_Hash.Count();
    iNewBuckets = max(iCount, iBuckets+iBuckets/2+1);
        
    // Remove any stale data.
    m_Hash.Clear();
    m_Hash.SetBuckets(iNewBuckets);
    
    // How far should the loop go.
    iMax = GetNextOffset();

    // Go through each string, skipping initial empty string.
    for (iSeg=iOffset=0; iOffset < iMax; )
    {
        // Get the string from the pool.
        pBlob = pSeg->m_pSegData + iSeg;
        
        cbBlob = CPackedLen::GetLength(pBlob, &iSizeLen);
        if (cbBlob == (ULONG)-1)
        {   // Invalid blob size encoding
            
            //#GarbageInBlobHeap
            // Note that this is allowed in ECMA spec (see chapter "#US and #Blob heaps"):
            //     Both these heaps can contain garbage, as long as any part that is reachable from any of 
            //     the tables contains a valid 'blob'.
            
            // The hash is incomplete, which means that we might emit duplicate blob entries ... that is fine
            return S_OK;
        }
        //_ASSERTE((iSizeLen >= 1) && (iSizeLen <= 4) && (cbBlob <= 0x1fffffff));
        
        // Make it blob size incl. its size encoding (cannot integer overflow)
        cbBlob += iSizeLen;
        // Check for integer overflow and that the entire blob entry is in this segment
        if ((iSeg > (iSeg + cbBlob)) || ((iSeg + cbBlob) > pSeg->m_cbSegNext))
        {   // Invalid blob size
            
            // See code:#GarbageInBlobHeap
            // The hash is incomplete, which means that we might emit duplicate blob entries ... that is fine
            return S_OK;
        }
        
        // Add the blob to the hash table.
        if ((pHash = m_Hash.Add(pBlob)) == 0)
        {
            Uninit();
            return (E_OUTOFMEMORY);
        }
        pHash->iOffset = iOffset;

        // Move to next blob.
        iOffset += cbBlob;
        iSeg += cbBlob;
        if (iSeg >= pSeg->m_cbSegNext)
        {
            pSeg = pSeg->m_pNextSeg;
            iSeg = 0;
        }
    }
    return (S_OK);
} // StgBlobPool::RehashBlobs


//
// CInMemoryStream
//


ULONG 
STDMETHODCALLTYPE CInMemoryStream::Release()
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
        SUPPORTS_DAC_HOST_ONLY;
    }
    CONTRACTL_END

    ULONG       cRef = InterlockedDecrement(&m_cRef);
    if (cRef == 0)
    {
        if (m_dataCopy != NULL)
            delete [] m_dataCopy;
        
        delete this;
    }
    return (cRef);
} // CInMemoryStream::Release

HRESULT 
STDMETHODCALLTYPE 
CInMemoryStream::QueryInterface(REFIID riid, PVOID *ppOut)
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    if (!ppOut)
    {
        return E_POINTER;
    }

    *ppOut = NULL;
    if (riid == IID_IStream || riid == IID_ISequentialStream || riid == IID_IUnknown)
    {
        *ppOut = this;
        AddRef();
        return (S_OK);
    }

    return E_NOINTERFACE;

} // CInMemoryStream::QueryInterface

HRESULT 
STDMETHODCALLTYPE 
CInMemoryStream::Read(
    void  *pv,
    ULONG  cb,
    ULONG *pcbRead)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY;

    ULONG       cbRead = min(cb, m_cbSize - m_cbCurrent);

    if (cbRead == 0)
        return (S_FALSE);
    memcpy(pv, (void *) ((ULONG_PTR) m_pMem + m_cbCurrent), cbRead);
    if (pcbRead)
        *pcbRead = cbRead;
    m_cbCurrent += cbRead;
    return (S_OK);
} // CInMemoryStream::Read

HRESULT 
STDMETHODCALLTYPE 
CInMemoryStream::Write(
    const void *pv,
    ULONG       cb,
    ULONG      *pcbWritten)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY;

    if (ovadd_gt(m_cbCurrent, cb, m_cbSize))
        return (OutOfMemory());

    memcpy((BYTE *) m_pMem + m_cbCurrent, pv, cb);
    m_cbCurrent += cb;
    if (pcbWritten) *pcbWritten = cb;
    return (S_OK);
} // CInMemoryStream::Write

HRESULT 
STDMETHODCALLTYPE 
CInMemoryStream::Seek(
    LARGE_INTEGER   dlibMove,
    DWORD           dwOrigin,
    ULARGE_INTEGER *plibNewPosition)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY;

    _ASSERTE(dwOrigin == STREAM_SEEK_SET || dwOrigin == STREAM_SEEK_CUR);
    _ASSERTE(dlibMove.QuadPart <= static_cast<LONGLONG>(ULONG_MAX));

    if (dwOrigin == STREAM_SEEK_SET)
    {
        m_cbCurrent = (ULONG) dlibMove.QuadPart;
    }
    else
    if (dwOrigin == STREAM_SEEK_CUR)
    {
        m_cbCurrent+= (ULONG)dlibMove.QuadPart;
    }

    if (plibNewPosition)
    {
            plibNewPosition->QuadPart = m_cbCurrent;
    }

    return (m_cbCurrent < m_cbSize) ? (S_OK) : E_FAIL;
} // CInMemoryStream::Seek

HRESULT 
STDMETHODCALLTYPE 
CInMemoryStream::CopyTo(
    IStream        *pstm, 
    ULARGE_INTEGER  cb, 
    ULARGE_INTEGER *pcbRead, 
    ULARGE_INTEGER *pcbWritten)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY;

    HRESULT     hr;
    // We don't handle pcbRead or pcbWritten.
    _ASSERTE(pcbRead == 0);
    _ASSERTE(pcbWritten == 0);

    _ASSERTE(cb.QuadPart <= ULONG_MAX);
    ULONG       cbTotal = min(static_cast<ULONG>(cb.QuadPart), m_cbSize - m_cbCurrent);
    ULONG       cbRead=min(1024, cbTotal);
    CQuickBytes rBuf;
    void        *pBuf = rBuf.AllocNoThrow(cbRead);
    if (pBuf == 0)
        return (PostError(OutOfMemory()));

    while (cbTotal)
        {
            if (cbRead > cbTotal)
                cbRead = cbTotal;
            if (FAILED(hr=Read(pBuf, cbRead, 0)))
                return (hr);
            if (FAILED(hr=pstm->Write(pBuf, cbRead, 0)))
                return (hr);
            cbTotal -= cbRead;
        }

    // Adjust seek pointer to the end.
    m_cbCurrent = m_cbSize;

    return (S_OK);
} // CInMemoryStream::CopyTo

HRESULT 
CInMemoryStream::CreateStreamOnMemory(
    void     *pMem,                     // Memory to create stream on.
    ULONG     cbSize,                   // Size of data.
    IStream **ppIStream,                // Return stream object here.
    BOOL      fDeleteMemoryOnRelease)
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    CInMemoryStream *pIStream;          // New stream object.
    if ((pIStream = new (nothrow) CInMemoryStream) == 0)
        return (PostError(OutOfMemory()));
    pIStream->InitNew(pMem, cbSize);
    if (fDeleteMemoryOnRelease)
    {
        // make sure this memory is allocated using new
        pIStream->m_dataCopy = (BYTE *)pMem;
    }
    *ppIStream = pIStream;
    return (S_OK);
} // CInMemoryStream::CreateStreamOnMemory

HRESULT 
CInMemoryStream::CreateStreamOnMemoryCopy(
    void     *pMem, 
    ULONG     cbSize, 
    IStream **ppIStream)
{
    CONTRACTL
    {
        NOTHROW;
        INJECT_FAULT(return E_OUTOFMEMORY;);
    }
    CONTRACTL_END

    CInMemoryStream *pIStream;          // New stream object.
    if ((pIStream = new (nothrow) CInMemoryStream) == 0)
        return (PostError(OutOfMemory()));

    // Init the stream.
    pIStream->m_cbCurrent = 0;
    pIStream->m_cbSize = cbSize;

    // Copy the data.
    pIStream->m_dataCopy = new (nothrow) BYTE[cbSize];

    if (pIStream->m_dataCopy == NULL)
    {
        delete pIStream;
        return (PostError(OutOfMemory()));
    }
    
    pIStream->m_pMem = pIStream->m_dataCopy;
    memcpy(pIStream->m_dataCopy, pMem, cbSize);

    *ppIStream = pIStream;
    return (S_OK);
} // CInMemoryStream::CreateStreamOnMemoryCopy

//---------------------------------------------------------------------------
// CGrowableStream is a simple IStream implementation that grows as
// its written to. All the memory is contigious, so read access is
// fast. A grow does a realloc, so be aware of that if you're going to
// use this.
//---------------------------------------------------------------------------

//Constructs a new GrowableStream
// multiplicativeGrowthRate - when the stream grows it will be at least this
//   multiple of its old size. Values greater than 1 ensure O(N) amortized
//   performance growing the stream to size N, 1 ensures O(N^2) amortized perf
//   but gives the tightest memory usage. Valid range is [1.0, 2.0].
// additiveGrowthRate - when the stream grows it will increase in size by at least
//   this number of bytes. Larger numbers cause fewer re-allocations at the cost of
//   increased memory usage.
CGrowableStream::CGrowableStream(float multiplicativeGrowthRate, DWORD additiveGrowthRate)
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
    }
    CONTRACTL_END

    m_swBuffer = NULL;
    m_dwBufferSize = 0;
    m_dwBufferIndex = 0;
    m_dwStreamLength = 0;
    m_cRef = 1;

    // Lets make sure these values stay somewhat sane... if you adjust the limits
    // make sure you also write correct overflow checking code in EnsureCapcity
    _ASSERTE(multiplicativeGrowthRate >= 1.0F && multiplicativeGrowthRate <= 2.0F);
    m_multiplicativeGrowthRate = min(max(1.0F, multiplicativeGrowthRate), 2.0F);

    _ASSERTE(additiveGrowthRate >= 1);
    m_additiveGrowthRate = max(1, additiveGrowthRate);
} // CGrowableStream::CGrowableStream

#ifndef DACCESS_COMPILE

CGrowableStream::~CGrowableStream() 
{
    CONTRACTL
    {
        NOTHROW;
        FORBID_FAULT;
    }
    CONTRACTL_END

    // Destroy the buffer.
    if (m_swBuffer != NULL)
        delete [] m_swBuffer;

    m_swBuffer = NULL;
    m_dwBufferSize = 0;
} // CGrowableStream::~CGrowableStream

// Grows the stream and optionally the internal buffer to ensure it is at least
// newLogicalSize
HRESULT CGrowableStream::EnsureCapacity(DWORD newLogicalSize)
{
    _ASSERTE(m_dwBufferSize >= m_dwStreamLength);

    // If there is no enough space left in the buffer, grow it
    if (newLogicalSize > m_dwBufferSize)
    {
        // Grow to max of newLogicalSize, m_dwBufferSize*multiplicativeGrowthRate, and
        // m_dwBufferSize+m_additiveGrowthRate
        S_UINT32 addSize = S_UINT32(m_dwBufferSize) + S_UINT32(m_additiveGrowthRate);
        if (addSize.IsOverflow())
        {
            addSize = S_UINT32(UINT_MAX);
        }

        // this should have been enforced in the constructor too
        _ASSERTE(m_multiplicativeGrowthRate <= 2.0 && m_multiplicativeGrowthRate >= 1.0);

        // 2*UINT_MAX doesn't overflow a float so this certain to be safe
        float multSizeF = (float)m_dwBufferSize * m_multiplicativeGrowthRate;
        DWORD multSize;
        if(multSizeF > (float)UINT_MAX)
        {
            multSize = UINT_MAX;
        }
        else
        {
            multSize = (DWORD)multSizeF;
        }
        
        DWORD newBufferSize = max(max(newLogicalSize, multSize), addSize.Value());

        char *tmp = new (nothrow) char[newBufferSize];
        if(tmp == NULL)
        {
            return E_OUTOFMEMORY;
        }
        
        if (m_swBuffer) {
            memcpy (tmp, m_swBuffer, m_dwBufferSize);
            delete [] m_swBuffer;
        }
        m_swBuffer = (BYTE *)tmp;
        m_dwBufferSize = newBufferSize;
    }

    _ASSERTE(m_dwBufferSize >= newLogicalSize);
    // the internal buffer is big enough, might have to increase logical size
    // though
    if(newLogicalSize > m_dwStreamLength)
    {
        m_dwStreamLength = newLogicalSize;
    }

    _ASSERTE(m_dwBufferSize >= m_dwStreamLength);
    return S_OK;
}

ULONG 
STDMETHODCALLTYPE 
CGrowableStream::Release()
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FORBID_FAULT;
    
    ULONG cRef = InterlockedDecrement(&m_cRef);
    
    if (cRef == 0)
        delete this;
    
    return cRef;
} // CGrowableStream::Release

HRESULT 
STDMETHODCALLTYPE 
CGrowableStream::QueryInterface(
    REFIID riid, 
    PVOID *ppOut)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY

    if (riid != IID_IUnknown && riid!=IID_ISequentialStream && riid!=IID_IStream)
        return E_NOINTERFACE;

    *ppOut = this;
    AddRef();
    return (S_OK);
} // CGrowableStream::QueryInterface

HRESULT 
CGrowableStream::Read(
    void  *pv, 
    ULONG  cb, 
    ULONG *pcbRead)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY

    HRESULT hr = S_OK;
    DWORD dwCanReadBytes = 0;

    if (NULL == pv)
        return E_POINTER;

    // short-circuit a zero-length read or see if we are at the end
    if (cb == 0 || m_dwBufferIndex >= m_dwStreamLength)
    {
        if (pcbRead != NULL)
            *pcbRead = 0;

        return S_OK;
    }

    // Figure out if we have enough room in the stream (excluding any
    // unused space at the end of the buffer)
    dwCanReadBytes = cb;

    S_UINT32 dwNewIndex = S_UINT32(dwCanReadBytes) + S_UINT32(m_dwBufferIndex);
    if (dwNewIndex.IsOverflow() || (dwNewIndex.Value() > m_dwStreamLength))
    {
        // Only read whatever is left in the buffer (if any)
        dwCanReadBytes = (m_dwStreamLength - m_dwBufferIndex);
    }

    // copy from our buffer to caller's buffer
    memcpy(pv, &m_swBuffer[m_dwBufferIndex], dwCanReadBytes);

    // adjust our current position
    m_dwBufferIndex += dwCanReadBytes;

    // if they want the info, tell them how many byte we read for them
    if (pcbRead != NULL)
        *pcbRead = dwCanReadBytes;

    return hr;
} // CGrowableStream::Read

HRESULT 
CGrowableStream::Write(
    const void *pv, 
    ULONG       cb, 
    ULONG      *pcbWritten)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY

    HRESULT hr = S_OK;
    DWORD dwActualWrite = 0;

    // avoid NULL write
    if (cb == 0)
    {
        hr = S_OK;
        goto Error;
    }

    // Check if our buffer is large enough
    _ASSERTE(m_dwBufferIndex <= m_dwStreamLength);
    _ASSERTE(m_dwStreamLength <= m_dwBufferSize);
    
    // If there is no enough space left in the buffer, grow it
    if (cb > (m_dwStreamLength - m_dwBufferIndex))
    {
        // Determine the new size needed
        S_UINT32 size = S_UINT32(m_dwBufferSize) + S_UINT32(cb);
        if (size.IsOverflow())
        {
            hr = HRESULT_FROM_WIN32(ERROR_ARITHMETIC_OVERFLOW);
            goto Error;
        }

        hr = EnsureCapacity(size.Value());
        if(FAILED(hr))
        {
            goto Error;
        }
    }
    
    if ((pv != NULL) && (cb > 0))
    {
        // write to current position in the buffer
        memcpy(&m_swBuffer[m_dwBufferIndex], pv, cb);

        // now update our current index
        m_dwBufferIndex += cb;

        // in case they want to know the number of bytes written
        dwActualWrite = cb;
    }

Error:
    if (pcbWritten)
        *pcbWritten = dwActualWrite;

    return hr;
} // CGrowableStream::Write

STDMETHODIMP 
CGrowableStream::Seek(
    LARGE_INTEGER   dlibMove, 
    DWORD           dwOrigin, 
    ULARGE_INTEGER *plibNewPosition)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY

    // a Seek() call on STREAM_SEEK_CUR and a dlibMove == 0 is a
    // request to get the current seek position.
    if ((dwOrigin == STREAM_SEEK_CUR && dlibMove.u.LowPart == 0) &&
        (dlibMove.u.HighPart == 0) &&
        (NULL != plibNewPosition))
    {
        goto Error;
    }

    // we only support STREAM_SEEK_SET (beginning of buffer)
    if (dwOrigin != STREAM_SEEK_SET)
        return E_NOTIMPL;

    // did they ask to seek past end of stream?  If so we're supposed to
    // extend with zeros.  But we've never supported that.
    if (dlibMove.u.LowPart > m_dwStreamLength)
        return E_UNEXPECTED;

    // we ignore the high part of the large integer
    SIMPLIFYING_ASSUMPTION(dlibMove.u.HighPart == 0);
    m_dwBufferIndex = dlibMove.u.LowPart;

Error:
    if (NULL != plibNewPosition)
    {
        plibNewPosition->u.HighPart = 0;
        plibNewPosition->u.LowPart = m_dwBufferIndex;
    }

    return S_OK;
} // CGrowableStream::Seek

STDMETHODIMP 
CGrowableStream::SetSize(
    ULARGE_INTEGER libNewSize)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY

    DWORD dwNewSize = libNewSize.u.LowPart;

    _ASSERTE(libNewSize.u.HighPart == 0);

    // we don't support large allocations
    if (libNewSize.u.HighPart > 0)
        return E_OUTOFMEMORY;

    HRESULT hr = EnsureCapacity(dwNewSize);
    if(FAILED(hr))
    {
        return hr;
    }

    // EnsureCapacity doesn't shrink the logicalSize if dwNewSize is smaller
    // and SetSize is allowed to shrink the stream too. Note that we won't
    // release physical memory here, we just appear to get smaller
    m_dwStreamLength = dwNewSize;
        
    return S_OK;
} // CGrowableStream::SetSize

STDMETHODIMP 
CGrowableStream::Stat(
    STATSTG *pstatstg, 
    DWORD    grfStatFlag)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY

    if (NULL == pstatstg)
        return E_POINTER;

    // this is the only useful information we hand out - the length of the stream
    pstatstg->cbSize.u.HighPart = 0;
    pstatstg->cbSize.u.LowPart = m_dwStreamLength;
    pstatstg->type = STGTY_STREAM;

    // we ignore the grfStatFlag - we always assume STATFLAG_NONAME
    pstatstg->pwcsName = NULL;

    pstatstg->grfMode = 0;
    pstatstg->grfLocksSupported = 0;
    pstatstg->clsid = CLSID_NULL;
    pstatstg->grfStateBits = 0;

    return S_OK;
} // CGrowableStream::Stat

// 
// Clone - Make a deep copy of the stream into a new cGrowableStream instance
// 
// Arguments:
//   ppStream - required output parameter for the new stream instance
// 
// Returns:
//   S_OK on succeess, or an error code on failure.
// 
HRESULT 
CGrowableStream::Clone(
    IStream **ppStream)
{
    STATIC_CONTRACT_NOTHROW;
    STATIC_CONTRACT_FAULT; //E_OUTOFMEMORY

    if (NULL == ppStream)
        return E_POINTER;

    // Copy our entire buffer into the new stream
    CGrowableStream * newStream = new (nothrow) CGrowableStream();
    if (newStream == NULL)
    {
        return E_OUTOFMEMORY;
    }
    
    HRESULT hr = newStream->Write(m_swBuffer, m_dwStreamLength, NULL);
    if (FAILED(hr))
    {
        delete newStream;
        return hr;
    }

    *ppStream = newStream;
    return S_OK;
} // CGrowableStream::Clone

#endif // !DACCESS_COMPILE