summaryrefslogtreecommitdiffstats
path: root/private/ntos/rtl/lznt1.c
blob: 9403d387d5cf6fa28cbf0d73a8ebf29f32a4718a (plain) (blame)
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
/*++

Copyright (c) 1989  Microsoft Corporation

Module Name:

    LZNT1.c

Abstract:

    This module implements the LZNT1 compression engine.

Author:

    Gary Kimura     [GaryKi]    21-Jan-1994

Revision History:

--*/

#include "ntrtlp.h"

#include <stdio.h>


//
//  Declare the internal workspace that we need
//

typedef struct _LZNT1_STANDARD_WORKSPACE {

    PUCHAR UncompressedBuffer;
    PUCHAR EndOfUncompressedBufferPlus1;
    ULONG  MaxLength;
    PUCHAR MatchedString;

    PUCHAR IndexPTable[4096][2];

} LZNT1_STANDARD_WORKSPACE, *PLZNT1_STANDARD_WORKSPACE;

typedef struct _LZNT1_MAXIMUM_WORKSPACE {

    PUCHAR UncompressedBuffer;
    PUCHAR EndOfUncompressedBufferPlus1;
    ULONG  MaxLength;
    PUCHAR MatchedString;

} LZNT1_MAXIMUM_WORKSPACE, *PLZNT1_MAXIMUM_WORKSPACE;

typedef struct _LZNT1_FRAGMENT_WORKSPACE {

    UCHAR Buffer[0x1000];

} LZNT1_FRAGMENT_WORKSPACE, *PLZNT1_FRAGMENT_WORKSPACE;

//
//  Now define the local procedure prototypes.
//

typedef ULONG (*PLZNT1_MATCH_FUNCTION) (
    );

NTSTATUS
LZNT1CompressChunk (
    IN PLZNT1_MATCH_FUNCTION MatchFunction,
    IN PUCHAR UncompressedBuffer,
    IN PUCHAR EndOfUncompressedBufferPlus1,
    OUT PUCHAR CompressedBuffer,
    IN PUCHAR EndOfCompressedBufferPlus1,
    OUT PULONG FinalCompressedChunkSize,
    IN PVOID WorkSpace
    );

NTSTATUS
LZNT1DecompressChunk (
    OUT PUCHAR UncompressedBuffer,
    IN PUCHAR EndOfUncompressedBufferPlus1,
    IN PUCHAR CompressedBuffer,
    IN PUCHAR EndOfCompressedBufferPlus1,
    OUT PULONG FinalUncompressedChunkSize
    );

ULONG
LZNT1FindMatchStandard (
    IN PUCHAR ZivString,
    IN PLZNT1_STANDARD_WORKSPACE WorkSpace
    );

ULONG
LZNT1FindMatchMaximum (
    IN PUCHAR ZivString,
    IN PVOID WorkSpace
    );


//
//  Local data structures
//

//
//  The compressed chunk header is the structure that starts every
//  new chunk in the compressed data stream.  In our definition here
//  we union it with a ushort to make setting and retrieving the chunk
//  header easier.  The header stores the size of the compressed chunk,
//  its signature, and if the data stored in the chunk is compressed or
//  not.
//
//  Compressed Chunk Size:
//
//      The actual size of a compressed chunk ranges from 4 bytes (2 byte
//      header, 1 flag byte, and 1 literal byte) to 4098 bytes (2 byte
//      header, and 4096 bytes of uncompressed data).  The size is encoded
//      in a 12 bit field biased by 3.  A value of 1 corresponds to a chunk
//      size of 4, 2 => 5, ..., 4095 => 4098.  A value of zero is special
//      because it denotes the ending chunk header.
//
//  Chunk Signature:
//
//      The only valid signature value is 3.  This denotes a 4KB uncompressed
//      chunk using with the 4/12 to 12/4 sliding offset/length encoding.
//
//  Is Chunk Compressed:
//
//      If the data in the chunk is compressed this field is 1 otherwise
//      the data is uncompressed and this field is 0.
//
//  The ending chunk header in a compressed buffer contains the a value of
//  zero (space permitting).
//

typedef union _COMPRESSED_CHUNK_HEADER {

    struct {

        USHORT CompressedChunkSizeMinus3 : 12;
        USHORT ChunkSignature            :  3;
        USHORT IsChunkCompressed         :  1;

    } Chunk;

    USHORT Short;

} COMPRESSED_CHUNK_HEADER, *PCOMPRESSED_CHUNK_HEADER;

#define MAX_UNCOMPRESSED_CHUNK_SIZE (4096)

//
//  USHORT
//  GetCompressedChunkSize (
//      IN COMPRESSED_CHUNK_HEADER ChunkHeader
//      );
//
//  USHORT
//  GetUncompressedChunkSize (
//      IN COMPRESSED_CHUNK_HEADER ChunkHeader
//      );
//
//  VOID
//  SetCompressedChunkHeader (
//      IN OUT COMPRESSED_CHUNK_HEADER ChunkHeader,
//      IN USHORT CompressedChunkSize,
//      IN BOOLEAN IsChunkCompressed
//      );
//

#define GetCompressedChunkSize(CH)   (       \
    (CH).Chunk.CompressedChunkSizeMinus3 + 3 \
)

#define GetUncompressedChunkSize(CH) (MAX_UNCOMPRESSED_CHUNK_SIZE)

#define SetCompressedChunkHeader(CH,CCS,ICC) {        \
    ASSERT((CCS) >= 4 && (CCS) <= 4098);              \
    (CH).Chunk.CompressedChunkSizeMinus3 = (CCS) - 3; \
    (CH).Chunk.ChunkSignature = 3;                    \
    (CH).Chunk.IsChunkCompressed = (ICC);             \
}


//
//  Local macros
//

#define FlagOn(F,SF)    ((F) & (SF))
#define SetFlag(F,SF)   { (F) |= (SF); }
#define ClearFlag(F,SF) { (F) &= ~(SF); }

#define Minimum(A,B)    ((A) < (B) ? (A) : (B))
#define Maximum(A,B)    ((A) > (B) ? (A) : (B))

#if defined(ALLOC_PRAGMA) && defined(NTOS_KERNEL_RUNTIME)

#pragma alloc_text(PAGE, RtlCompressWorkSpaceSizeLZNT1)
#pragma alloc_text(PAGE, RtlCompressBufferLZNT1)
#pragma alloc_text(PAGE, RtlDecompressBufferLZNT1)
#pragma alloc_text(PAGE, RtlDecompressFragmentLZNT1)
#pragma alloc_text(PAGE, RtlDescribeChunkLZNT1)
#pragma alloc_text(PAGE, RtlReserveChunkLZNT1)

#pragma alloc_text(PAGE, LZNT1CompressChunk)

#if !defined(_ALPHA_)
#if !defined(_MIPS_)
#if !defined(_PPC_)
#if !defined(i386)
#pragma alloc_text(PAGE, LZNT1DecompressChunk)
#endif
#endif
#endif
#endif

#pragma alloc_text(PAGE, LZNT1FindMatchStandard)
#pragma alloc_text(PAGE, LZNT1FindMatchMaximum)

#endif


NTSTATUS
RtlCompressWorkSpaceSizeLZNT1 (
    IN USHORT Engine,
    OUT PULONG CompressBufferWorkSpaceSize,
    OUT PULONG CompressFragmentWorkSpaceSize
    )

/*++

Routine Description:

Arguments:

Return Value:

--*/

{
    if (Engine == COMPRESSION_ENGINE_STANDARD) {

        *CompressBufferWorkSpaceSize = sizeof(LZNT1_STANDARD_WORKSPACE);
        *CompressFragmentWorkSpaceSize = sizeof(LZNT1_FRAGMENT_WORKSPACE);

        return STATUS_SUCCESS;

    } else if (Engine == COMPRESSION_ENGINE_MAXIMUM) {

        *CompressBufferWorkSpaceSize = sizeof(LZNT1_MAXIMUM_WORKSPACE);
        *CompressFragmentWorkSpaceSize = sizeof(LZNT1_FRAGMENT_WORKSPACE);

        return STATUS_SUCCESS;

    } else {

        return STATUS_NOT_SUPPORTED;
    }
}


NTSTATUS
RtlCompressBufferLZNT1 (
    IN USHORT Engine,
    IN PUCHAR UncompressedBuffer,
    IN ULONG UncompressedBufferSize,
    OUT PUCHAR CompressedBuffer,
    IN ULONG CompressedBufferSize,
    IN ULONG UncompressedChunkSize,
    OUT PULONG FinalCompressedSize,
    IN PVOID WorkSpace
    )

/*++

Routine Description:

    This routine takes as input an uncompressed buffer and produces
    its compressed equivalent provided the compressed data fits within
    the specified destination buffer.

    An output variable indicates the number of bytes used to store
    the compressed buffer.

Arguments:

    UncompressedBuffer - Supplies a pointer to the uncompressed data.

    UncompressedBufferSize - Supplies the size, in bytes, of the
        uncompressed buffer.

    CompressedBuffer - Supplies a pointer to where the compressed data
        is to be stored.

    CompressedBufferSize - Supplies the size, in bytes, of the
        compressed buffer.

    UncompressedChunkSize - Ignored.

    FinalCompressedSize - Receives the number of bytes needed in
        the compressed buffer to store the compressed data.

    WorkSpace - Mind your own business, just give it to me.

Return Value:

    STATUS_SUCCESS - the compression worked without a hitch.

    STATUS_BUFFER_ALL_ZEROS - the compression worked without a hitch and in
        addition the input buffer was all zeros.

    STATUS_BUFFER_TOO_SMALL - the compressed buffer is too small to hold the
        compressed data.

--*/

{
    NTSTATUS Status;

    PLZNT1_MATCH_FUNCTION MatchFunction;

    PUCHAR UncompressedChunk;
    PUCHAR CompressedChunk;
    LONG CompressedChunkSize;

    //
    //  The following variable is used to tell if we have processed an entire
    //  buffer of zeros and that we should return an alternate status value
    //

    BOOLEAN AllZero = TRUE;

    //
    //  The following variables are pointers to the byte following the
    //  end of each appropriate buffer.
    //

    PUCHAR EndOfUncompressedBuffer = UncompressedBuffer + UncompressedBufferSize;
    PUCHAR EndOfCompressedBuffer = CompressedBuffer + CompressedBufferSize;

    //
    //  Get the match function we are to be using
    //

    if (Engine == COMPRESSION_ENGINE_STANDARD) {

        MatchFunction = LZNT1FindMatchStandard;

    } else if (Engine == COMPRESSION_ENGINE_MAXIMUM) {

        MatchFunction = LZNT1FindMatchMaximum;

    } else {

        return STATUS_NOT_SUPPORTED;
    }

    //
    //  For each uncompressed chunk (even the odd sized ending buffer) we will
    //  try and compress the chunk
    //

    for (UncompressedChunk = UncompressedBuffer, CompressedChunk = CompressedBuffer;
         UncompressedChunk < EndOfUncompressedBuffer;
         UncompressedChunk += MAX_UNCOMPRESSED_CHUNK_SIZE, CompressedChunk += CompressedChunkSize) {

        ASSERT(EndOfUncompressedBuffer >= UncompressedChunk);
        ASSERT(EndOfCompressedBuffer >= CompressedChunk);

        //
        //  Call the appropriate engine to compress one chunk. and
        //  return an error if we got one.
        //

        if (!NT_SUCCESS(Status = LZNT1CompressChunk( MatchFunction,
                                                     UncompressedChunk,
                                                     EndOfUncompressedBuffer,
                                                     CompressedChunk,
                                                     EndOfCompressedBuffer,
                                                     &CompressedChunkSize,
                                                     WorkSpace ))) {

            return Status;
        }

        //
        //  See if we stay all zeros.  If not then all zeros will become
        //  false and stay that way no matter what we later compress
        //

        AllZero = AllZero && (Status == STATUS_BUFFER_ALL_ZEROS);
    }

    //
    //  If we are not within two bytes of the end of the compressed buffer then we
    //  need to zero out two more for the ending compressed header and update
    //  the compressed chunk pointer value.  Don't include these bytes in
    //  the count however, as that may force our caller to allocate an unneeded
    //  cluster, since on decompress we will terminate either on these two
    //  bytes of 0, or byte count.
    //

    if (CompressedChunk <= (EndOfCompressedBuffer - 2)) {

        *(CompressedChunk) = 0;
        *(CompressedChunk + 1) = 0;
    }

    //
    //  The final compressed size is the difference between the start of the
    //  compressed buffer and where the compressed chunk pointer was left
    //

    *FinalCompressedSize = CompressedChunk - CompressedBuffer;

    //
    //  Check if the input buffer was all zeros and return the alternate status
    //  if appropriate
    //

    if (AllZero) { return STATUS_BUFFER_ALL_ZEROS; }

    return STATUS_SUCCESS;
}


NTSTATUS
RtlDecompressBufferLZNT1 (
    OUT PUCHAR UncompressedBuffer,
    IN ULONG UncompressedBufferSize,
    IN PUCHAR CompressedBuffer,
    IN ULONG CompressedBufferSize,
    OUT PULONG FinalUncompressedSize
    )

/*++

Routine Description:

    This routine takes as input a compressed buffer and produces
    its uncompressed equivalent provided the uncompressed data fits
    within the specified destination buffer.

    An output variable indicates the number of bytes used to store the
    uncompressed data.

Arguments:

    UncompressedBuffer - Supplies a pointer to where the uncompressed
        data is to be stored.

    UncompressedBufferSize - Supplies the size, in bytes, of the
        uncompressed buffer.

    CompressedBuffer - Supplies a pointer to the compressed data.

    CompressedBufferSize - Supplies the size, in bytes, of the
        compressed buffer.

    FinalUncompressedSize - Receives the number of bytes needed in
        the uncompressed buffer to store the uncompressed data.

Return Value:

    STATUS_SUCCESS - the decompression worked without a hitch.

    STATUS_BAD_COMPRESSION_BUFFER - the input compressed buffer is
        ill-formed.

--*/

{
    NTSTATUS Status;

    PUCHAR CompressedChunk = CompressedBuffer;
    PUCHAR UncompressedChunk = UncompressedBuffer;

    COMPRESSED_CHUNK_HEADER ChunkHeader;
    LONG SavedChunkSize;

    LONG UncompressedChunkSize;
    LONG CompressedChunkSize;

    //
    //  The following to variables are pointers to the byte following the
    //  end of each appropriate buffer.  This saves us from doing the addition
    //  for each loop check
    //

    PUCHAR EndOfUncompressedBuffer = UncompressedBuffer + UncompressedBufferSize;
    PUCHAR EndOfCompressedBuffer = CompressedBuffer + CompressedBufferSize;

    //
    //  Make sure that the compressed buffer is at least four bytes long to
    //  start with, and then get the first chunk header and make sure it
    //  is not an ending chunk header.
    //

    ASSERT(CompressedChunk <= EndOfCompressedBuffer - 4);

    RtlRetrieveUshort( &ChunkHeader, CompressedChunk );

    ASSERT(ChunkHeader.Short != 0);

    //
    //  Now while there is space in the uncompressed buffer to store data
    //  we will loop through decompressing chunks
    //

    while (TRUE) {

        ASSERT(ChunkHeader.Chunk.ChunkSignature == 3);

        CompressedChunkSize = GetCompressedChunkSize(ChunkHeader);

        //
        //  Check that the chunk actually fits in the buffer supplied
        //  by the caller
        //

        if (CompressedChunk + CompressedChunkSize > EndOfCompressedBuffer) {

            ASSERTMSG("CompressedBuffer is too small", FALSE);

            *FinalUncompressedSize = (ULONG)CompressedChunk;

            return STATUS_BAD_COMPRESSION_BUFFER;
        }

        //
        //  First make sure the chunk contains compressed data
        //

        if (ChunkHeader.Chunk.IsChunkCompressed) {

            //
            //  Decompress a chunk and return if we get an error
            //

            if (!NT_SUCCESS(Status = LZNT1DecompressChunk( UncompressedChunk,
                                                           EndOfUncompressedBuffer,
                                                           CompressedChunk + sizeof(COMPRESSED_CHUNK_HEADER),
                                                           CompressedChunk + CompressedChunkSize,
                                                           &UncompressedChunkSize ))) {

                *FinalUncompressedSize = UncompressedChunkSize;

                return Status;
            }

        } else {

            //
            //  The chunk does not contain compressed data so we need to simply
            //  copy over the uncompressed data
            //

            UncompressedChunkSize = GetUncompressedChunkSize( ChunkHeader );

            //
            //  Make sure the data will fit into the output buffer
            //

            if (UncompressedChunk + UncompressedChunkSize > EndOfUncompressedBuffer) {

                UncompressedChunkSize = EndOfUncompressedBuffer - UncompressedChunk;
            }

            //
            //  Check that the compressed chunk has this many bytes to copy.
            //

            if (CompressedChunk + sizeof(COMPRESSED_CHUNK_HEADER) + UncompressedChunkSize > EndOfCompressedBuffer) {

                ASSERTMSG("CompressedBuffer is too small", FALSE);
                *FinalUncompressedSize = (ULONG)CompressedChunk;
                return STATUS_BAD_COMPRESSION_BUFFER;
            }

            RtlCopyMemory( UncompressedChunk,
                           CompressedChunk + sizeof(COMPRESSED_CHUNK_HEADER),
                           UncompressedChunkSize );
        }

        //
        //  Now update the compressed and uncompressed chunk pointers with
        //  the size of the compressed chunk and the number of bytes we
        //  decompressed into, and then make sure we didn't exceed our buffers
        //

        CompressedChunk += CompressedChunkSize;
        UncompressedChunk += UncompressedChunkSize;

        ASSERT( CompressedChunk <= EndOfCompressedBuffer );
        ASSERT( UncompressedChunk <= EndOfUncompressedBuffer );

        //
        //  Now if the uncompressed is full then we are done
        //

        if (UncompressedChunk == EndOfUncompressedBuffer) { break; }

        //
        //  Otherwise we need to get the next chunk header.  We first
        //  check if there is one, save the old chunk size for the
        //  chunk we just read in, get the new chunk, and then check
        //  if it is the ending chunk header
        //

        if (CompressedChunk > EndOfCompressedBuffer - 2) { break; }

        SavedChunkSize = GetUncompressedChunkSize(ChunkHeader);

        RtlRetrieveUshort( &ChunkHeader, CompressedChunk );
        if (ChunkHeader.Short == 0) { break; }

        //
        //  At this point we are not at the end of the uncompressed buffer
        //  and we have another chunk to process.  But before we go on we
        //  need to see if the last uncompressed chunk didn't fill the full
        //  uncompressed chunk size.
        //

        if (UncompressedChunkSize < SavedChunkSize) {

            LONG t1;
            PUCHAR t2;

            //
            //  Now we only need to zero out data if the really are going
            //  to process another chunk, to test for that we check if
            //  the zero will go beyond the end of the uncompressed buffer
            //

            if ((t2 = (UncompressedChunk +
                       (t1 = (SavedChunkSize -
                              UncompressedChunkSize)))) >= EndOfUncompressedBuffer) {

                break;
            }

            RtlZeroMemory( UncompressedChunk, t1);
            UncompressedChunk = t2;
        }
    }

    //
    //  If we got out of the loop with the compressed chunk pointer beyond the
    //  end of compressed buffer then the compression buffer is ill formed.
    //

    if (CompressedChunk > EndOfCompressedBuffer) {

        *FinalUncompressedSize = (ULONG)CompressedChunk;

        return STATUS_BAD_COMPRESSION_BUFFER;
    }

    //
    //  The final uncompressed size is the difference between the start of the
    //  uncompressed buffer and where the uncompressed chunk pointer was left
    //

    *FinalUncompressedSize = UncompressedChunk - UncompressedBuffer;

    //
    //  And return to our caller
    //

    return STATUS_SUCCESS;
}


NTSTATUS
RtlDecompressFragmentLZNT1 (
    OUT PUCHAR UncompressedFragment,
    IN ULONG UncompressedFragmentSize,
    IN PUCHAR CompressedBuffer,
    IN ULONG CompressedBufferSize,
    IN ULONG FragmentOffset,
    OUT PULONG FinalUncompressedSize,
    IN PLZNT1_FRAGMENT_WORKSPACE WorkSpace
    )

/*++

Routine Description:

    This routine takes as input a compressed buffer and extract an
    uncompressed fragment.

    Output bytes are copied to the fragment buffer until either the
    fragment buffer is full or the end of the uncompressed buffer is
    reached.

    An output variable indicates the number of bytes used to store the
    uncompressed fragment.

Arguments:

    UncompressedFragment - Supplies a pointer to where the uncompressed
        fragment is to be stored.

    UncompressedFragmentSize - Supplies the size, in bytes, of the
        uncompressed fragment buffer.

    CompressedBuffer - Supplies a pointer to the compressed data buffer.

    CompressedBufferSize - Supplies the size, in bytes, of the
        compressed buffer.

    FragmentOffset - Supplies the offset (zero based) where the uncompressed
        fragment is being extract from.  The offset is the position within
        the original uncompressed buffer.

    FinalUncompressedSize - Receives the number of bytes needed in
        the Uncompressed fragment buffer to store the data.

    WorkSpace - Stop looking.

Return Value:

    STATUS_SUCCESS - the operation worked without a hitch.

    STATUS_BAD_COMPRESSION_BUFFER - the input compressed buffer is
        ill-formed.

--*/

{
    NTSTATUS Status;

    PUCHAR CompressedChunk = CompressedBuffer;

    COMPRESSED_CHUNK_HEADER ChunkHeader;
    ULONG UncompressedChunkSize;
    ULONG CompressedChunkSize;

    PUCHAR EndOfUncompressedFragment = UncompressedFragment + UncompressedFragmentSize;
    PUCHAR EndOfCompressedBuffer = CompressedBuffer + CompressedBufferSize;
    PUCHAR CurrentUncompressedFragment;

    ULONG CopySize;

    ASSERT(UncompressedFragmentSize > 0);

    //
    //  Get the chunk header for the first chunk in the
    //  compressed buffer and extract the uncompressed and
    //  the compressed chunk sizes
    //

    ASSERT(CompressedChunk <= EndOfCompressedBuffer - 2);

    RtlRetrieveUshort( &ChunkHeader, CompressedChunk );

    ASSERT(ChunkHeader.Short != 0);
    ASSERT(ChunkHeader.Chunk.ChunkSignature == 3);

    UncompressedChunkSize = GetUncompressedChunkSize(ChunkHeader);
    CompressedChunkSize = GetCompressedChunkSize(ChunkHeader);

    //
    //  Now we want to skip over chunks that precede the fragment
    //  we're after.  To do that we'll loop until the fragment
    //  offset is within the current chunk.  If it is not within
    //  the current chunk then we'll skip to the next chunk and
    //  subtract the uncompressed chunk size from the fragment offset
    //

    while (FragmentOffset >= UncompressedChunkSize) {

        //
        //  Check that the chunk actually fits in the buffer supplied
        //  by the caller
        //

        if (CompressedChunk + CompressedChunkSize > EndOfCompressedBuffer) {

            ASSERTMSG("CompressedBuffer is too small", FALSE);

            *FinalUncompressedSize = (ULONG)CompressedChunk;

            return STATUS_BAD_COMPRESSION_BUFFER;
        }

        //
        //  Adjust the fragment offset and move the compressed
        //  chunk pointer to the next chunk
        //

        FragmentOffset -= UncompressedChunkSize;
        CompressedChunk += CompressedChunkSize;

        //
        //  Get the next chunk header and if it is not in use
        //  then the fragment that the user wants is beyond the
        //  compressed data so we'll return a zero sized fragment
        //

        if (CompressedChunk > EndOfCompressedBuffer - 2) {

            *FinalUncompressedSize = 0;
            return STATUS_SUCCESS;
        }

        RtlRetrieveUshort( &ChunkHeader, CompressedChunk );

        if (ChunkHeader.Short == 0) {

            *FinalUncompressedSize = 0;
            return STATUS_SUCCESS;
        }

        ASSERT(ChunkHeader.Chunk.ChunkSignature == 3);

        //
        //  Decode the chunk sizes for the new current chunk
        //

        UncompressedChunkSize = GetUncompressedChunkSize(ChunkHeader);
        CompressedChunkSize = GetCompressedChunkSize(ChunkHeader);
    }

    //
    //  At this point the current chunk contains the starting point
    //  for the fragment.  Now we'll loop extracting data until
    //  we've filled up the uncompressed fragment buffer or until
    //  we've run out of chunks.  Both test are done near the end of
    //  the loop
    //

    CurrentUncompressedFragment = UncompressedFragment;

    while (TRUE) {

        //
        //  Check that the chunk actually fits in the buffer supplied
        //  by the caller
        //

        if (CompressedChunk + CompressedChunkSize > EndOfCompressedBuffer) {

            ASSERTMSG("CompressedBuffer is too small", FALSE);

            *FinalUncompressedSize = (ULONG)CompressedChunk;

            return STATUS_BAD_COMPRESSION_BUFFER;
        }


        //
        //  Now we need to compute the amount of data to copy from the
        //  chunk.  It will be based on either to the end of the chunk
        //  size or the amount of data the user specified
        //

        CopySize = Minimum( UncompressedChunkSize - FragmentOffset, UncompressedFragmentSize );

        //
        //  Now check if the chunk contains compressed data
        //

        if (ChunkHeader.Chunk.IsChunkCompressed) {

            //
            //  The chunk is compressed but now check if the amount
            //  we need to get is the entire chunk and if so then
            //  we can do the decompress straight into the caller's
            //  buffer
            //

            if ((FragmentOffset == 0) && (CopySize == UncompressedChunkSize)) {

                if (!NT_SUCCESS(Status = LZNT1DecompressChunk( CurrentUncompressedFragment,
                                                               EndOfUncompressedFragment,
                                                               CompressedChunk + sizeof(COMPRESSED_CHUNK_HEADER),
                                                               CompressedChunk + CompressedChunkSize,
                                                               &CopySize ))) {

                    *FinalUncompressedSize = CopySize;

                    return Status;
                }

            } else {

                //
                //  The caller wants only a portion of this compressed chunk
                //  so we need to read it into our work buffer and then copy
                //  the parts from the work buffer into the caller's buffer
                //

                if (!NT_SUCCESS(Status = LZNT1DecompressChunk( (PUCHAR)WorkSpace,
                                                               &WorkSpace->Buffer[0] + sizeof(LZNT1_FRAGMENT_WORKSPACE),
                                                               CompressedChunk + sizeof(COMPRESSED_CHUNK_HEADER),
                                                               CompressedChunk + CompressedChunkSize,
                                                               &UncompressedChunkSize ))) {

                    *FinalUncompressedSize = UncompressedChunkSize;

                    return Status;
                }

                //
                //  If we got less than we were looking for then we are at the
                //  end of the file.  Remember the real uncompressed size and
                //  break out of the loop.
                //

                if ((UncompressedChunkSize - FragmentOffset) < CopySize) {

                    RtlCopyMemory( CurrentUncompressedFragment,
                                   &WorkSpace->Buffer[ FragmentOffset ],
                                   (UncompressedChunkSize - FragmentOffset) );

                    CurrentUncompressedFragment += (UncompressedChunkSize - FragmentOffset);
                    break;
                }

                RtlCopyMemory( CurrentUncompressedFragment,
                               &WorkSpace->Buffer[ FragmentOffset ],
                               CopySize );
            }

        } else {

            //
            //  The chunk is not compressed so we can do a simple copy of the
            //  data.  First verify that the compressed buffer holds this much
            //  data.
            //

            if (CompressedChunk + sizeof(COMPRESSED_CHUNK_HEADER) + FragmentOffset + CopySize > EndOfCompressedBuffer) {

                ASSERTMSG("CompressedBuffer is too small", FALSE);
                *FinalUncompressedSize = (ULONG)CompressedChunk;
                return STATUS_BAD_COMPRESSION_BUFFER;
            }

            RtlCopyMemory( CurrentUncompressedFragment,
                           CompressedChunk + sizeof(COMPRESSED_CHUNK_HEADER) + FragmentOffset,
                           CopySize );
        }

        //
        //  Now that we've done at least one copy make sure the fragment
        //  offset is set to zero so the next time through the loop will
        //  start at the right offset
        //

        FragmentOffset = 0;

        //
        //  Adjust the uncompressed fragment information by moving the
        //  pointer up by the copy size and subtracting copy size from
        //  the amount of data the user wants
        //

        CurrentUncompressedFragment += CopySize;
        UncompressedFragmentSize -= CopySize;

        //
        //  Now if the uncompressed fragment size is zero then we're
        //  done
        //

        if (UncompressedFragmentSize == 0) { break; }

        //
        //  Otherwise the user wants more data so we'll move to the
        //  next chunk, and then check if the chunk is is use.  If
        //  it is not in use then we the user is trying to read beyond
        //  the end of compressed data so we'll break out of the loop
        //

        CompressedChunk += CompressedChunkSize;

        if (CompressedChunk > EndOfCompressedBuffer - 2) { break; }

        RtlRetrieveUshort( &ChunkHeader, CompressedChunk );

        if (ChunkHeader.Short == 0) { break; }

        ASSERT(ChunkHeader.Chunk.ChunkSignature == 3);

        //
        //  Decode the chunk sizes for the new current chunk
        //

        UncompressedChunkSize = GetUncompressedChunkSize(ChunkHeader);
        CompressedChunkSize = GetCompressedChunkSize(ChunkHeader);
    }

    //
    //  Now either we finished filling up the caller's buffer (and
    //  uncompressed fragment size is zero) or we've exhausted the
    //  compresed buffer (and chunk header is zero).  In either case
    //  we're done and we can now compute the size of the fragment
    //  that we're returning to the caller it is simply the difference
    //  between the start of the buffer and the current position
    //

    *FinalUncompressedSize = CurrentUncompressedFragment - UncompressedFragment;

    return STATUS_SUCCESS;
}


NTSTATUS
RtlDescribeChunkLZNT1 (
    IN OUT PUCHAR *CompressedBuffer,
    IN PUCHAR EndOfCompressedBufferPlus1,
    OUT PUCHAR *ChunkBuffer,
    OUT PULONG ChunkSize
    )

/*++

Routine Description:

    This routine takes as input a compressed buffer, and returns
    a description of the current chunk in that buffer, updating
    the CompressedBuffer pointer to point to the next chunk (if
    there is one).

Arguments:

    CompressedBuffer - Supplies a pointer to the current chunk in
        the compressed data, and returns pointing to the next chunk

    EndOfCompressedBufferPlus1 - Points at first byte beyond
        compressed buffer

    ChunkBuffer - Receives a pointer to the chunk, if ChunkSize
        is nonzero, else undefined

    ChunkSize - Receives the size of the current chunk pointed
        to by CompressedBuffer.  Returns 0 if STATUS_NO_MORE_ENTRIES.

Return Value:

    STATUS_SUCCESS - the chunk size is being returned

    STATUS_BAD_COMPRESSION_BUFFER - the input compressed buffer is
        ill-formed.

    STATUS_NO_MORE_ENTRIES - There is no chunk at the current pointer.

--*/

{
    COMPRESSED_CHUNK_HEADER ChunkHeader;
    NTSTATUS Status = STATUS_NO_MORE_ENTRIES;

    //
    //  First initialize outputs
    //

    *ChunkBuffer = *CompressedBuffer;
    *ChunkSize = 0;

    //
    //  Make sure that the compressed buffer is at least four bytes long to
    //  start with, otherwise just return a zero chunk.
    //

    if (*CompressedBuffer <= EndOfCompressedBufferPlus1 - 4) {

        RtlRetrieveUshort( &ChunkHeader, *CompressedBuffer );

        //
        //  Check for end of chunks, terminated by USHORT of 0.
        //  First assume there are no more.
        //

        if (ChunkHeader.Short != 0) {

            Status = STATUS_SUCCESS;

            *ChunkSize = GetCompressedChunkSize(ChunkHeader);
            *CompressedBuffer += *ChunkSize;

            //
            //  Check that the chunk actually fits in the buffer supplied
            //  by the caller.  If not, restore *CompressedBuffer for debug!
            //

            if ((*CompressedBuffer > EndOfCompressedBufferPlus1) ||
                (ChunkHeader.Chunk.ChunkSignature != 3)) {

                ASSERTMSG("CompressedBuffer is bad or too small", FALSE);

                *CompressedBuffer -= *ChunkSize;

                Status = STATUS_BAD_COMPRESSION_BUFFER;

            //
            //  First make sure the chunk contains compressed data
            //

            } else if (!ChunkHeader.Chunk.IsChunkCompressed) {

                //
                //  The uncompressed chunk must be exactly this size!
                //  If not, restore *CompressedBuffer for debug!
                //

                if (*ChunkSize != MAX_UNCOMPRESSED_CHUNK_SIZE + 2) {

                    ASSERTMSG("Uncompressed chunk is wrong size", FALSE);

                    *CompressedBuffer -= *ChunkSize;

                    Status = STATUS_BAD_COMPRESSION_BUFFER;

                //
                //  The chunk does not contain compressed data so we need to
                //  remove the chunk header from the chunk description.
                //

                } else {

                    *ChunkBuffer += 2;
                    *ChunkSize -= 2;
                }

            //
            //  Otherwise we have a compressed chunk, and we only need to
            //  see if it is all zeros!  Since the header is already interpreted,
            //  we only have to see if there is exactly one literal and if it
            //  is zero - it doesn't matter what the copy token says - we have
            //  a chunk of zeros!
            //

            } else if ((*ChunkSize == 6) && (*(*ChunkBuffer + 2) == 2) && (*(*ChunkBuffer + 3) == 0)) {

                *ChunkSize = 0;
            }
        }
    }

    return Status;
}


NTSTATUS
RtlReserveChunkLZNT1 (
    IN OUT PUCHAR *CompressedBuffer,
    IN PUCHAR EndOfCompressedBufferPlus1,
    OUT PUCHAR *ChunkBuffer,
    IN ULONG ChunkSize
    )

/*++

Routine Description:

    This routine reserves space for a chunk of the specified
    size in the buffer, writing in a chunk header if necessary
    (uncompressed or all zeros case).  On return the CompressedBuffer
    pointer points to the next chunk.

Arguments:

    CompressedBuffer - Supplies a pointer to the current chunk in
        the compressed data, and returns pointing to the next chunk

    EndOfCompressedBufferPlus1 - Points at first byte beyond
        compressed buffer

    ChunkBuffer - Receives a pointer to the chunk, if ChunkSize
        is nonzero, else undefined

    ChunkSize - Supplies the compressed size of the chunk to be received.
                Two special values are 0 and MAX_UNCOMPRESSED_CHUNK_SIZE (4096).
                0 means the chunk should be filled with a pattern that equates
                to 4096 0's.  4096 implies that the compression routine should
                prepare to receive all of the data in uncompressed form.

Return Value:

    STATUS_SUCCESS - the chunk size is being returned

    STATUS_BUFFER_TOO_SMALL - the compressed buffer is too small to hold the
        compressed data.

--*/

{
    COMPRESSED_CHUNK_HEADER ChunkHeader;
    BOOLEAN Compressed;
    PUCHAR Tail, NextChunk, DontCare;
    ULONG Size;
    NTSTATUS Status;

    ASSERT(ChunkSize <= MAX_UNCOMPRESSED_CHUNK_SIZE);

    //
    //  Calculate the address of the tail of this buffer and its
    //  size, so it can be moved before we store anything.
    //

    Tail = NextChunk = *CompressedBuffer;
    while (NT_SUCCESS(Status = RtlDescribeChunkLZNT1( &NextChunk,
                                                      EndOfCompressedBufferPlus1,
                                                      &DontCare,
                                                      &Size))) {

        //
        //  First time through the loop, capture the address of the next chunk.
        //

        if (Tail == *CompressedBuffer) {
            Tail = NextChunk;
        }
    }

    //
    //  The buffer could be invalid.
    //

    if (Status == STATUS_NO_MORE_ENTRIES) {

        //
        //  The only way to successfully terminate the loop is by finding a USHORT
        //  terminator of 0.  Now calculate the size including the final USHORT
        //  we stopped on.
        //

        Size = NextChunk - Tail + sizeof(USHORT);

        //
        //  First initialize outputs
        //

        Status = STATUS_BUFFER_TOO_SMALL;
        *ChunkBuffer = *CompressedBuffer;

        //
        //  Make sure that the compressed buffer is at least four bytes long to
        //  start with, otherwise just return a zero chunk.
        //

        if (*CompressedBuffer <= (EndOfCompressedBufferPlus1 - ChunkSize)) {

            //
            //  If the chunk is uncompressed, then we have to adjust the
            //  chunk description for the header.
            //

            if (ChunkSize == MAX_UNCOMPRESSED_CHUNK_SIZE) {

                //
                //  Increase ChunkSize to include header.
                //

                ChunkSize += 2;

                //
                //  Move the tail now that we know where to put it.
                //

                if ((*CompressedBuffer + ChunkSize + Size) <= EndOfCompressedBufferPlus1) {

                    RtlMoveMemory( *CompressedBuffer + ChunkSize, Tail, Size );

                    //
                    //  Build the header and store it for an uncompressed chunk.
                    //

                    SetCompressedChunkHeader( ChunkHeader,
                                              MAX_UNCOMPRESSED_CHUNK_SIZE + 2,
                                              FALSE );

                    RtlStoreUshort( *CompressedBuffer, ChunkHeader.Short );

                    //
                    //  Advance to where the uncompressed data goes.
                    //

                    *ChunkBuffer += 2;

                    Status = STATUS_SUCCESS;
                }

            //
            //  Otherwise, if this is a zero chunk we have to build it.
            //

            } else if (ChunkSize == 0) {

                //
                //  It takes 6 bytes to describe a chunk of zeros.
                //

                ChunkSize = 6;

                if ((*CompressedBuffer + ChunkSize + Size) <= EndOfCompressedBufferPlus1) {

                    //
                    //  Move the tail now that we know where to put it.
                    //

                    RtlMoveMemory( *CompressedBuffer + ChunkSize, Tail, Size );

                    //
                    //  Build the header and store it
                    //

                    SetCompressedChunkHeader( ChunkHeader,
                                              6,
                                              TRUE );

                    RtlStoreUshort( *CompressedBuffer, ChunkHeader.Short );

                    //
                    //  Now store the mask byte with one literal and the literal
                    //  is 0.
                    //

                    RtlStoreUshort( *CompressedBuffer + 2, (USHORT)2 );

                    //
                    //  Now store the copy token for copying 4095 bytes from
                    //  the preceding byte (stored as offset 0).
                    //

                    RtlStoreUshort( *CompressedBuffer + 4, (USHORT)(4095-3));

                    Status = STATUS_SUCCESS;
                }

            //
            //  Otherwise we have a normal compressed chunk.
            //

            } else {

                //
                //  Move the tail now that we know where to put it.
                //

                if ((*CompressedBuffer + ChunkSize + Size) <= EndOfCompressedBufferPlus1) {

                    RtlMoveMemory( *CompressedBuffer + ChunkSize, Tail, Size );

                    Status = STATUS_SUCCESS;
                }
            }

            //
            //  Advance the *CompressedBuffer before return
            //

            *CompressedBuffer += ChunkSize;
        }
    }

    return Status;
}


//
//  The Copy token is two bytes in size.
//  Our definition uses a union to make it easier to set and retrieve token values.
//
//  Copy Token
//
//          Length            Displacement
//
//      12 bits 3 to 4098    4 bits 1 to 16
//      11 bits 3 to 2050    5 bits 1 to 32
//      10 bits 3 to 1026    6 bits 1 to 64
//       9 bits 3 to 514     7 bits 1 to 128
//       8 bits 3 to 258     8 bits 1 to 256
//       7 bits 3 to 130     9 bits 1 to 512
//       6 bits 3 to 66     10 bits 1 to 1024
//       5 bits 3 to 34     11 bits 1 to 2048
//       4 bits 3 to 18     12 bits 1 to 4096
//

#define FORMAT412 0
#define FORMAT511 1
#define FORMAT610 2
#define FORMAT79  3
#define FORMAT88  4
#define FORMAT97  5
#define FORMAT106 6
#define FORMAT115 7
#define FORMAT124 8

//                                4/12  5/11  6/10   7/9   8/8   9/7  10/6  11/5  12/4

ULONG FormatMaxLength[]       = { 4098, 2050, 1026,  514,  258,  130,   66,   34,   18 };
ULONG FormatMaxDisplacement[] = {   16,   32,   64,  128,  256,  512, 1024, 2048, 4096 };

typedef union _LZNT1_COPY_TOKEN {

    struct { USHORT Length : 12; USHORT Displacement :  4; } Fields412;
    struct { USHORT Length : 11; USHORT Displacement :  5; } Fields511;
    struct { USHORT Length : 10; USHORT Displacement :  6; } Fields610;
    struct { USHORT Length :  9; USHORT Displacement :  7; } Fields79;
    struct { USHORT Length :  8; USHORT Displacement :  8; } Fields88;
    struct { USHORT Length :  7; USHORT Displacement :  9; } Fields97;
    struct { USHORT Length :  6; USHORT Displacement : 10; } Fields106;
    struct { USHORT Length :  5; USHORT Displacement : 11; } Fields115;
    struct { USHORT Length :  4; USHORT Displacement : 12; } Fields124;

    UCHAR Bytes[2];

} LZNT1_COPY_TOKEN, *PLZNT1_COPY_TOKEN;

//
//  USHORT
//  GetLZNT1Length (
//      IN COPY_TOKEN_FORMAT Format,
//      IN LZNT1_COPY_TOKEN CopyToken
//      );
//
//  USHORT
//  GetLZNT1Displacement (
//      IN COPY_TOKEN_FORMAT Format,
//      IN LZNT1_COPY_TOKEN CopyToken
//      );
//
//  VOID
//  SetLZNT1 (
//      IN COPY_TOKEN_FORMAT Format,
//      IN LZNT1_COPY_TOKEN CopyToken,
//      IN USHORT Length,
//      IN USHORT Displacement
//      );
//

#define GetLZNT1Length(F,CT) (                   \
    ( F == FORMAT412 ? (CT).Fields412.Length + 3 \
    : F == FORMAT511 ? (CT).Fields511.Length + 3 \
    : F == FORMAT610 ? (CT).Fields610.Length + 3 \
    : F == FORMAT79  ? (CT).Fields79.Length  + 3 \
    : F == FORMAT88  ? (CT).Fields88.Length  + 3 \
    : F == FORMAT97  ? (CT).Fields97.Length  + 3 \
    : F == FORMAT106 ? (CT).Fields106.Length + 3 \
    : F == FORMAT115 ? (CT).Fields115.Length + 3 \
    :                  (CT).Fields124.Length + 3 \
    )                                            \
)

#define GetLZNT1Displacement(F,CT) (                   \
    ( F == FORMAT412 ? (CT).Fields412.Displacement + 1 \
    : F == FORMAT511 ? (CT).Fields511.Displacement + 1 \
    : F == FORMAT610 ? (CT).Fields610.Displacement + 1 \
    : F == FORMAT79  ? (CT).Fields79.Displacement  + 1 \
    : F == FORMAT88  ? (CT).Fields88.Displacement  + 1 \
    : F == FORMAT97  ? (CT).Fields97.Displacement  + 1 \
    : F == FORMAT106 ? (CT).Fields106.Displacement + 1 \
    : F == FORMAT115 ? (CT).Fields115.Displacement + 1 \
    :                  (CT).Fields124.Displacement + 1 \
    )                                                  \
)

#define SetLZNT1(F,CT,L,D) {                                                                             \
    if      (F == FORMAT412) { (CT).Fields412.Length = (L) - 3; (CT).Fields412.Displacement = (D) - 1; } \
    else if (F == FORMAT511) { (CT).Fields511.Length = (L) - 3; (CT).Fields511.Displacement = (D) - 1; } \
    else if (F == FORMAT610) { (CT).Fields610.Length = (L) - 3; (CT).Fields610.Displacement = (D) - 1; } \
    else if (F == FORMAT79)  { (CT).Fields79.Length  = (L) - 3; (CT).Fields79.Displacement  = (D) - 1; } \
    else if (F == FORMAT88)  { (CT).Fields88.Length  = (L) - 3; (CT).Fields88.Displacement  = (D) - 1; } \
    else if (F == FORMAT97)  { (CT).Fields97.Length  = (L) - 3; (CT).Fields97.Displacement  = (D) - 1; } \
    else if (F == FORMAT106) { (CT).Fields106.Length = (L) - 3; (CT).Fields106.Displacement = (D) - 1; } \
    else if (F == FORMAT115) { (CT).Fields115.Length = (L) - 3; (CT).Fields115.Displacement = (D) - 1; } \
    else                     { (CT).Fields124.Length = (L) - 3; (CT).Fields124.Displacement = (D) - 1; } \
}


//
//  Local support routine
//

NTSTATUS
LZNT1CompressChunk (
    IN PLZNT1_MATCH_FUNCTION MatchFunction,
    IN PUCHAR UncompressedBuffer,
    IN PUCHAR EndOfUncompressedBufferPlus1,
    OUT PUCHAR CompressedBuffer,
    IN PUCHAR EndOfCompressedBufferPlus1,
    OUT PULONG FinalCompressedChunkSize,
    IN PVOID WorkSpace
    )

/*++

Routine Description:

    This routine takes as input an uncompressed chunk and produces
    one compressed chunk provided the compressed data fits within
    the specified destination buffer.

    The LZNT1 format used to store the compressed buffer.

    An output variable indicates the number of bytes used to store
    the compressed chunk.

Arguments:

    UncompressedBuffer - Supplies a pointer to the uncompressed chunk.

    EndOfUncompressedBufferPlus1 - Supplies a pointer to the next byte
        following the end of the uncompressed buffer.  This is supplied
        instead of the size in bytes because our caller and ourselves
        test against the pointer and by passing the pointer we get to
        skip the code to compute it each time.

    CompressedBuffer - Supplies a pointer to where the compressed chunk
        is to be stored.

    EndOfCompressedBufferPlus1 - Supplies a pointer to the next
        byte following the end of the compressed buffer.

    FinalCompressedChunkSize - Receives the number of bytes needed in
        the compressed buffer to store the compressed chunk.

Return Value:

    STATUS_SUCCESS - the compression worked without a hitch.

    STATUS_BUFFER_ALL_ZEROS - the compression worked without a hitch and in
        addition the input chunk was all zeros.

    STATUS_BUFFER_TOO_SMALL - the compressed buffer is too small to hold the
        compressed data.

--*/

{
    PUCHAR EndOfCompressedChunkPlus1;

    PUCHAR InputPointer;
    PUCHAR OutputPointer;

    PUCHAR FlagPointer;
    UCHAR FlagByte;
    ULONG FlagBit;

    LONG Length;
    LONG Displacement;

    LZNT1_COPY_TOKEN CopyToken;

    COMPRESSED_CHUNK_HEADER ChunkHeader;

    UCHAR NullCharacter = 0;

    ULONG Format = FORMAT412;

    //
    //  First adjust the end of the uncompressed buffer pointer to the smaller
    //  of what we're passed in and the uncompressed chunk size.  We use this
    //  to make sure we never compress more than a chunk worth at a time
    //

    if ((UncompressedBuffer + MAX_UNCOMPRESSED_CHUNK_SIZE) < EndOfUncompressedBufferPlus1) {

        EndOfUncompressedBufferPlus1 = UncompressedBuffer + MAX_UNCOMPRESSED_CHUNK_SIZE;
    }

    //
    //  Now set the end of the compressed chunk pointer to be the smaller of the
    //  compressed size necessary to hold the data in an uncompressed form and
    //  the compressed buffer size.  We use this to decide if we can't compress
    //  any more because the buffer is too small or just because the data
    //  doesn't compress very well.
    //

    if ((CompressedBuffer + MAX_UNCOMPRESSED_CHUNK_SIZE + sizeof(COMPRESSED_CHUNK_HEADER)) < EndOfCompressedBufferPlus1) {

        EndOfCompressedChunkPlus1 = CompressedBuffer + MAX_UNCOMPRESSED_CHUNK_SIZE + sizeof(COMPRESSED_CHUNK_HEADER);

    } else {

        EndOfCompressedChunkPlus1 = EndOfCompressedBufferPlus1;
    }

    //
    //  Now set the input and output pointers to the next byte we are
    //  go to process and asser that the user gave use buffers that were
    //  large enough to hold the minimum size chunks
    //

    InputPointer = UncompressedBuffer;
    OutputPointer = CompressedBuffer + sizeof(COMPRESSED_CHUNK_HEADER);

    ASSERT(InputPointer < EndOfUncompressedBufferPlus1);
    //**** ASSERT(OutputPointer + 2 <= EndOfCompressedChunkPlus1);

    //
    //  The flag byte stores a copy of the flags for the current
    //  run and the flag bit denotes the current bit position within
    //  the flag that we are processing.  The Flag pointer denotes
    //  where in the compressed buffer we will store the current
    //  flag byte
    //

    FlagPointer = OutputPointer++;
    FlagBit = 0;
    FlagByte = 0;

    ChunkHeader.Short = 0;

    //
    //  While there is some more data to be compressed we will do the
    //  following loop
    //

    ((PLZNT1_STANDARD_WORKSPACE)WorkSpace)->UncompressedBuffer = UncompressedBuffer;
    ((PLZNT1_STANDARD_WORKSPACE)WorkSpace)->EndOfUncompressedBufferPlus1 = EndOfUncompressedBufferPlus1;
    ((PLZNT1_STANDARD_WORKSPACE)WorkSpace)->MaxLength = FormatMaxLength[FORMAT412];

    while (InputPointer < EndOfUncompressedBufferPlus1) {

        while (UncompressedBuffer + FormatMaxDisplacement[Format] < InputPointer) {

            Format += 1;
            ((PLZNT1_STANDARD_WORKSPACE)WorkSpace)->MaxLength = FormatMaxLength[Format];
        }

        //
        //  Search for a string in the Lempel
        //

        Length = 0;
        if ((InputPointer + 3) <= EndOfUncompressedBufferPlus1) {

            Length = (MatchFunction)( InputPointer, WorkSpace );
        }

        //
        //  If the return length is zero then we need to output
        //  a literal.  We clear the flag bit to denote the literal
        //  output the charcter and build up a character bits
        //  composite that if it is still zero when we are done then
        //  we know the uncompressed buffer contained only zeros.
        //

        if (!Length) {

            //
            //  There is more data to output now make sure the output
            //  buffer is not already full and can contain at least one
            //  more byte
            //

            if (OutputPointer >= EndOfCompressedChunkPlus1) { break; }

            ClearFlag(FlagByte, (1 << FlagBit));

            NullCharacter |= *(OutputPointer++) = *(InputPointer++);

        } else {

            //
            //  We need to output two byte, now make sure that
            //  the output buffer can contain at least two more
            //  bytes.
            //

            if ((OutputPointer+1) >= EndOfCompressedChunkPlus1) { break; }

            //
            //  Compute the displacement from the current pointer
            //  to the matched string
            //

            Displacement = InputPointer - ((PLZNT1_STANDARD_WORKSPACE)WorkSpace)->MatchedString;

            //
            //  Make sure there is enough room in the output buffer
            //  for two bytes
            //

            if ((OutputPointer + 1) >= EndOfCompressedChunkPlus1) { break; }

            SetFlag(FlagByte, (1 << FlagBit));

            SetLZNT1(Format, CopyToken, Length, Displacement);

            *(OutputPointer++) = CopyToken.Bytes[0];
            *(OutputPointer++) = CopyToken.Bytes[1];

            InputPointer += Length;
        }

        //
        //  Now adjust the flag bit and check if the flag byte
        //  should now be output.  If so output the flag byte
        //  and scarf up a new byte in the output buffer for the
        //  next flag byte
        //

        FlagBit = (FlagBit + 1) % 8;

        if (!FlagBit) {

            *FlagPointer = FlagByte;
            FlagByte = 0;

            FlagPointer = (OutputPointer++);
        }
    }

    //
    //  We've exited the preceeding loop because either the input buffer is
    //  all compressed or because we ran out of space in the output buffer.
    //  Check here if the input buffer is not exhasted (i.e., we ran out
    //  of space)
    //

    if (InputPointer < EndOfUncompressedBufferPlus1) {

        //
        //  We ran out of space, but now if the total space available
        //  for the compressed chunk is equal to the uncompressed data plus
        //  the header then we will make this an uncompressed chunk and copy
        //  over the uncompressed data
        //

        if ((CompressedBuffer + MAX_UNCOMPRESSED_CHUNK_SIZE + sizeof(COMPRESSED_CHUNK_HEADER)) <= EndOfCompressedBufferPlus1) {

            RtlCopyMemory( CompressedBuffer + sizeof(COMPRESSED_CHUNK_HEADER),
                           UncompressedBuffer,
                           MAX_UNCOMPRESSED_CHUNK_SIZE );

            *FinalCompressedChunkSize = MAX_UNCOMPRESSED_CHUNK_SIZE + sizeof(COMPRESSED_CHUNK_HEADER);

            SetCompressedChunkHeader( ChunkHeader,
                                      (LONG)*FinalCompressedChunkSize,
                                      FALSE );

            RtlStoreUshort( CompressedBuffer, ChunkHeader.Short );

            return STATUS_SUCCESS;
        }

        //
        //  Otherwise the input buffer really is too small to store the
        //  compressed chuunk
        //

        return STATUS_BUFFER_TOO_SMALL;
    }

    //
    //  At this point the entire input buffer has been compressed so we need
    //  to output the last flag byte, provided it fits in the compressed buffer,
    //  set and store the chunk header.  Now if the Flag pointer doesn't fit
    //  in the output buffer that is because it is one beyond the end and
    //  we incremented output pointer too far so now bring output pointer
    //  back down.
    //

    if (FlagPointer < EndOfCompressedChunkPlus1) {

        *FlagPointer = FlagByte;

    } else {

        OutputPointer--;
    }

    *FinalCompressedChunkSize = (OutputPointer - CompressedBuffer);

    SetCompressedChunkHeader( ChunkHeader,
                              (LONG)*FinalCompressedChunkSize,
                              TRUE );

    RtlStoreUshort( CompressedBuffer, ChunkHeader.Short );

    //
    //  Now if the only literal we ever output was a null then the
    //  input buffer was all zeros.
    //

    if (!NullCharacter) {

        return STATUS_BUFFER_ALL_ZEROS;
    }

    //
    //  Otherwise return to our caller
    //

    return STATUS_SUCCESS;
}


#if !defined(_ALPHA_)
#if !defined(_MIPS_)
#if !defined(_PPC_)
#if !defined(i386)
//
//  Local support routine
//

NTSTATUS
LZNT1DecompressChunk (
    OUT PUCHAR UncompressedBuffer,
    IN PUCHAR EndOfUncompressedBufferPlus1,
    IN PUCHAR CompressedBuffer,
    IN PUCHAR EndOfCompressedBufferPlus1,
    OUT PULONG FinalUncompressedChunkSize
    )

/*++

Routine Description:

    This routine takes as input a compressed chunk and produces its
    uncompressed equivalent chunk provided the uncompressed data fits
    within the specified destination buffer.

    The compressed buffer must be stored in the LZNT1 format.

    An output variable indicates the number of bytes used to store the
    uncompressed data.

Arguments:

    UncompressedBuffer - Supplies a pointer to where the uncompressed
        chunk is to be stored.

    EndOfUncompressedBufferPlus1 - Supplies a pointer to the next byte
        following the end of the uncompressed buffer.  This is supplied
        instead of the size in bytes because our caller and ourselves
        test against the pointer and by passing the pointer we get to
        skip the code to compute it each time.

    CompressedBuffer - Supplies a pointer to the compressed chunk.  (This
        pointer has already been adjusted to point past the chunk header.)

    EndOfCompressedBufferPlus1 - Supplies a pointer to the next
        byte following the end of the compressed buffer.

    FinalUncompressedChunkSize - Receives the number of bytes needed in
        the uncompressed buffer to store the uncompressed chunk.

Return Value:

    STATUS_SUCCESS - the decompression worked without a hitch.

    STATUS_BAD_COMPRESSION_BUFFER - the input compressed buffer is
        ill-formed.

--*/

{
    PUCHAR OutputPointer;
    PUCHAR InputPointer;

    UCHAR FlagByte;
    ULONG FlagBit;

    ULONG Format = FORMAT412;

    //
    //  The two pointers will slide through our input and input buffer.
    //  For the input buffer we skip over the chunk header.
    //

    OutputPointer = UncompressedBuffer;
    InputPointer = CompressedBuffer;

    //
    //  The flag byte stores a copy of the flags for the current
    //  run and the flag bit denotes the current bit position within
    //  the flag that we are processing
    //

    FlagByte = *(InputPointer++);
    FlagBit = 0;

    //
    //  While we haven't exhausted either the input or output buffer
    //  we will do some more decompression
    //

    while ((OutputPointer < EndOfUncompressedBufferPlus1) && (InputPointer < EndOfCompressedBufferPlus1)) {

        while (UncompressedBuffer + FormatMaxDisplacement[Format] < OutputPointer) { Format += 1; }

        //
        //  Check the current flag if it is zero then the current
        //  input token is a literal byte that we simply copy over
        //  to the output buffer
        //

        if (!FlagOn(FlagByte, (1 << FlagBit))) {

            *(OutputPointer++) = *(InputPointer++);

        } else {

            LZNT1_COPY_TOKEN CopyToken;
            LONG Displacement;
            LONG Length;

            //
            //  The current input is a copy token so we'll get the
            //  copy token into our variable and extract the
            //  length and displacement from the token
            //

            if (InputPointer+1 >= EndOfCompressedBufferPlus1) {

                *FinalUncompressedChunkSize = (ULONG)InputPointer;

                return STATUS_BAD_COMPRESSION_BUFFER;
            }

            //
            //  Now grab the next input byte and extract the
            //  length and displacement from the copy token
            //

            CopyToken.Bytes[0] = *(InputPointer++);
            CopyToken.Bytes[1] = *(InputPointer++);

            Displacement = GetLZNT1Displacement(Format, CopyToken);
            Length = GetLZNT1Length(Format, CopyToken);

            //
            //  At this point we have the length and displacement
            //  from the copy token, now we need to make sure that the
            //  displacement doesn't send us outside the uncompressed buffer
            //

            if (Displacement > (OutputPointer - UncompressedBuffer)) {

                *FinalUncompressedChunkSize = (ULONG)InputPointer;

                return STATUS_BAD_COMPRESSION_BUFFER;
            }

            //
            //  We also need to adjust the length to keep the copy from
            //  overflowing the output buffer
            //

            if ((OutputPointer + Length) >= EndOfUncompressedBufferPlus1) {

                Length = EndOfUncompressedBufferPlus1 - OutputPointer;
            }

            //
            //  Now we copy bytes.  We cannot use Rtl Move Memory here because
            //  it does the copy backwards from what the LZ algorithm needs.
            //

            while (Length > 0) {

                *(OutputPointer) = *(OutputPointer-Displacement);

                Length -= 1;
                OutputPointer += 1;
            }
        }

        //
        //  Before we go back to the start of the loop we need to adjust the
        //  flag bit value (it goes from 0, 1, ... 7) and if the flag bit
        //  is back to zero we need to read in the next flag byte.  In this
        //  case we are at the end of the input buffer we'll just break out
        //  of the loop because we're done.
        //

        FlagBit = (FlagBit + 1) % 8;

        if (!FlagBit) {

            if (InputPointer >= EndOfCompressedBufferPlus1) { break; }

            FlagByte = *(InputPointer++);
        }
    }

    //
    //  The decompression is done so now set the final uncompressed
    //  chunk size and return success to our caller
    //

    *FinalUncompressedChunkSize = OutputPointer - UncompressedBuffer;

    return STATUS_SUCCESS;
}
#endif // i386
#endif // _MIPS_
#endif // _PPC_
#endif // _ALPHA_


//
//  Local support routine
//

ULONG
LZNT1FindMatchStandard (
    IN PUCHAR ZivString,
    IN PLZNT1_STANDARD_WORKSPACE WorkSpace
    )

/*++

Routine Description:

    This routine does the compression lookup.  It locates
    a match for the ziv within a specified uncompressed buffer.

Arguments:

    ZivString - Supplies a pointer to the Ziv in the uncompressed buffer.
        The Ziv is the string we want to try and find a match for.

Return Value:

    Returns the length of the match if the match is greater than three
    characters otherwise return 0.

--*/

{
    PUCHAR UncompressedBuffer = WorkSpace->UncompressedBuffer;
    PUCHAR EndOfUncompressedBufferPlus1 = WorkSpace->EndOfUncompressedBufferPlus1;
    ULONG MaxLength = WorkSpace->MaxLength;

    ULONG Index;

    PUCHAR FirstEntry;
    ULONG  FirstLength;

    PUCHAR SecondEntry;
    ULONG  SecondLength;

    //
    //  First check if the Ziv is within two bytes of the end of
    //  the uncompressed buffer, if so then we can't match
    //  three or more characters
    //

    Index = ((40543*((((ZivString[0]<<4)^ZivString[1])<<4)^ZivString[2]))>>4) & 0xfff;

    FirstEntry  = WorkSpace->IndexPTable[Index][0];
    FirstLength = 0;

    SecondEntry  = WorkSpace->IndexPTable[Index][1];
    SecondLength = 0;

    //
    //  Check if first entry is good, and if so then get its length
    //

    if ((FirstEntry >= UncompressedBuffer) &&    //  is it within the uncompressed buffer?
        (FirstEntry < ZivString)           &&

        (FirstEntry[0] == ZivString[0])    &&    //  do at least 3 characters match?
        (FirstEntry[1] == ZivString[1])    &&
        (FirstEntry[2] == ZivString[2])) {

        FirstLength = 3;

        while ((FirstLength < MaxLength)

                 &&

               (ZivString + FirstLength < EndOfUncompressedBufferPlus1)

                 &&

               (ZivString[FirstLength] == FirstEntry[FirstLength])) {

            FirstLength++;
        }
    }

    //
    //  Check if second entry is good, and if so then get its length
    //

    if ((SecondEntry >= UncompressedBuffer) &&    //  is it within the uncompressed buffer?
        (SecondEntry < ZivString)           &&

        (SecondEntry[0] == ZivString[0])    &&    //  do at least 3 characters match?
        (SecondEntry[1] == ZivString[1])    &&
        (SecondEntry[2] == ZivString[2])) {

        SecondLength = 3;

        while ((SecondLength < MaxLength)

                 &&

               (ZivString + SecondLength< EndOfUncompressedBufferPlus1)

                 &&

               (ZivString[SecondLength] == SecondEntry[SecondLength])) {

            SecondLength++;
        }
    }

    if ((FirstLength >= SecondLength)) {

        WorkSpace->IndexPTable[Index][1] = FirstEntry;
        WorkSpace->IndexPTable[Index][0] = ZivString;

        WorkSpace->MatchedString = FirstEntry;
        return FirstLength;
    }

    WorkSpace->IndexPTable[Index][1] = FirstEntry;
    WorkSpace->IndexPTable[Index][0] = ZivString;

    WorkSpace->MatchedString = SecondEntry;
    return SecondLength;
}


//
//  Local support routine
//

ULONG
LZNT1FindMatchMaximum (
    IN PUCHAR ZivString,
    IN PLZNT1_MAXIMUM_WORKSPACE WorkSpace
    )

/*++

Routine Description:

    This routine does the compression lookup.  It locates
    a match for the ziv within a specified uncompressed buffer.

    If the matched string is two or more characters long then this
    routine does not update the lookup state information.

Arguments:

    ZivString - Supplies a pointer to the Ziv in the uncompressed buffer.
        The Ziv is the string we want to try and find a match for.

Return Value:

    Returns the length of the match if the match is greater than three
    characters otherwise return 0.

--*/

{
    PUCHAR UncompressedBuffer = WorkSpace->UncompressedBuffer;
    PUCHAR EndOfUncompressedBufferPlus1 = WorkSpace->EndOfUncompressedBufferPlus1;
    ULONG MaxLength = WorkSpace->MaxLength;

    ULONG i;
    ULONG BestMatchedLength;
    PUCHAR q;

    //
    //  First check if the Ziv is within two bytes of the end of
    //  the uncompressed buffer, if so then we can't match
    //  three or more characters
    //

    BestMatchedLength = 0;

    for (q = UncompressedBuffer; q < ZivString; q += 1) {

        i = 0;

        while ((i < MaxLength)

                 &&

               (ZivString + i < EndOfUncompressedBufferPlus1)

                 &&

               (ZivString[i] == q[i])) {

            i++;
        }

        if (i >= BestMatchedLength) {

            BestMatchedLength = i;
            WorkSpace->MatchedString = q;
        }
    }

    if (BestMatchedLength < 3) {

        return 0;

    } else {

        return BestMatchedLength;
    }
}