From bb6f58f509e788460ba308977966b0a19ed6bbf5 Mon Sep 17 00:00:00 2001 From: Nikolaj Schlej Date: Wed, 4 Dec 2013 21:27:12 +0100 Subject: [PATCH] Version 0.11.0 - UI reworked once again - Hex pattern and text string search implemented - Code slightly refactored --- LZMA/LzmaCompress.c | 116 +- LZMA/LzmaDecompress.c | 110 +- LZMA/LzmaDecompress.h | 16 +- LZMA/SDK/C/LzFind.c | 638 +++++----- LZMA/SDK/C/LzmaDec.c | 1212 +++++++++--------- LZMA/SDK/C/LzmaEnc.c | 1912 ++++++++++++++-------------- Tiano/EfiCompress.c | 726 +++++------ Tiano/EfiTianoCompress.h | 10 +- Tiano/EfiTianoDecompress.c | 436 +++---- Tiano/EfiTianoDecompress.h | 4 +- Tiano/TianoCompress.c | 2444 ++++++++++++++++++------------------ basetypes.h | 5 + ffs.cpp | 22 +- ffs.h | 30 +- ffsengine.cpp | 213 ++-- ffsengine.h | 10 +- main.cpp | 4 + searchdialog.cpp | 48 + searchdialog.h | 34 + searchdialog.ui | 199 +++ treeitem.cpp | 2 +- treeitem.h | 2 +- uefitool.cpp | 377 +++--- uefitool.h | 59 +- uefitool.pro | 9 +- uefitool.ui | 386 +++--- 26 files changed, 4697 insertions(+), 4327 deletions(-) create mode 100644 searchdialog.cpp create mode 100644 searchdialog.h create mode 100644 searchdialog.ui diff --git a/LZMA/LzmaCompress.c b/LZMA/LzmaCompress.c index a6019ef..c30d64f 100644 --- a/LZMA/LzmaCompress.c +++ b/LZMA/LzmaCompress.c @@ -25,85 +25,85 @@ static ISzAlloc SzAllocForLzma = { &AllocForLzma, &FreeForLzma }; SRes OnProgress(void *p, UInt64 inSize, UInt64 outSize) { - return SZ_OK; + return SZ_OK; } static ICompressProgress g_ProgressCallback = { &OnProgress }; STATIC - UINT64 - EFIAPI - RShiftU64 ( - UINT64 Operand, - UINT32 Count - ) + UINT64 + EFIAPI + RShiftU64 ( + UINT64 Operand, + UINT32 Count + ) { - return Operand >> Count; + return Operand >> Count; } VOID - SetEncodedSizeOfBuf( - UINT64 EncodedSize, - UINT8 *EncodedData - ) + SetEncodedSizeOfBuf( + UINT64 EncodedSize, + UINT8 *EncodedData + ) { - INT32 Index; + INT32 Index; - EncodedData[LZMA_PROPS_SIZE] = EncodedSize & 0xFF; - for (Index = LZMA_PROPS_SIZE+1; Index <= LZMA_PROPS_SIZE + 7; Index++) - { - EncodedSize = RShiftU64(EncodedSize, 8); - EncodedData[Index] = EncodedSize & 0xFF; - } + EncodedData[LZMA_PROPS_SIZE] = EncodedSize & 0xFF; + for (Index = LZMA_PROPS_SIZE+1; Index <= LZMA_PROPS_SIZE + 7; Index++) + { + EncodedSize = RShiftU64(EncodedSize, 8); + EncodedData[Index] = EncodedSize & 0xFF; + } } INT32 - EFIAPI - LzmaCompress ( - CONST UINT8 *Source, - UINT32 SourceSize, - UINT8 *Destination, - UINT32 *DestinationSize - ) + EFIAPI + LzmaCompress ( + CONST UINT8 *Source, + UINT32 SourceSize, + UINT8 *Destination, + UINT32 *DestinationSize + ) { - SRes LzmaResult; - CLzmaEncProps props; - SizeT propsSize = LZMA_PROPS_SIZE; - SizeT destLen = SourceSize + SourceSize / 3 + 128; + SRes LzmaResult; + CLzmaEncProps props; + SizeT propsSize = LZMA_PROPS_SIZE; + SizeT destLen = SourceSize + SourceSize / 3 + 128; - if (*DestinationSize < destLen) - { - *DestinationSize = destLen; - return ERR_BUFFER_TOO_SMALL; - } + if (*DestinationSize < destLen) + { + *DestinationSize = destLen; + return ERR_BUFFER_TOO_SMALL; + } - LzmaEncProps_Init(&props); - props.dictSize = LZMA_DICTIONARY_SIZE; - props.level = 9; - props.fb = 273; + LzmaEncProps_Init(&props); + props.dictSize = LZMA_DICTIONARY_SIZE; + props.level = 9; + props.fb = 273; - LzmaResult = LzmaEncode( - (Byte*)((UINT8*)Destination + LZMA_HEADER_SIZE), - &destLen, - Source, - SourceSize, - &props, - (UINT8*)Destination, - &propsSize, - props.writeEndMark, - &g_ProgressCallback, - &SzAllocForLzma, - &SzAllocForLzma); + LzmaResult = LzmaEncode( + (Byte*)((UINT8*)Destination + LZMA_HEADER_SIZE), + &destLen, + Source, + SourceSize, + &props, + (UINT8*)Destination, + &propsSize, + props.writeEndMark, + &g_ProgressCallback, + &SzAllocForLzma, + &SzAllocForLzma); - *DestinationSize = destLen + LZMA_HEADER_SIZE; + *DestinationSize = destLen + LZMA_HEADER_SIZE; - SetEncodedSizeOfBuf((UINT64)SourceSize, Destination); + SetEncodedSizeOfBuf((UINT64)SourceSize, Destination); - if (LzmaResult == SZ_OK) { - return ERR_SUCCESS; - } else { - return ERR_INVALID_PARAMETER; - } + if (LzmaResult == SZ_OK) { + return ERR_SUCCESS; + } else { + return ERR_INVALID_PARAMETER; + } } diff --git a/LZMA/LzmaDecompress.c b/LZMA/LzmaDecompress.c index 81a65d3..5c37e23 100644 --- a/LZMA/LzmaDecompress.c +++ b/LZMA/LzmaDecompress.c @@ -18,13 +18,13 @@ WITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. #include UINT64 - EFIAPI - LShiftU64 ( - UINT64 Operand, - UINT32 Count - ) + EFIAPI + LShiftU64 ( + UINT64 Operand, + UINT32 Count + ) { - return Operand << Count; + return Operand << Count; } static void * AllocForLzma(void *p, size_t size) { return malloc(size); } @@ -39,19 +39,19 @@ Get the size of the uncompressed buffer by parsing EncodeData header. @return The size of the uncompressed buffer. */ UINT64 - GetDecodedSizeOfBuf( - UINT8 *EncodedData - ) + GetDecodedSizeOfBuf( + UINT8 *EncodedData + ) { - UINT64 DecodedSize; - INT32 Index; + UINT64 DecodedSize; + INT32 Index; - // Parse header - DecodedSize = 0; - for (Index = LZMA_PROPS_SIZE + 7; Index >= LZMA_PROPS_SIZE; Index--) - DecodedSize = LShiftU64(DecodedSize, 8) + EncodedData[Index]; + // Parse header + DecodedSize = 0; + for (Index = LZMA_PROPS_SIZE + 7; Index >= LZMA_PROPS_SIZE; Index--) + DecodedSize = LShiftU64(DecodedSize, 8) + EncodedData[Index]; - return DecodedSize; + return DecodedSize; } // @@ -86,21 +86,21 @@ buffer was returned ScratchSize. */ INT32 - EFIAPI - LzmaGetInfo ( - CONST VOID *Source, - UINT32 SourceSize, - UINT32 *DestinationSize - ) + EFIAPI + LzmaGetInfo ( + CONST VOID *Source, + UINT32 SourceSize, + UINT32 *DestinationSize + ) { - UInt64 DecodedSize; + UInt64 DecodedSize; - ASSERT(SourceSize >= LZMA_HEADER_SIZE); + ASSERT(SourceSize >= LZMA_HEADER_SIZE); - DecodedSize = GetDecodedSizeOfBuf((UINT8*)Source); + DecodedSize = GetDecodedSizeOfBuf((UINT8*)Source); - *DestinationSize = (UINT32)DecodedSize; - return ERR_SUCCESS; + *DestinationSize = (UINT32)DecodedSize; + return ERR_SUCCESS; } /* @@ -123,37 +123,37 @@ The source buffer specified by Source is corrupted (not a valid compressed format). */ INT32 - EFIAPI - LzmaDecompress ( - CONST VOID *Source, - UINT32 SourceSize, - VOID *Destination - ) + EFIAPI + LzmaDecompress ( + CONST VOID *Source, + UINT32 SourceSize, + VOID *Destination + ) { - SRes LzmaResult; - ELzmaStatus Status; - SizeT DecodedBufSize; - SizeT EncodedDataSize; + SRes LzmaResult; + ELzmaStatus Status; + SizeT DecodedBufSize; + SizeT EncodedDataSize; - DecodedBufSize = (SizeT)GetDecodedSizeOfBuf((UINT8*)Source); - EncodedDataSize = (SizeT) (SourceSize - LZMA_HEADER_SIZE); + DecodedBufSize = (SizeT)GetDecodedSizeOfBuf((UINT8*)Source); + EncodedDataSize = (SizeT) (SourceSize - LZMA_HEADER_SIZE); - LzmaResult = LzmaDecode( - Destination, - &DecodedBufSize, - (Byte*)((UINT8*)Source + LZMA_HEADER_SIZE), - &EncodedDataSize, - Source, - LZMA_PROPS_SIZE, - LZMA_FINISH_END, - &Status, - &SzAllocForLzma - ); + LzmaResult = LzmaDecode( + (Byte*) Destination, + &DecodedBufSize, + (Byte*)((UINT8*)Source + LZMA_HEADER_SIZE), + &EncodedDataSize, + (CONST Byte*) Source, + LZMA_PROPS_SIZE, + LZMA_FINISH_END, + &Status, + &SzAllocForLzma + ); - if (LzmaResult == SZ_OK) { - return ERR_SUCCESS; - } else { - return ERR_INVALID_PARAMETER; - } + if (LzmaResult == SZ_OK) { + return ERR_SUCCESS; + } else { + return ERR_INVALID_PARAMETER; + } } diff --git a/LZMA/LzmaDecompress.h b/LZMA/LzmaDecompress.h index 9ed377c..6501891 100644 --- a/LZMA/LzmaDecompress.h +++ b/LZMA/LzmaDecompress.h @@ -49,12 +49,12 @@ LShiftU64 ( @param Source The source buffer containing the compressed data. @param SourceSize The size, bytes, of the source buffer. @param DestinationSize A pointer to the size, bytes, of the uncompressed buffer - that will be generated when the compressed buffer specified - by Source and SourceSize is decompressed. + that will be generated when the compressed buffer specified + by Source and SourceSize is decompressed. @retval EFI_SUCCESS The size of the uncompressed data was returned - DestinationSize and the size of the scratch - buffer was returned ScratchSize. + DestinationSize and the size of the scratch + buffer was returned ScratchSize. */ INT32 @@ -77,12 +77,12 @@ LzmaGetInfo ( @param Source The source buffer containing the compressed data. @param SourceSize The size of source buffer. @param Destination The destination buffer to store the decompressed data - + @retval EFI_SUCCESS Decompression completed successfully, and - the uncompressed buffer is returned Destination. + the uncompressed buffer is returned Destination. @retval EFI_INVALID_PARAMETER - The source buffer specified by Source is corrupted - (not a valid compressed format). + The source buffer specified by Source is corrupted + (not a valid compressed format). */ INT32 EFIAPI diff --git a/LZMA/SDK/C/LzFind.c b/LZMA/SDK/C/LzFind.c index ea1c210..41eced0 100644 --- a/LZMA/SDK/C/LzFind.c +++ b/LZMA/SDK/C/LzFind.c @@ -18,8 +18,8 @@ static void LzInWindow_Free(CMatchFinder *p, ISzAlloc *alloc) { if (!p->directInput) { - alloc->Free(alloc, p->bufferBase); - p->bufferBase = 0; + alloc->Free(alloc, p->bufferBase); + p->bufferBase = 0; } } @@ -30,14 +30,14 @@ static int LzInWindow_Create(CMatchFinder *p, UInt32 keepSizeReserv, ISzAlloc *a UInt32 blockSize = p->keepSizeBefore + p->keepSizeAfter + keepSizeReserv; if (p->directInput) { - p->blockSize = blockSize; - return 1; + p->blockSize = blockSize; + return 1; } if (p->bufferBase == 0 || p->blockSize != blockSize) { - LzInWindow_Free(p, alloc); - p->blockSize = blockSize; - p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize); + LzInWindow_Free(p, alloc); + p->blockSize = blockSize; + p->bufferBase = (Byte *)alloc->Alloc(alloc, (size_t)blockSize); } return (p->bufferBase != 0); } @@ -57,50 +57,50 @@ void MatchFinder_ReduceOffsets(CMatchFinder *p, UInt32 subValue) static void MatchFinder_ReadBlock(CMatchFinder *p) { if (p->streamEndWasReached || p->result != SZ_OK) - return; + return; if (p->directInput) { - UInt32 curSize = 0xFFFFFFFF - p->streamPos; - if (curSize > p->directInputRem) - curSize = (UInt32)p->directInputRem; - p->directInputRem -= curSize; - p->streamPos += curSize; - if (p->directInputRem == 0) - p->streamEndWasReached = 1; - return; + UInt32 curSize = 0xFFFFFFFF - p->streamPos; + if (curSize > p->directInputRem) + curSize = (UInt32)p->directInputRem; + p->directInputRem -= curSize; + p->streamPos += curSize; + if (p->directInputRem == 0) + p->streamEndWasReached = 1; + return; } for (;;) { - Byte *dest = p->buffer + (p->streamPos - p->pos); - size_t size = (p->bufferBase + p->blockSize - dest); - if (size == 0) - return; - p->result = p->stream->Read(p->stream, dest, &size); - if (p->result != SZ_OK) - return; - if (size == 0) - { - p->streamEndWasReached = 1; - return; - } - p->streamPos += (UInt32)size; - if (p->streamPos - p->pos > p->keepSizeAfter) - return; + Byte *dest = p->buffer + (p->streamPos - p->pos); + size_t size = (p->bufferBase + p->blockSize - dest); + if (size == 0) + return; + p->result = p->stream->Read(p->stream, dest, &size); + if (p->result != SZ_OK) + return; + if (size == 0) + { + p->streamEndWasReached = 1; + return; + } + p->streamPos += (UInt32)size; + if (p->streamPos - p->pos > p->keepSizeAfter) + return; } } void MatchFinder_MoveBlock(CMatchFinder *p) { memmove(p->bufferBase, - p->buffer - p->keepSizeBefore, - (size_t)(p->streamPos - p->pos + p->keepSizeBefore)); + p->buffer - p->keepSizeBefore, + (size_t)(p->streamPos - p->pos + p->keepSizeBefore)); p->buffer = p->bufferBase + p->keepSizeBefore; } int MatchFinder_NeedMove(CMatchFinder *p) { if (p->directInput) - return 0; + return 0; /* if (p->streamEndWasReached) return 0; */ return ((size_t)(p->bufferBase + p->blockSize - p->buffer) <= p->keepSizeAfter); } @@ -108,15 +108,15 @@ int MatchFinder_NeedMove(CMatchFinder *p) void MatchFinder_ReadIfRequired(CMatchFinder *p) { if (p->streamEndWasReached) - return; + return; if (p->keepSizeAfter >= p->streamPos - p->pos) - MatchFinder_ReadBlock(p); + MatchFinder_ReadBlock(p); } static void MatchFinder_CheckAndMoveAndRead(CMatchFinder *p) { if (MatchFinder_NeedMove(p)) - MatchFinder_MoveBlock(p); + MatchFinder_MoveBlock(p); MatchFinder_ReadBlock(p); } @@ -140,11 +140,11 @@ void MatchFinder_Construct(CMatchFinder *p) for (i = 0; i < 256; i++) { - UInt32 r = i; - int j; - for (j = 0; j < 8; j++) - r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); - p->crc[i] = r; + UInt32 r = i; + int j; + for (j = 0; j < 8; j++) + r = (r >> 1) ^ (kCrcPoly & ~((r & 1) - 1)); + p->crc[i] = r; } } @@ -164,23 +164,23 @@ static CLzRef* AllocRefs(UInt32 num, ISzAlloc *alloc) { size_t sizeInBytes = (size_t)num * sizeof(CLzRef); if (sizeInBytes / sizeof(CLzRef) != num) - return 0; + return 0; return (CLzRef *)alloc->Alloc(alloc, sizeInBytes); } int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, - UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, - ISzAlloc *alloc) + UInt32 keepAddBufferBefore, UInt32 matchMaxLen, UInt32 keepAddBufferAfter, + ISzAlloc *alloc) { UInt32 sizeReserv; if (historySize > kMaxHistorySize) { - MatchFinder_Free(p, alloc); - return 0; + MatchFinder_Free(p, alloc); + return 0; } sizeReserv = historySize >> 1; if (historySize > ((UInt32)2 << 30)) - sizeReserv = historySize >> 2; + sizeReserv = historySize >> 2; sizeReserv += (keepAddBufferBefore + matchMaxLen + keepAddBufferAfter) / 2 + (1 << 19); p->keepSizeBefore = historySize + keepAddBufferBefore + 1; @@ -188,56 +188,56 @@ int MatchFinder_Create(CMatchFinder *p, UInt32 historySize, /* we need one additional byte, since we use MoveBlock after pos++ and before dictionary using */ if (LzInWindow_Create(p, sizeReserv, alloc)) { - UInt32 newCyclicBufferSize = historySize + 1; - UInt32 hs; - p->matchMaxLen = matchMaxLen; - { - p->fixedHashSize = 0; - if (p->numHashBytes == 2) - hs = (1 << 16) - 1; - else - { - hs = historySize - 1; - hs |= (hs >> 1); - hs |= (hs >> 2); - hs |= (hs >> 4); - hs |= (hs >> 8); - hs >>= 1; - hs |= 0xFFFF; /* don't change it! It's required for Deflate */ - if (hs > (1 << 24)) - { - if (p->numHashBytes == 3) - hs = (1 << 24) - 1; - else - hs >>= 1; - } - } - p->hashMask = hs; - hs++; - if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; - if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; - if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size; - hs += p->fixedHashSize; - } + UInt32 newCyclicBufferSize = historySize + 1; + UInt32 hs; + p->matchMaxLen = matchMaxLen; + { + p->fixedHashSize = 0; + if (p->numHashBytes == 2) + hs = (1 << 16) - 1; + else + { + hs = historySize - 1; + hs |= (hs >> 1); + hs |= (hs >> 2); + hs |= (hs >> 4); + hs |= (hs >> 8); + hs >>= 1; + hs |= 0xFFFF; /* don't change it! It's required for Deflate */ + if (hs > (1 << 24)) + { + if (p->numHashBytes == 3) + hs = (1 << 24) - 1; + else + hs >>= 1; + } + } + p->hashMask = hs; + hs++; + if (p->numHashBytes > 2) p->fixedHashSize += kHash2Size; + if (p->numHashBytes > 3) p->fixedHashSize += kHash3Size; + if (p->numHashBytes > 4) p->fixedHashSize += kHash4Size; + hs += p->fixedHashSize; + } - { - UInt32 prevSize = p->hashSizeSum + p->numSons; - UInt32 newSize; - p->historySize = historySize; - p->hashSizeSum = hs; - p->cyclicBufferSize = newCyclicBufferSize; - p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize); - newSize = p->hashSizeSum + p->numSons; - if (p->hash != 0 && prevSize == newSize) - return 1; - MatchFinder_FreeThisClassMemory(p, alloc); - p->hash = AllocRefs(newSize, alloc); - if (p->hash != 0) - { - p->son = p->hash + p->hashSizeSum; - return 1; - } - } + { + UInt32 prevSize = p->hashSizeSum + p->numSons; + UInt32 newSize; + p->historySize = historySize; + p->hashSizeSum = hs; + p->cyclicBufferSize = newCyclicBufferSize; + p->numSons = (p->btMode ? newCyclicBufferSize * 2 : newCyclicBufferSize); + newSize = p->hashSizeSum + p->numSons; + if (p->hash != 0 && prevSize == newSize) + return 1; + MatchFinder_FreeThisClassMemory(p, alloc); + p->hash = AllocRefs(newSize, alloc); + if (p->hash != 0) + { + p->son = p->hash + p->hashSizeSum; + return 1; + } + } } MatchFinder_Free(p, alloc); return 0; @@ -248,22 +248,22 @@ static void MatchFinder_SetLimits(CMatchFinder *p) UInt32 limit = kMaxValForNormalize - p->pos; UInt32 limit2 = p->cyclicBufferSize - p->cyclicBufferPos; if (limit2 < limit) - limit = limit2; + limit = limit2; limit2 = p->streamPos - p->pos; if (limit2 <= p->keepSizeAfter) { - if (limit2 > 0) - limit2 = 1; + if (limit2 > 0) + limit2 = 1; } else - limit2 -= p->keepSizeAfter; + limit2 -= p->keepSizeAfter; if (limit2 < limit) - limit = limit2; + limit = limit2; { - UInt32 lenLimit = p->streamPos - p->pos; - if (lenLimit > p->matchMaxLen) - lenLimit = p->matchMaxLen; - p->lenLimit = lenLimit; + UInt32 lenLimit = p->streamPos - p->pos; + if (lenLimit > p->matchMaxLen) + lenLimit = p->matchMaxLen; + p->lenLimit = lenLimit; } p->posLimit = p->pos + limit; } @@ -272,7 +272,7 @@ void MatchFinder_Init(CMatchFinder *p) { UInt32 i; for (i = 0; i < p->hashSizeSum; i++) - p->hash[i] = kEmptyHashValue; + p->hash[i] = kEmptyHashValue; p->cyclicBufferPos = 0; p->buffer = p->bufferBase; p->pos = p->streamPos = p->cyclicBufferSize; @@ -292,12 +292,12 @@ void MatchFinder_Normalize3(UInt32 subValue, CLzRef *items, UInt32 numItems) UInt32 i; for (i = 0; i < numItems; i++) { - UInt32 value = items[i]; - if (value <= subValue) - value = kEmptyHashValue; - else - value -= subValue; - items[i] = value; + UInt32 value = items[i]; + if (value <= subValue) + value = kEmptyHashValue; + else + value -= subValue; + items[i] = value; } } @@ -311,147 +311,147 @@ static void MatchFinder_Normalize(CMatchFinder *p) static void MatchFinder_CheckLimits(CMatchFinder *p) { if (p->pos == kMaxValForNormalize) - MatchFinder_Normalize(p); + MatchFinder_Normalize(p); if (!p->streamEndWasReached && p->keepSizeAfter == p->streamPos - p->pos) - MatchFinder_CheckAndMoveAndRead(p); + MatchFinder_CheckAndMoveAndRead(p); if (p->cyclicBufferPos == p->cyclicBufferSize) - p->cyclicBufferPos = 0; + p->cyclicBufferPos = 0; MatchFinder_SetLimits(p); } static UInt32 * Hc_GetMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, UInt32 maxLen) + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, + UInt32 *distances, UInt32 maxLen) { son[_cyclicBufferPos] = curMatch; for (;;) { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - return distances; - { - const Byte *pb = cur - delta; - curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; - if (pb[maxLen] == cur[maxLen] && *pb == *cur) - { - UInt32 len = 0; - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - return distances; - } - } - } + UInt32 delta = pos - curMatch; + if (cutValue-- == 0 || delta >= _cyclicBufferSize) + return distances; + { + const Byte *pb = cur - delta; + curMatch = son[_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)]; + if (pb[maxLen] == cur[maxLen] && *pb == *cur) + { + UInt32 len = 0; + while (++len != lenLimit) + if (pb[len] != cur[len]) + break; + if (maxLen < len) + { + *distances++ = maxLen = len; + *distances++ = delta - 1; + if (len == lenLimit) + return distances; + } + } + } } } UInt32 * GetMatchesSpec1(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, - UInt32 *distances, UInt32 maxLen) + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue, + UInt32 *distances, UInt32 maxLen) { CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; CLzRef *ptr1 = son + (_cyclicBufferPos << 1); UInt32 len0 = 0, len1 = 0; for (;;) { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - return distances; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - if (++len != lenLimit && pb[len] == cur[len]) - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - if (maxLen < len) - { - *distances++ = maxLen = len; - *distances++ = delta - 1; - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - return distances; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } + UInt32 delta = pos - curMatch; + if (cutValue-- == 0 || delta >= _cyclicBufferSize) + { + *ptr0 = *ptr1 = kEmptyHashValue; + return distances; + } + { + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); + const Byte *pb = cur - delta; + UInt32 len = (len0 < len1 ? len0 : len1); + if (pb[len] == cur[len]) + { + if (++len != lenLimit && pb[len] == cur[len]) + while (++len != lenLimit) + if (pb[len] != cur[len]) + break; + if (maxLen < len) + { + *distances++ = maxLen = len; + *distances++ = delta - 1; + if (len == lenLimit) + { + *ptr1 = pair[0]; + *ptr0 = pair[1]; + return distances; + } + } + } + if (pb[len] < cur[len]) + { + *ptr1 = curMatch; + ptr1 = pair + 1; + curMatch = *ptr1; + len1 = len; + } + else + { + *ptr0 = curMatch; + ptr0 = pair; + curMatch = *ptr0; + len0 = len; + } + } } } static void SkipMatchesSpec(UInt32 lenLimit, UInt32 curMatch, UInt32 pos, const Byte *cur, CLzRef *son, - UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue) + UInt32 _cyclicBufferPos, UInt32 _cyclicBufferSize, UInt32 cutValue) { CLzRef *ptr0 = son + (_cyclicBufferPos << 1) + 1; CLzRef *ptr1 = son + (_cyclicBufferPos << 1); UInt32 len0 = 0, len1 = 0; for (;;) { - UInt32 delta = pos - curMatch; - if (cutValue-- == 0 || delta >= _cyclicBufferSize) - { - *ptr0 = *ptr1 = kEmptyHashValue; - return; - } - { - CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); - const Byte *pb = cur - delta; - UInt32 len = (len0 < len1 ? len0 : len1); - if (pb[len] == cur[len]) - { - while (++len != lenLimit) - if (pb[len] != cur[len]) - break; - { - if (len == lenLimit) - { - *ptr1 = pair[0]; - *ptr0 = pair[1]; - return; - } - } - } - if (pb[len] < cur[len]) - { - *ptr1 = curMatch; - ptr1 = pair + 1; - curMatch = *ptr1; - len1 = len; - } - else - { - *ptr0 = curMatch; - ptr0 = pair; - curMatch = *ptr0; - len0 = len; - } - } + UInt32 delta = pos - curMatch; + if (cutValue-- == 0 || delta >= _cyclicBufferSize) + { + *ptr0 = *ptr1 = kEmptyHashValue; + return; + } + { + CLzRef *pair = son + ((_cyclicBufferPos - delta + ((delta > _cyclicBufferPos) ? _cyclicBufferSize : 0)) << 1); + const Byte *pb = cur - delta; + UInt32 len = (len0 < len1 ? len0 : len1); + if (pb[len] == cur[len]) + { + while (++len != lenLimit) + if (pb[len] != cur[len]) + break; + { + if (len == lenLimit) + { + *ptr1 = pair[0]; + *ptr0 = pair[1]; + return; + } + } + } + if (pb[len] < cur[len]) + { + *ptr1 = curMatch; + ptr1 = pair + 1; + curMatch = *ptr1; + len1 = len; + } + else + { + *ptr0 = curMatch; + ptr0 = pair; + curMatch = *ptr0; + len0 = len; + } + } } } @@ -521,17 +521,17 @@ static UInt32 Bt3_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) offset = 0; if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[0] = maxLen; - distances[1] = delta2 - 1; - offset = 2; - if (maxLen == lenLimit) - { - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); - MOVE_POS_RET; - } + for (; maxLen != lenLimit; maxLen++) + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) + break; + distances[0] = maxLen; + distances[1] = delta2 - 1; + offset = 2; + if (maxLen == lenLimit) + { + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); + MOVE_POS_RET; + } } GET_MATCHES_FOOTER(offset, maxLen) } @@ -555,31 +555,31 @@ static UInt32 Bt4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) offset = 0; if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) { - distances[0] = maxLen = 2; - distances[1] = delta2 - 1; - offset = 2; + distances[0] = maxLen = 2; + distances[1] = delta2 - 1; + offset = 2; } if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) { - maxLen = 3; - distances[offset + 1] = delta3 - 1; - offset += 2; - delta2 = delta3; + maxLen = 3; + distances[offset + 1] = delta3 - 1; + offset += 2; + delta2 = delta3; } if (offset != 0) { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[offset - 2] = maxLen; - if (maxLen == lenLimit) - { - SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); - MOVE_POS_RET; - } + for (; maxLen != lenLimit; maxLen++) + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) + break; + distances[offset - 2] = maxLen; + if (maxLen == lenLimit) + { + SkipMatchesSpec(lenLimit, curMatch, MF_PARAMS(p)); + MOVE_POS_RET; + } } if (maxLen < 3) - maxLen = 3; + maxLen = 3; GET_MATCHES_FOOTER(offset, maxLen) } @@ -602,33 +602,33 @@ static UInt32 Hc4_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) offset = 0; if (delta2 < p->cyclicBufferSize && *(cur - delta2) == *cur) { - distances[0] = maxLen = 2; - distances[1] = delta2 - 1; - offset = 2; + distances[0] = maxLen = 2; + distances[1] = delta2 - 1; + offset = 2; } if (delta2 != delta3 && delta3 < p->cyclicBufferSize && *(cur - delta3) == *cur) { - maxLen = 3; - distances[offset + 1] = delta3 - 1; - offset += 2; - delta2 = delta3; + maxLen = 3; + distances[offset + 1] = delta3 - 1; + offset += 2; + delta2 = delta3; } if (offset != 0) { - for (; maxLen != lenLimit; maxLen++) - if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) - break; - distances[offset - 2] = maxLen; - if (maxLen == lenLimit) - { - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS_RET; - } + for (; maxLen != lenLimit; maxLen++) + if (cur[(ptrdiff_t)maxLen - delta2] != cur[maxLen]) + break; + distances[offset - 2] = maxLen; + if (maxLen == lenLimit) + { + p->son[p->cyclicBufferPos] = curMatch; + MOVE_POS_RET; + } } if (maxLen < 3) - maxLen = 3; + maxLen = 3; offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances + offset, maxLen) - (distances)); + distances + offset, maxLen) - (distances)); MOVE_POS_RET } @@ -640,7 +640,7 @@ UInt32 Hc3Zip_MatchFinder_GetMatches(CMatchFinder *p, UInt32 *distances) curMatch = p->hash[hashValue]; p->hash[hashValue] = p->pos; offset = (UInt32)(Hc_GetMatchesSpec(lenLimit, curMatch, MF_PARAMS(p), - distances, 2) - (distances)); + distances, 2) - (distances)); MOVE_POS_RET } @@ -648,11 +648,11 @@ static void Bt2_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { do { - SKIP_HEADER(2) - HASH2_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - SKIP_FOOTER + SKIP_HEADER(2) + HASH2_CALC; + curMatch = p->hash[hashValue]; + p->hash[hashValue] = p->pos; + SKIP_FOOTER } while (--num != 0); } @@ -661,11 +661,11 @@ void Bt3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { do { - SKIP_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - SKIP_FOOTER + SKIP_HEADER(3) + HASH_ZIP_CALC; + curMatch = p->hash[hashValue]; + p->hash[hashValue] = p->pos; + SKIP_FOOTER } while (--num != 0); } @@ -674,13 +674,13 @@ static void Bt3_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { do { - UInt32 hash2Value; - SKIP_HEADER(3) - HASH3_CALC; - curMatch = p->hash[kFix3HashSize + hashValue]; - p->hash[hash2Value] = - p->hash[kFix3HashSize + hashValue] = p->pos; - SKIP_FOOTER + UInt32 hash2Value; + SKIP_HEADER(3) + HASH3_CALC; + curMatch = p->hash[kFix3HashSize + hashValue]; + p->hash[hash2Value] = + p->hash[kFix3HashSize + hashValue] = p->pos; + SKIP_FOOTER } while (--num != 0); } @@ -689,14 +689,14 @@ static void Bt4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { do { - UInt32 hash2Value, hash3Value; - SKIP_HEADER(4) - HASH4_CALC; - curMatch = p->hash[kFix4HashSize + hashValue]; - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = p->pos; - p->hash[kFix4HashSize + hashValue] = p->pos; - SKIP_FOOTER + UInt32 hash2Value, hash3Value; + SKIP_HEADER(4) + HASH4_CALC; + curMatch = p->hash[kFix4HashSize + hashValue]; + p->hash[ hash2Value] = + p->hash[kFix3HashSize + hash3Value] = p->pos; + p->hash[kFix4HashSize + hashValue] = p->pos; + SKIP_FOOTER } while (--num != 0); } @@ -705,15 +705,15 @@ static void Hc4_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { do { - UInt32 hash2Value, hash3Value; - SKIP_HEADER(4) - HASH4_CALC; - curMatch = p->hash[kFix4HashSize + hashValue]; - p->hash[ hash2Value] = - p->hash[kFix3HashSize + hash3Value] = - p->hash[kFix4HashSize + hashValue] = p->pos; - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS + UInt32 hash2Value, hash3Value; + SKIP_HEADER(4) + HASH4_CALC; + curMatch = p->hash[kFix4HashSize + hashValue]; + p->hash[ hash2Value] = + p->hash[kFix3HashSize + hash3Value] = + p->hash[kFix4HashSize + hashValue] = p->pos; + p->son[p->cyclicBufferPos] = curMatch; + MOVE_POS } while (--num != 0); } @@ -722,12 +722,12 @@ void Hc3Zip_MatchFinder_Skip(CMatchFinder *p, UInt32 num) { do { - SKIP_HEADER(3) - HASH_ZIP_CALC; - curMatch = p->hash[hashValue]; - p->hash[hashValue] = p->pos; - p->son[p->cyclicBufferPos] = curMatch; - MOVE_POS + SKIP_HEADER(3) + HASH_ZIP_CALC; + curMatch = p->hash[hashValue]; + p->hash[hashValue] = p->pos; + p->son[p->cyclicBufferPos] = curMatch; + MOVE_POS } while (--num != 0); } @@ -740,22 +740,22 @@ void MatchFinder_CreateVTable(CMatchFinder *p, IMatchFinder *vTable) vTable->GetPointerToCurrentPos = (Mf_GetPointerToCurrentPos_Func)MatchFinder_GetPointerToCurrentPos; if (!p->btMode) { - vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; + vTable->GetMatches = (Mf_GetMatches_Func)Hc4_MatchFinder_GetMatches; + vTable->Skip = (Mf_Skip_Func)Hc4_MatchFinder_Skip; } else if (p->numHashBytes == 2) { - vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; + vTable->GetMatches = (Mf_GetMatches_Func)Bt2_MatchFinder_GetMatches; + vTable->Skip = (Mf_Skip_Func)Bt2_MatchFinder_Skip; } else if (p->numHashBytes == 3) { - vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; + vTable->GetMatches = (Mf_GetMatches_Func)Bt3_MatchFinder_GetMatches; + vTable->Skip = (Mf_Skip_Func)Bt3_MatchFinder_Skip; } else { - vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches; - vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; + vTable->GetMatches = (Mf_GetMatches_Func)Bt4_MatchFinder_GetMatches; + vTable->Skip = (Mf_Skip_Func)Bt4_MatchFinder_Skip; } } diff --git a/LZMA/SDK/C/LzmaDec.c b/LZMA/SDK/C/LzmaDec.c index 54bd103..031b1c3 100644 --- a/LZMA/SDK/C/LzmaDec.c +++ b/LZMA/SDK/C/LzmaDec.c @@ -119,13 +119,13 @@ StopCompilingDueBUG And it decodes new LZMA-symbols while (buf < bufLimit), but "buf" is withlast normalization Out: Result: - SZ_OK - OK - SZ_ERROR_DATA - Error + SZ_OK - OK + SZ_ERROR_DATA - Error p->remainLen: - < kMatchSpecLenStart : normal remain - = kMatchSpecLenStart : finished - = kMatchSpecLenStart + 1 : Flush marker - = kMatchSpecLenStart + 2 : State Init Marker + < kMatchSpecLenStart : normal remain + = kMatchSpecLenStart : finished + = kMatchSpecLenStart + 1 : Flush marker + = kMatchSpecLenStart + 2 : State Init Marker */ static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte *bufLimit) @@ -152,261 +152,261 @@ static int MY_FAST_CALL LzmaDec_DecodeReal(CLzmaDec *p, SizeT limit, const Byte do { - CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = processedPos & pbMask; + CLzmaProb *prob; + UInt32 bound; + unsigned ttt; + unsigned posState = processedPos & pbMask; - prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; - IF_BIT_0(prob) - { - unsigned symbol; - UPDATE_0(prob); - prob = probs + Literal; - if (checkDicSize != 0 || processedPos != 0) - prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) + - (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc)))); + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; + IF_BIT_0(prob) + { + unsigned symbol; + UPDATE_0(prob); + prob = probs + Literal; + if (checkDicSize != 0 || processedPos != 0) + prob += (LZMA_LIT_SIZE * (((processedPos & lpMask) << lc) + + (dic[(dicPos == 0 ? dicBufSize : dicPos) - 1] >> (8 - lc)))); - if (state < kNumLitStates) - { - state -= (state < 4) ? state : 3; - symbol = 1; - do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100); - } - else - { - unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - unsigned offs = 0x100; - state -= (state < 10) ? 3 : 6; - symbol = 1; - do - { - unsigned bit; - CLzmaProb *probLit; - matchByte <<= 1; - bit = (matchByte & offs); - probLit = prob + offs + bit + symbol; - GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit) - } - while (symbol < 0x100); - } - dic[dicPos++] = (Byte)symbol; - processedPos++; - continue; - } - else - { - UPDATE_1(prob); - prob = probs + IsRep + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - state += kNumStates; - prob = probs + LenCoder; - } - else - { - UPDATE_1(prob); - if (checkDicSize == 0 && processedPos == 0) - return SZ_ERROR_DATA; - prob = probs + IsRepG0 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; - IF_BIT_0(prob) - { - UPDATE_0(prob); - dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - dicPos++; - processedPos++; - state = state < kNumLitStates ? 9 : 11; - continue; - } - UPDATE_1(prob); - } - else - { - UInt32 distance; - UPDATE_1(prob); - prob = probs + IsRepG1 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - distance = rep1; - } - else - { - UPDATE_1(prob); - prob = probs + IsRepG2 + state; - IF_BIT_0(prob) - { - UPDATE_0(prob); - distance = rep2; - } - else - { - UPDATE_1(prob); - distance = rep3; - rep3 = rep2; - } - rep2 = rep1; - } - rep1 = rep0; - rep0 = distance; - } - state = state < kNumLitStates ? 8 : 11; - prob = probs + RepLenCoder; - } - { - unsigned limit, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); - probLen = prob + LenLow + (posState << kLenNumLowBits); - offset = 0; - limit = (1 << kLenNumLowBits); - } - else - { - UPDATE_1(probLen); - probLen = prob + LenChoice2; - IF_BIT_0(probLen) - { - UPDATE_0(probLen); - probLen = prob + LenMid + (posState << kLenNumMidBits); - offset = kLenNumLowSymbols; - limit = (1 << kLenNumMidBits); - } - else - { - UPDATE_1(probLen); - probLen = prob + LenHigh; - offset = kLenNumLowSymbols + kLenNumMidSymbols; - limit = (1 << kLenNumHighBits); - } - } - TREE_DECODE(probLen, limit, len); - len += offset; - } + if (state < kNumLitStates) + { + state -= (state < 4) ? state : 3; + symbol = 1; + do { GET_BIT(prob + symbol, symbol) } while (symbol < 0x100); + } + else + { + unsigned matchByte = p->dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; + unsigned offs = 0x100; + state -= (state < 10) ? 3 : 6; + symbol = 1; + do + { + unsigned bit; + CLzmaProb *probLit; + matchByte <<= 1; + bit = (matchByte & offs); + probLit = prob + offs + bit + symbol; + GET_BIT2(probLit, symbol, offs &= ~bit, offs &= bit) + } + while (symbol < 0x100); + } + dic[dicPos++] = (Byte)symbol; + processedPos++; + continue; + } + else + { + UPDATE_1(prob); + prob = probs + IsRep + state; + IF_BIT_0(prob) + { + UPDATE_0(prob); + state += kNumStates; + prob = probs + LenCoder; + } + else + { + UPDATE_1(prob); + if (checkDicSize == 0 && processedPos == 0) + return SZ_ERROR_DATA; + prob = probs + IsRepG0 + state; + IF_BIT_0(prob) + { + UPDATE_0(prob); + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; + IF_BIT_0(prob) + { + UPDATE_0(prob); + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; + dicPos++; + processedPos++; + state = state < kNumLitStates ? 9 : 11; + continue; + } + UPDATE_1(prob); + } + else + { + UInt32 distance; + UPDATE_1(prob); + prob = probs + IsRepG1 + state; + IF_BIT_0(prob) + { + UPDATE_0(prob); + distance = rep1; + } + else + { + UPDATE_1(prob); + prob = probs + IsRepG2 + state; + IF_BIT_0(prob) + { + UPDATE_0(prob); + distance = rep2; + } + else + { + UPDATE_1(prob); + distance = rep3; + rep3 = rep2; + } + rep2 = rep1; + } + rep1 = rep0; + rep0 = distance; + } + state = state < kNumLitStates ? 8 : 11; + prob = probs + RepLenCoder; + } + { + unsigned limit, offset; + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0(probLen) + { + UPDATE_0(probLen); + probLen = prob + LenLow + (posState << kLenNumLowBits); + offset = 0; + limit = (1 << kLenNumLowBits); + } + else + { + UPDATE_1(probLen); + probLen = prob + LenChoice2; + IF_BIT_0(probLen) + { + UPDATE_0(probLen); + probLen = prob + LenMid + (posState << kLenNumMidBits); + offset = kLenNumLowSymbols; + limit = (1 << kLenNumMidBits); + } + else + { + UPDATE_1(probLen); + probLen = prob + LenHigh; + offset = kLenNumLowSymbols + kLenNumMidSymbols; + limit = (1 << kLenNumHighBits); + } + } + TREE_DECODE(probLen, limit, len); + len += offset; + } - if (state >= kNumStates) - { - UInt32 distance; - prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); - TREE_6_DECODE(prob, distance); - if (distance >= kStartPosModelIndex) - { - unsigned posSlot = (unsigned)distance; - int numDirectBits = (int)(((distance >> 1) - 1)); - distance = (2 | (distance & 1)); - if (posSlot < kEndPosModelIndex) - { - distance <<= numDirectBits; - prob = probs + SpecPos + distance - posSlot - 1; - { - UInt32 mask = 1; - unsigned i = 1; - do - { - GET_BIT2(prob + i, i, ; , distance |= mask); - mask <<= 1; - } - while (--numDirectBits != 0); - } - } - else - { - numDirectBits -= kNumAlignBits; - do - { - NORMALIZE - range >>= 1; - - { - UInt32 t; - code -= range; - t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */ - distance = (distance << 1) + (t + 1); - code += range & t; - } - /* - distance <<= 1; - if (code >= range) - { - code -= range; - distance |= 1; - } - */ - } - while (--numDirectBits != 0); - prob = probs + Align; - distance <<= kNumAlignBits; - { - unsigned i = 1; - GET_BIT2(prob + i, i, ; , distance |= 1); - GET_BIT2(prob + i, i, ; , distance |= 2); - GET_BIT2(prob + i, i, ; , distance |= 4); - GET_BIT2(prob + i, i, ; , distance |= 8); - } - if (distance == (UInt32)0xFFFFFFFF) - { - len += kMatchSpecLenStart; - state -= kNumStates; - break; - } - } - } - rep3 = rep2; - rep2 = rep1; - rep1 = rep0; - rep0 = distance + 1; - if (checkDicSize == 0) - { - if (distance >= processedPos) - return SZ_ERROR_DATA; - } - else if (distance >= checkDicSize) - return SZ_ERROR_DATA; - state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; - } + if (state >= kNumStates) + { + UInt32 distance; + prob = probs + PosSlot + + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << kNumPosSlotBits); + TREE_6_DECODE(prob, distance); + if (distance >= kStartPosModelIndex) + { + unsigned posSlot = (unsigned)distance; + int numDirectBits = (int)(((distance >> 1) - 1)); + distance = (2 | (distance & 1)); + if (posSlot < kEndPosModelIndex) + { + distance <<= numDirectBits; + prob = probs + SpecPos + distance - posSlot - 1; + { + UInt32 mask = 1; + unsigned i = 1; + do + { + GET_BIT2(prob + i, i, ; , distance |= mask); + mask <<= 1; + } + while (--numDirectBits != 0); + } + } + else + { + numDirectBits -= kNumAlignBits; + do + { + NORMALIZE + range >>= 1; + + { + UInt32 t; + code -= range; + t = (0 - ((UInt32)code >> 31)); /* (UInt32)((Int32)code >> 31) */ + distance = (distance << 1) + (t + 1); + code += range & t; + } + /* + distance <<= 1; + if (code >= range) + { + code -= range; + distance |= 1; + } + */ + } + while (--numDirectBits != 0); + prob = probs + Align; + distance <<= kNumAlignBits; + { + unsigned i = 1; + GET_BIT2(prob + i, i, ; , distance |= 1); + GET_BIT2(prob + i, i, ; , distance |= 2); + GET_BIT2(prob + i, i, ; , distance |= 4); + GET_BIT2(prob + i, i, ; , distance |= 8); + } + if (distance == (UInt32)0xFFFFFFFF) + { + len += kMatchSpecLenStart; + state -= kNumStates; + break; + } + } + } + rep3 = rep2; + rep2 = rep1; + rep1 = rep0; + rep0 = distance + 1; + if (checkDicSize == 0) + { + if (distance >= processedPos) + return SZ_ERROR_DATA; + } + else if (distance >= checkDicSize) + return SZ_ERROR_DATA; + state = (state < kNumStates + kNumLitStates) ? kNumLitStates : kNumLitStates + 3; + } - len += kMatchMinLen; + len += kMatchMinLen; - if (limit == dicPos) - return SZ_ERROR_DATA; - { - SizeT rem = limit - dicPos; - unsigned curLen = ((rem < len) ? (unsigned)rem : len); - SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0); + if (limit == dicPos) + return SZ_ERROR_DATA; + { + SizeT rem = limit - dicPos; + unsigned curLen = ((rem < len) ? (unsigned)rem : len); + SizeT pos = (dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0); - processedPos += curLen; + processedPos += curLen; - len -= curLen; - if (pos + curLen <= dicBufSize) - { - Byte *dest = dic + dicPos; - ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; - const Byte *lim = dest + curLen; - dicPos += curLen; - do - *(dest) = (Byte)*(dest + src); - while (++dest != lim); - } - else - { - do - { - dic[dicPos++] = dic[pos]; - if (++pos == dicBufSize) - pos = 0; - } - while (--curLen != 0); - } - } - } + len -= curLen; + if (pos + curLen <= dicBufSize) + { + Byte *dest = dic + dicPos; + ptrdiff_t src = (ptrdiff_t)pos - (ptrdiff_t)dicPos; + const Byte *lim = dest + curLen; + dicPos += curLen; + do + *(dest) = (Byte)*(dest + src); + while (++dest != lim); + } + else + { + do + { + dic[dicPos++] = dic[pos]; + if (++pos == dicBufSize) + pos = 0; + } + while (--curLen != 0); + } + } + } } while (dicPos < limit && buf < bufLimit); NORMALIZE; @@ -429,25 +429,25 @@ static void MY_FAST_CALL LzmaDec_WriteRem(CLzmaDec *p, SizeT limit) { if (p->remainLen != 0 && p->remainLen < kMatchSpecLenStart) { - Byte *dic = p->dic; - SizeT dicPos = p->dicPos; - SizeT dicBufSize = p->dicBufSize; - unsigned len = p->remainLen; - UInt32 rep0 = p->reps[0]; - if (limit - dicPos < len) - len = (unsigned)(limit - dicPos); + Byte *dic = p->dic; + SizeT dicPos = p->dicPos; + SizeT dicBufSize = p->dicBufSize; + unsigned len = p->remainLen; + UInt32 rep0 = p->reps[0]; + if (limit - dicPos < len) + len = (unsigned)(limit - dicPos); - if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len) - p->checkDicSize = p->prop.dicSize; + if (p->checkDicSize == 0 && p->prop.dicSize - p->processedPos <= len) + p->checkDicSize = p->prop.dicSize; - p->processedPos += len; - p->remainLen -= len; - while (len-- != 0) - { - dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; - dicPos++; - } - p->dicPos = dicPos; + p->processedPos += len; + p->remainLen -= len; + while (len-- != 0) + { + dic[dicPos] = dic[(dicPos - rep0) + ((dicPos < rep0) ? dicBufSize : 0)]; + dicPos++; + } + p->dicPos = dicPos; } } @@ -455,23 +455,23 @@ static int MY_FAST_CALL LzmaDec_DecodeReal2(CLzmaDec *p, SizeT limit, const Byte { do { - SizeT limit2 = limit; - if (p->checkDicSize == 0) - { - UInt32 rem = p->prop.dicSize - p->processedPos; - if (limit - p->dicPos > rem) - limit2 = p->dicPos + rem; - } - RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit)); - if (p->processedPos >= p->prop.dicSize) - p->checkDicSize = p->prop.dicSize; - LzmaDec_WriteRem(p, limit); + SizeT limit2 = limit; + if (p->checkDicSize == 0) + { + UInt32 rem = p->prop.dicSize - p->processedPos; + if (limit - p->dicPos > rem) + limit2 = p->dicPos + rem; + } + RINOK(LzmaDec_DecodeReal(p, limit2, bufLimit)); + if (p->processedPos >= p->prop.dicSize) + p->checkDicSize = p->prop.dicSize; + LzmaDec_WriteRem(p, limit); } while (p->dicPos < limit && p->buf < bufLimit && p->remainLen < kMatchSpecLenStart); if (p->remainLen > kMatchSpecLenStart) { - p->remainLen = kMatchSpecLenStart; + p->remainLen = kMatchSpecLenStart; } return 0; } @@ -494,181 +494,181 @@ static ELzmaDummy LzmaDec_TryDummy(const CLzmaDec *p, const Byte *buf, SizeT inS ELzmaDummy res; { - CLzmaProb *prob; - UInt32 bound; - unsigned ttt; - unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1); + CLzmaProb *prob; + UInt32 bound; + unsigned ttt; + unsigned posState = (p->processedPos) & ((1 << p->prop.pb) - 1); - prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK + prob = probs + IsMatch + (state << kNumPosBitsMax) + posState; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK - /* if (bufLimit - buf >= 7) return DUMMY_LIT; */ + /* if (bufLimit - buf >= 7) return DUMMY_LIT; */ - prob = probs + Literal; - if (p->checkDicSize != 0 || p->processedPos != 0) - prob += (LZMA_LIT_SIZE * - ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) + - (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc)))); + prob = probs + Literal; + if (p->checkDicSize != 0 || p->processedPos != 0) + prob += (LZMA_LIT_SIZE * + ((((p->processedPos) & ((1 << (p->prop.lp)) - 1)) << p->prop.lc) + + (p->dic[(p->dicPos == 0 ? p->dicBufSize : p->dicPos) - 1] >> (8 - p->prop.lc)))); - if (state < kNumLitStates) - { - unsigned symbol = 1; - do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); - } - else - { - unsigned matchByte = p->dic[p->dicPos - p->reps[0] + - ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)]; - unsigned offs = 0x100; - unsigned symbol = 1; - do - { - unsigned bit; - CLzmaProb *probLit; - matchByte <<= 1; - bit = (matchByte & offs); - probLit = prob + offs + bit + symbol; - GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit) - } - while (symbol < 0x100); - } - res = DUMMY_LIT; - } - else - { - unsigned len; - UPDATE_1_CHECK; + if (state < kNumLitStates) + { + unsigned symbol = 1; + do { GET_BIT_CHECK(prob + symbol, symbol) } while (symbol < 0x100); + } + else + { + unsigned matchByte = p->dic[p->dicPos - p->reps[0] + + ((p->dicPos < p->reps[0]) ? p->dicBufSize : 0)]; + unsigned offs = 0x100; + unsigned symbol = 1; + do + { + unsigned bit; + CLzmaProb *probLit; + matchByte <<= 1; + bit = (matchByte & offs); + probLit = prob + offs + bit + symbol; + GET_BIT2_CHECK(probLit, symbol, offs &= ~bit, offs &= bit) + } + while (symbol < 0x100); + } + res = DUMMY_LIT; + } + else + { + unsigned len; + UPDATE_1_CHECK; - prob = probs + IsRep + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - state = 0; - prob = probs + LenCoder; - res = DUMMY_MATCH; - } - else - { - UPDATE_1_CHECK; - res = DUMMY_REP; - prob = probs + IsRepG0 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - NORMALIZE_CHECK; - return DUMMY_REP; - } - else - { - UPDATE_1_CHECK; - } - } - else - { - UPDATE_1_CHECK; - prob = probs + IsRepG1 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - } - else - { - UPDATE_1_CHECK; - prob = probs + IsRepG2 + state; - IF_BIT_0_CHECK(prob) - { - UPDATE_0_CHECK; - } - else - { - UPDATE_1_CHECK; - } - } - } - state = kNumStates; - prob = probs + RepLenCoder; - } - { - unsigned limit, offset; - CLzmaProb *probLen = prob + LenChoice; - IF_BIT_0_CHECK(probLen) - { - UPDATE_0_CHECK; - probLen = prob + LenLow + (posState << kLenNumLowBits); - offset = 0; - limit = 1 << kLenNumLowBits; - } - else - { - UPDATE_1_CHECK; - probLen = prob + LenChoice2; - IF_BIT_0_CHECK(probLen) - { - UPDATE_0_CHECK; - probLen = prob + LenMid + (posState << kLenNumMidBits); - offset = kLenNumLowSymbols; - limit = 1 << kLenNumMidBits; - } - else - { - UPDATE_1_CHECK; - probLen = prob + LenHigh; - offset = kLenNumLowSymbols + kLenNumMidSymbols; - limit = 1 << kLenNumHighBits; - } - } - TREE_DECODE_CHECK(probLen, limit, len); - len += offset; - } + prob = probs + IsRep + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK; + state = 0; + prob = probs + LenCoder; + res = DUMMY_MATCH; + } + else + { + UPDATE_1_CHECK; + res = DUMMY_REP; + prob = probs + IsRepG0 + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK; + prob = probs + IsRep0Long + (state << kNumPosBitsMax) + posState; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK; + NORMALIZE_CHECK; + return DUMMY_REP; + } + else + { + UPDATE_1_CHECK; + } + } + else + { + UPDATE_1_CHECK; + prob = probs + IsRepG1 + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK; + } + else + { + UPDATE_1_CHECK; + prob = probs + IsRepG2 + state; + IF_BIT_0_CHECK(prob) + { + UPDATE_0_CHECK; + } + else + { + UPDATE_1_CHECK; + } + } + } + state = kNumStates; + prob = probs + RepLenCoder; + } + { + unsigned limit, offset; + CLzmaProb *probLen = prob + LenChoice; + IF_BIT_0_CHECK(probLen) + { + UPDATE_0_CHECK; + probLen = prob + LenLow + (posState << kLenNumLowBits); + offset = 0; + limit = 1 << kLenNumLowBits; + } + else + { + UPDATE_1_CHECK; + probLen = prob + LenChoice2; + IF_BIT_0_CHECK(probLen) + { + UPDATE_0_CHECK; + probLen = prob + LenMid + (posState << kLenNumMidBits); + offset = kLenNumLowSymbols; + limit = 1 << kLenNumMidBits; + } + else + { + UPDATE_1_CHECK; + probLen = prob + LenHigh; + offset = kLenNumLowSymbols + kLenNumMidSymbols; + limit = 1 << kLenNumHighBits; + } + } + TREE_DECODE_CHECK(probLen, limit, len); + len += offset; + } - if (state < 4) - { - unsigned posSlot; - prob = probs + PosSlot + - ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << - kNumPosSlotBits); - TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); - if (posSlot >= kStartPosModelIndex) - { - int numDirectBits = ((posSlot >> 1) - 1); + if (state < 4) + { + unsigned posSlot; + prob = probs + PosSlot + + ((len < kNumLenToPosStates ? len : kNumLenToPosStates - 1) << + kNumPosSlotBits); + TREE_DECODE_CHECK(prob, 1 << kNumPosSlotBits, posSlot); + if (posSlot >= kStartPosModelIndex) + { + int numDirectBits = ((posSlot >> 1) - 1); - /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */ + /* if (bufLimit - buf >= 8) return DUMMY_MATCH; */ - if (posSlot < kEndPosModelIndex) - { - prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1; - } - else - { - numDirectBits -= kNumAlignBits; - do - { - NORMALIZE_CHECK - range >>= 1; - code -= range & (((code - range) >> 31) - 1); - /* if (code >= range) code -= range; */ - } - while (--numDirectBits != 0); - prob = probs + Align; - numDirectBits = kNumAlignBits; - } - { - unsigned i = 1; - do - { - GET_BIT_CHECK(prob + i, i); - } - while (--numDirectBits != 0); - } - } - } - } + if (posSlot < kEndPosModelIndex) + { + prob = probs + SpecPos + ((2 | (posSlot & 1)) << numDirectBits) - posSlot - 1; + } + else + { + numDirectBits -= kNumAlignBits; + do + { + NORMALIZE_CHECK + range >>= 1; + code -= range & (((code - range) >> 31) - 1); + /* if (code >= range) code -= range; */ + } + while (--numDirectBits != 0); + prob = probs + Align; + numDirectBits = kNumAlignBits; + } + { + unsigned i = 1; + do + { + GET_BIT_CHECK(prob + i, i); + } + while (--numDirectBits != 0); + } + } + } + } } NORMALIZE_CHECK; return res; @@ -690,12 +690,12 @@ void LzmaDec_InitDicAndState(CLzmaDec *p, Bool initDic, Bool initState) if (initDic) { - p->processedPos = 0; - p->checkDicSize = 0; - p->needInitState = 1; + p->processedPos = 0; + p->checkDicSize = 0; + p->needInitState = 1; } if (initState) - p->needInitState = 1; + p->needInitState = 1; } void LzmaDec_Init(CLzmaDec *p) @@ -710,14 +710,14 @@ static void LzmaDec_InitStateReal(CLzmaDec *p) UInt32 i; CLzmaProb *probs = p->probs; for (i = 0; i < numProbs; i++) - probs[i] = kBitModelTotal >> 1; + probs[i] = kBitModelTotal >> 1; p->reps[0] = p->reps[1] = p->reps[2] = p->reps[3] = 1; p->state = 0; p->needInitState = 0; } SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *srcLen, - ELzmaFinishMode finishMode, ELzmaStatus *status) + ELzmaFinishMode finishMode, ELzmaStatus *status) { SizeT inSize = *srcLen; (*srcLen) = 0; @@ -727,113 +727,113 @@ SRes LzmaDec_DecodeToDic(CLzmaDec *p, SizeT dicLimit, const Byte *src, SizeT *sr while (p->remainLen != kMatchSpecLenStart) { - int checkEndMarkNow; + int checkEndMarkNow; - if (p->needFlush != 0) - { - for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) - p->tempBuf[p->tempBufSize++] = *src++; - if (p->tempBufSize < RC_INIT_SIZE) - { - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (p->tempBuf[0] != 0) - return SZ_ERROR_DATA; + if (p->needFlush != 0) + { + for (; inSize > 0 && p->tempBufSize < RC_INIT_SIZE; (*srcLen)++, inSize--) + p->tempBuf[p->tempBufSize++] = *src++; + if (p->tempBufSize < RC_INIT_SIZE) + { + *status = LZMA_STATUS_NEEDS_MORE_INPUT; + return SZ_OK; + } + if (p->tempBuf[0] != 0) + return SZ_ERROR_DATA; - LzmaDec_InitRc(p, p->tempBuf); - p->tempBufSize = 0; - } + LzmaDec_InitRc(p, p->tempBuf); + p->tempBufSize = 0; + } - checkEndMarkNow = 0; - if (p->dicPos >= dicLimit) - { - if (p->remainLen == 0 && p->code == 0) - { - *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; - return SZ_OK; - } - if (finishMode == LZMA_FINISH_ANY) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_OK; - } - if (p->remainLen != 0) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - checkEndMarkNow = 1; - } + checkEndMarkNow = 0; + if (p->dicPos >= dicLimit) + { + if (p->remainLen == 0 && p->code == 0) + { + *status = LZMA_STATUS_MAYBE_FINISHED_WITHOUT_MARK; + return SZ_OK; + } + if (finishMode == LZMA_FINISH_ANY) + { + *status = LZMA_STATUS_NOT_FINISHED; + return SZ_OK; + } + if (p->remainLen != 0) + { + *status = LZMA_STATUS_NOT_FINISHED; + return SZ_ERROR_DATA; + } + checkEndMarkNow = 1; + } - if (p->needInitState) - LzmaDec_InitStateReal(p); + if (p->needInitState) + LzmaDec_InitStateReal(p); - if (p->tempBufSize == 0) - { - SizeT processed; - const Byte *bufLimit; - if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, src, inSize); - if (dummyRes == DUMMY_ERROR) - { - memcpy(p->tempBuf, src, inSize); - p->tempBufSize = (unsigned)inSize; - (*srcLen) += inSize; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - bufLimit = src; - } - else - bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; - p->buf = src; - if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0) - return SZ_ERROR_DATA; - processed = (SizeT)(p->buf - src); - (*srcLen) += processed; - src += processed; - inSize -= processed; - } - else - { - unsigned rem = p->tempBufSize, lookAhead = 0; - while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) - p->tempBuf[rem++] = src[lookAhead++]; - p->tempBufSize = rem; - if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) - { - int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem); - if (dummyRes == DUMMY_ERROR) - { - (*srcLen) += lookAhead; - *status = LZMA_STATUS_NEEDS_MORE_INPUT; - return SZ_OK; - } - if (checkEndMarkNow && dummyRes != DUMMY_MATCH) - { - *status = LZMA_STATUS_NOT_FINISHED; - return SZ_ERROR_DATA; - } - } - p->buf = p->tempBuf; - if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0) - return SZ_ERROR_DATA; - lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf)); - (*srcLen) += lookAhead; - src += lookAhead; - inSize -= lookAhead; - p->tempBufSize = 0; - } + if (p->tempBufSize == 0) + { + SizeT processed; + const Byte *bufLimit; + if (inSize < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) + { + int dummyRes = LzmaDec_TryDummy(p, src, inSize); + if (dummyRes == DUMMY_ERROR) + { + memcpy(p->tempBuf, src, inSize); + p->tempBufSize = (unsigned)inSize; + (*srcLen) += inSize; + *status = LZMA_STATUS_NEEDS_MORE_INPUT; + return SZ_OK; + } + if (checkEndMarkNow && dummyRes != DUMMY_MATCH) + { + *status = LZMA_STATUS_NOT_FINISHED; + return SZ_ERROR_DATA; + } + bufLimit = src; + } + else + bufLimit = src + inSize - LZMA_REQUIRED_INPUT_MAX; + p->buf = src; + if (LzmaDec_DecodeReal2(p, dicLimit, bufLimit) != 0) + return SZ_ERROR_DATA; + processed = (SizeT)(p->buf - src); + (*srcLen) += processed; + src += processed; + inSize -= processed; + } + else + { + unsigned rem = p->tempBufSize, lookAhead = 0; + while (rem < LZMA_REQUIRED_INPUT_MAX && lookAhead < inSize) + p->tempBuf[rem++] = src[lookAhead++]; + p->tempBufSize = rem; + if (rem < LZMA_REQUIRED_INPUT_MAX || checkEndMarkNow) + { + int dummyRes = LzmaDec_TryDummy(p, p->tempBuf, rem); + if (dummyRes == DUMMY_ERROR) + { + (*srcLen) += lookAhead; + *status = LZMA_STATUS_NEEDS_MORE_INPUT; + return SZ_OK; + } + if (checkEndMarkNow && dummyRes != DUMMY_MATCH) + { + *status = LZMA_STATUS_NOT_FINISHED; + return SZ_ERROR_DATA; + } + } + p->buf = p->tempBuf; + if (LzmaDec_DecodeReal2(p, dicLimit, p->buf) != 0) + return SZ_ERROR_DATA; + lookAhead -= (rem - (unsigned)(p->buf - p->tempBuf)); + (*srcLen) += lookAhead; + src += lookAhead; + inSize -= lookAhead; + p->tempBufSize = 0; + } } if (p->code == 0) - *status = LZMA_STATUS_FINISHED_WITH_MARK; + *status = LZMA_STATUS_FINISHED_WITH_MARK; return (p->code == 0) ? SZ_OK : SZ_ERROR_DATA; } @@ -844,36 +844,36 @@ SRes LzmaDec_DecodeToBuf(CLzmaDec *p, Byte *dest, SizeT *destLen, const Byte *sr *srcLen = *destLen = 0; for (;;) { - SizeT inSizeCur = inSize, outSizeCur, dicPos; - ELzmaFinishMode curFinishMode; - SRes res; - if (p->dicPos == p->dicBufSize) - p->dicPos = 0; - dicPos = p->dicPos; - if (outSize > p->dicBufSize - dicPos) - { - outSizeCur = p->dicBufSize; - curFinishMode = LZMA_FINISH_ANY; - } - else - { - outSizeCur = dicPos + outSize; - curFinishMode = finishMode; - } + SizeT inSizeCur = inSize, outSizeCur, dicPos; + ELzmaFinishMode curFinishMode; + SRes res; + if (p->dicPos == p->dicBufSize) + p->dicPos = 0; + dicPos = p->dicPos; + if (outSize > p->dicBufSize - dicPos) + { + outSizeCur = p->dicBufSize; + curFinishMode = LZMA_FINISH_ANY; + } + else + { + outSizeCur = dicPos + outSize; + curFinishMode = finishMode; + } - res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); - src += inSizeCur; - inSize -= inSizeCur; - *srcLen += inSizeCur; - outSizeCur = p->dicPos - dicPos; - memcpy(dest, p->dic + dicPos, outSizeCur); - dest += outSizeCur; - outSize -= outSizeCur; - *destLen += outSizeCur; - if (res != 0) - return res; - if (outSizeCur == 0 || outSize == 0) - return SZ_OK; + res = LzmaDec_DecodeToDic(p, outSizeCur, src, &inSizeCur, curFinishMode, status); + src += inSizeCur; + inSize -= inSizeCur; + *srcLen += inSizeCur; + outSizeCur = p->dicPos - dicPos; + memcpy(dest, p->dic + dicPos, outSizeCur); + dest += outSizeCur; + outSize -= outSizeCur; + *destLen += outSizeCur; + if (res != 0) + return res; + if (outSizeCur == 0 || outSize == 0) + return SZ_OK; } } @@ -901,17 +901,17 @@ SRes LzmaProps_Decode(CLzmaProps *p, const Byte *data, unsigned size) Byte d; if (size < LZMA_PROPS_SIZE) - return SZ_ERROR_UNSUPPORTED; + return SZ_ERROR_UNSUPPORTED; else - dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24); + dicSize = data[1] | ((UInt32)data[2] << 8) | ((UInt32)data[3] << 16) | ((UInt32)data[4] << 24); if (dicSize < LZMA_DIC_MIN) - dicSize = LZMA_DIC_MIN; + dicSize = LZMA_DIC_MIN; p->dicSize = dicSize; d = data[0]; if (d >= (9 * 5 * 5)) - return SZ_ERROR_UNSUPPORTED; + return SZ_ERROR_UNSUPPORTED; p->lc = d % 9; d /= 9; @@ -926,11 +926,11 @@ static SRes LzmaDec_AllocateProbs2(CLzmaDec *p, const CLzmaProps *propNew, ISzAl UInt32 numProbs = LzmaProps_GetNumProbs(propNew); if (p->probs == 0 || numProbs != p->numProbs) { - LzmaDec_FreeProbs(p, alloc); - p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb)); - p->numProbs = numProbs; - if (p->probs == 0) - return SZ_ERROR_MEM; + LzmaDec_FreeProbs(p, alloc); + p->probs = (CLzmaProb *)alloc->Alloc(alloc, numProbs * sizeof(CLzmaProb)); + p->numProbs = numProbs; + if (p->probs == 0) + return SZ_ERROR_MEM; } return SZ_OK; } @@ -953,13 +953,13 @@ SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAll dicBufSize = propNew.dicSize; if (p->dic == 0 || dicBufSize != p->dicBufSize) { - LzmaDec_FreeDict(p, alloc); - p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize); - if (p->dic == 0) - { - LzmaDec_FreeProbs(p, alloc); - return SZ_ERROR_MEM; - } + LzmaDec_FreeDict(p, alloc); + p->dic = (Byte *)alloc->Alloc(alloc, dicBufSize); + if (p->dic == 0) + { + LzmaDec_FreeProbs(p, alloc); + return SZ_ERROR_MEM; + } } p->dicBufSize = dicBufSize; p->prop = propNew; @@ -967,8 +967,8 @@ SRes LzmaDec_Allocate(CLzmaDec *p, const Byte *props, unsigned propsSize, ISzAll } SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, - const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, - ELzmaStatus *status, ISzAlloc *alloc) + const Byte *propData, unsigned propSize, ELzmaFinishMode finishMode, + ELzmaStatus *status, ISzAlloc *alloc) { CLzmaDec p; SRes res; @@ -976,12 +976,12 @@ SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, SizeT outSize = *destLen; *srcLen = *destLen = 0; if (inSize < RC_INIT_SIZE) - return SZ_ERROR_INPUT_EOF; + return SZ_ERROR_INPUT_EOF; LzmaDec_Construct(&p); res = LzmaDec_AllocateProbs(&p, propData, propSize, alloc); if (res != 0) - return res; + return res; p.dic = dest; p.dicBufSize = outSize; @@ -991,7 +991,7 @@ SRes LzmaDecode(Byte *dest, SizeT *destLen, const Byte *src, SizeT *srcLen, res = LzmaDec_DecodeToDic(&p, outSize, src, srcLen, finishMode, status); if (res == SZ_OK && *status == LZMA_STATUS_NEEDS_MORE_INPUT) - res = SZ_ERROR_INPUT_EOF; + res = SZ_ERROR_INPUT_EOF; (*destLen) = p.dicPos; LzmaDec_FreeProbs(&p, alloc); diff --git a/LZMA/SDK/C/LzmaEnc.c b/LZMA/SDK/C/LzmaEnc.c index 95e7891..3caff35 100644 --- a/LZMA/SDK/C/LzmaEnc.c +++ b/LZMA/SDK/C/LzmaEnc.c @@ -65,12 +65,12 @@ void LzmaEncProps_Normalize(CLzmaEncProps *p) if (p->numHashBytes < 0) p->numHashBytes = 4; if (p->mc == 0) p->mc = (16 + (p->fb >> 1)) >> (p->btMode ? 0 : 1); if (p->numThreads < 0) - p->numThreads = - #ifndef _7ZIP_ST - ((p->btMode && p->algo) ? 2 : 1); - #else - 1; - #endif + p->numThreads = + #ifndef _7ZIP_ST + ((p->btMode && p->algo) ? 2 : 1); + #else + 1; + #endif } UInt32 LzmaEncProps_GetDictSize(const CLzmaEncProps *props2) @@ -112,10 +112,10 @@ void LzmaEnc_FastPosInit(Byte *g_FastPos) for (slotFast = 2; slotFast < kNumLogBits * 2; slotFast++) { - UInt32 k = (1 << ((slotFast >> 1) - 1)); - UInt32 j; - for (j = 0; j < k; j++, c++) - g_FastPos[c] = (Byte)slotFast; + UInt32 k = (1 << ((slotFast >> 1) - 1)); + UInt32 j; + for (j = 0; j < k; j++, c++) + g_FastPos[c] = (Byte)slotFast; } } @@ -347,11 +347,11 @@ void LzmaEnc_SaveState(CLzmaEncHandle pp) for (i = 0; i < kNumStates; i++) { - memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); - memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); } for (i = 0; i < kNumLenToPosStates; i++) - memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); memcpy(dest->isRep, p->isRep, sizeof(p->isRep)); memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0)); memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1)); @@ -373,11 +373,11 @@ void LzmaEnc_RestoreState(CLzmaEncHandle pp) for (i = 0; i < kNumStates; i++) { - memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); - memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); + memcpy(dest->isMatch[i], p->isMatch[i], sizeof(p->isMatch[i])); + memcpy(dest->isRep0Long[i], p->isRep0Long[i], sizeof(p->isRep0Long[i])); } for (i = 0; i < kNumLenToPosStates; i++) - memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); + memcpy(dest->posSlotEncoder[i], p->posSlotEncoder[i], sizeof(p->posSlotEncoder[i])); memcpy(dest->isRep, p->isRep, sizeof(p->isRep)); memcpy(dest->isRepG0, p->isRepG0, sizeof(p->isRepG0)); memcpy(dest->isRepG1, p->isRepG1, sizeof(p->isRepG1)); @@ -395,17 +395,17 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) LzmaEncProps_Normalize(&props); if (props.lc > LZMA_LC_MAX || props.lp > LZMA_LP_MAX || props.pb > LZMA_PB_MAX || - props.dictSize > ((UInt32)1 << kDicLogSizeMaxCompress) || props.dictSize > ((UInt32)1 << 30)) - return SZ_ERROR_PARAM; + props.dictSize > ((UInt32)1 << kDicLogSizeMaxCompress) || props.dictSize > ((UInt32)1 << 30)) + return SZ_ERROR_PARAM; p->dictSize = props.dictSize; p->matchFinderCycles = props.mc; { - unsigned fb = props.fb; - if (fb < 5) - fb = 5; - if (fb > LZMA_MATCH_LEN_MAX) - fb = LZMA_MATCH_LEN_MAX; - p->numFastBytes = fb; + unsigned fb = props.fb; + if (fb < 5) + fb = 5; + if (fb > LZMA_MATCH_LEN_MAX) + fb = LZMA_MATCH_LEN_MAX; + p->numFastBytes = fb; } p->lc = props.lc; p->lp = props.lp; @@ -413,15 +413,15 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) p->fastMode = (props.algo == 0); p->matchFinderBase.btMode = props.btMode; { - UInt32 numHashBytes = 4; - if (props.btMode) - { - if (props.numHashBytes < 2) - numHashBytes = 2; - else if (props.numHashBytes < 4) - numHashBytes = props.numHashBytes; - } - p->matchFinderBase.numHashBytes = numHashBytes; + UInt32 numHashBytes = 4; + if (props.btMode) + { + if (props.numHashBytes < 2) + numHashBytes = 2; + else if (props.numHashBytes < 4) + numHashBytes = props.numHashBytes; + } + p->matchFinderBase.numHashBytes = numHashBytes; } p->matchFinderBase.cutValue = props.mc; @@ -432,8 +432,8 @@ SRes LzmaEnc_SetProps(CLzmaEncHandle pp, const CLzmaEncProps *props2) /* if (newMultiThread != _multiThread) { - ReleaseMatchFinder(); - _multiThread = newMultiThread; + ReleaseMatchFinder(); + _multiThread = newMultiThread; } */ p->multiThread = (props.numThreads > 1); @@ -466,10 +466,10 @@ static int RangeEnc_Alloc(CRangeEnc *p, ISzAlloc *alloc) { if (p->bufBase == 0) { - p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE); - if (p->bufBase == 0) - return 0; - p->bufLim = p->bufBase + RC_BUF_SIZE; + p->bufBase = (Byte *)alloc->Alloc(alloc, RC_BUF_SIZE); + if (p->bufBase == 0) + return 0; + p->bufLim = p->bufBase + RC_BUF_SIZE; } return 1; } @@ -498,10 +498,10 @@ static void RangeEnc_FlushStream(CRangeEnc *p) { size_t num; if (p->res != SZ_OK) - return; + return; num = p->buf - p->bufBase; if (num != p->outStream->Write(p->outStream, p->bufBase, num)) - p->res = SZ_ERROR_WRITE; + p->res = SZ_ERROR_WRITE; p->processed += num; p->buf = p->bufBase; } @@ -510,18 +510,18 @@ static void MY_FAST_CALL RangeEnc_ShiftLow(CRangeEnc *p) { if ((UInt32)p->low < (UInt32)0xFF000000 || (int)(p->low >> 32) != 0) { - Byte temp = p->cache; - do - { - Byte *buf = p->buf; - *buf++ = (Byte)(temp + (Byte)(p->low >> 32)); - p->buf = buf; - if (buf == p->bufLim) - RangeEnc_FlushStream(p); - temp = 0xFF; - } - while (--p->cacheSize != 0); - p->cache = (Byte)((UInt32)p->low >> 24); + Byte temp = p->cache; + do + { + Byte *buf = p->buf; + *buf++ = (Byte)(temp + (Byte)(p->low >> 32)); + p->buf = buf; + if (buf == p->bufLim) + RangeEnc_FlushStream(p); + temp = 0xFF; + } + while (--p->cacheSize != 0); + p->cache = (Byte)((UInt32)p->low >> 24); } p->cacheSize++; p->low = (UInt32)p->low << 8; @@ -531,20 +531,20 @@ static void RangeEnc_FlushData(CRangeEnc *p) { int i; for (i = 0; i < 5; i++) - RangeEnc_ShiftLow(p); + RangeEnc_ShiftLow(p); } static void RangeEnc_EncodeDirectBits(CRangeEnc *p, UInt32 value, int numBits) { do { - p->range >>= 1; - p->low += p->range & (0 - ((value >> --numBits) & 1)); - if (p->range < kTopValue) - { - p->range <<= 8; - RangeEnc_ShiftLow(p); - } + p->range >>= 1; + p->low += p->range & (0 - ((value >> --numBits) & 1)); + if (p->range < kTopValue) + { + p->range <<= 8; + RangeEnc_ShiftLow(p); + } } while (numBits != 0); } @@ -555,20 +555,20 @@ static void RangeEnc_EncodeBit(CRangeEnc *p, CLzmaProb *prob, UInt32 symbol) UInt32 newBound = (p->range >> kNumBitModelTotalBits) * ttt; if (symbol == 0) { - p->range = newBound; - ttt += (kBitModelTotal - ttt) >> kNumMoveBits; + p->range = newBound; + ttt += (kBitModelTotal - ttt) >> kNumMoveBits; } else { - p->low += newBound; - p->range -= newBound; - ttt -= ttt >> kNumMoveBits; + p->low += newBound; + p->range -= newBound; + ttt -= ttt >> kNumMoveBits; } *prob = (CLzmaProb)ttt; if (p->range < kTopValue) { - p->range <<= 8; - RangeEnc_ShiftLow(p); + p->range <<= 8; + RangeEnc_ShiftLow(p); } } @@ -577,8 +577,8 @@ static void LitEnc_Encode(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol) symbol |= 0x100; do { - RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1); - symbol <<= 1; + RangeEnc_EncodeBit(p, probs + (symbol >> 8), (symbol >> 7) & 1); + symbol <<= 1; } while (symbol < 0x10000); } @@ -589,10 +589,10 @@ static void LitEnc_EncodeMatched(CRangeEnc *p, CLzmaProb *probs, UInt32 symbol, symbol |= 0x100; do { - matchByte <<= 1; - RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1); - symbol <<= 1; - offs &= ~(matchByte ^ symbol); + matchByte <<= 1; + RangeEnc_EncodeBit(p, probs + (offs + (matchByte & offs) + (symbol >> 8)), (symbol >> 7) & 1); + symbol <<= 1; + offs &= ~(matchByte ^ symbol); } while (symbol < 0x10000); } @@ -602,21 +602,21 @@ void LzmaEnc_InitPriceTables(UInt32 *ProbPrices) UInt32 i; for (i = (1 << kNumMoveReducingBits) / 2; i < kBitModelTotal; i += (1 << kNumMoveReducingBits)) { - const int kCyclesBits = kNumBitPriceShiftBits; - UInt32 w = i; - UInt32 bitCount = 0; - int j; - for (j = 0; j < kCyclesBits; j++) - { - w = w * w; - bitCount <<= 1; - while (w >= ((UInt32)1 << 16)) - { - w >>= 1; - bitCount++; - } - } - ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount); + const int kCyclesBits = kNumBitPriceShiftBits; + UInt32 w = i; + UInt32 bitCount = 0; + int j; + for (j = 0; j < kCyclesBits; j++) + { + w = w * w; + bitCount <<= 1; + while (w >= ((UInt32)1 << 16)) + { + w >>= 1; + bitCount++; + } + } + ProbPrices[i >> kNumMoveReducingBits] = ((kNumBitModelTotalBits << kCyclesBits) - 15 - bitCount); } } @@ -639,8 +639,8 @@ static UInt32 LitEnc_GetPrice(const CLzmaProb *probs, UInt32 symbol, UInt32 *Pro symbol |= 0x100; do { - price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1); - symbol <<= 1; + price += GET_PRICEa(probs[symbol >> 8], (symbol >> 7) & 1); + symbol <<= 1; } while (symbol < 0x10000); return price; @@ -653,10 +653,10 @@ static UInt32 LitEnc_GetPriceMatched(const CLzmaProb *probs, UInt32 symbol, UInt symbol |= 0x100; do { - matchByte <<= 1; - price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1); - symbol <<= 1; - offs &= ~(matchByte ^ symbol); + matchByte <<= 1; + price += GET_PRICEa(probs[offs + (matchByte & offs) + (symbol >> 8)], (symbol >> 7) & 1); + symbol <<= 1; + offs &= ~(matchByte ^ symbol); } while (symbol < 0x10000); return price; @@ -669,11 +669,11 @@ static void RcTree_Encode(CRangeEnc *rc, CLzmaProb *probs, int numBitLevels, UIn int i; for (i = numBitLevels; i != 0;) { - UInt32 bit; - i--; - bit = (symbol >> i) & 1; - RangeEnc_EncodeBit(rc, probs + m, bit); - m = (m << 1) | bit; + UInt32 bit; + i--; + bit = (symbol >> i) & 1; + RangeEnc_EncodeBit(rc, probs + m, bit); + m = (m << 1) | bit; } } @@ -683,10 +683,10 @@ static void RcTree_ReverseEncode(CRangeEnc *rc, CLzmaProb *probs, int numBitLeve int i; for (i = 0; i < numBitLevels; i++) { - UInt32 bit = symbol & 1; - RangeEnc_EncodeBit(rc, probs + m, bit); - m = (m << 1) | bit; - symbol >>= 1; + UInt32 bit = symbol & 1; + RangeEnc_EncodeBit(rc, probs + m, bit); + m = (m << 1) | bit; + symbol >>= 1; } } @@ -696,8 +696,8 @@ static UInt32 RcTree_GetPrice(const CLzmaProb *probs, int numBitLevels, UInt32 s symbol |= (1 << numBitLevels); while (symbol != 1) { - price += GET_PRICEa(probs[symbol >> 1], symbol & 1); - symbol >>= 1; + price += GET_PRICEa(probs[symbol >> 1], symbol & 1); + symbol >>= 1; } return price; } @@ -709,10 +709,10 @@ static UInt32 RcTree_ReverseGetPrice(const CLzmaProb *probs, int numBitLevels, U int i; for (i = numBitLevels; i != 0; i--) { - UInt32 bit = symbol & 1; - symbol >>= 1; - price += GET_PRICEa(probs[m], bit); - m = (m << 1) | bit; + UInt32 bit = symbol & 1; + symbol >>= 1; + price += GET_PRICEa(probs[m], bit); + m = (m << 1) | bit; } return price; } @@ -723,33 +723,33 @@ static void LenEnc_Init(CLenEnc *p) unsigned i; p->choice = p->choice2 = kProbInitValue; for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumLowBits); i++) - p->low[i] = kProbInitValue; + p->low[i] = kProbInitValue; for (i = 0; i < (LZMA_NUM_PB_STATES_MAX << kLenNumMidBits); i++) - p->mid[i] = kProbInitValue; + p->mid[i] = kProbInitValue; for (i = 0; i < kLenNumHighSymbols; i++) - p->high[i] = kProbInitValue; + p->high[i] = kProbInitValue; } static void LenEnc_Encode(CLenEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState) { if (symbol < kLenNumLowSymbols) { - RangeEnc_EncodeBit(rc, &p->choice, 0); - RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol); + RangeEnc_EncodeBit(rc, &p->choice, 0); + RcTree_Encode(rc, p->low + (posState << kLenNumLowBits), kLenNumLowBits, symbol); } else { - RangeEnc_EncodeBit(rc, &p->choice, 1); - if (symbol < kLenNumLowSymbols + kLenNumMidSymbols) - { - RangeEnc_EncodeBit(rc, &p->choice2, 0); - RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols); - } - else - { - RangeEnc_EncodeBit(rc, &p->choice2, 1); - RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols); - } + RangeEnc_EncodeBit(rc, &p->choice, 1); + if (symbol < kLenNumLowSymbols + kLenNumMidSymbols) + { + RangeEnc_EncodeBit(rc, &p->choice2, 0); + RcTree_Encode(rc, p->mid + (posState << kLenNumMidBits), kLenNumMidBits, symbol - kLenNumLowSymbols); + } + else + { + RangeEnc_EncodeBit(rc, &p->choice2, 1); + RcTree_Encode(rc, p->high, kLenNumHighBits, symbol - kLenNumLowSymbols - kLenNumMidSymbols); + } } } @@ -762,18 +762,18 @@ static void LenEnc_SetPrices(CLenEnc *p, UInt32 posState, UInt32 numSymbols, UIn UInt32 i = 0; for (i = 0; i < kLenNumLowSymbols; i++) { - if (i >= numSymbols) - return; - prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices); + if (i >= numSymbols) + return; + prices[i] = a0 + RcTree_GetPrice(p->low + (posState << kLenNumLowBits), kLenNumLowBits, i, ProbPrices); } for (; i < kLenNumLowSymbols + kLenNumMidSymbols; i++) { - if (i >= numSymbols) - return; - prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices); + if (i >= numSymbols) + return; + prices[i] = b0 + RcTree_GetPrice(p->mid + (posState << kLenNumMidBits), kLenNumMidBits, i - kLenNumLowSymbols, ProbPrices); } for (; i < numSymbols; i++) - prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices); + prices[i] = b1 + RcTree_GetPrice(p->high, kLenNumHighBits, i - kLenNumLowSymbols - kLenNumMidSymbols, ProbPrices); } static void MY_FAST_CALL LenPriceEnc_UpdateTable(CLenPriceEnc *p, UInt32 posState, UInt32 *ProbPrices) @@ -786,15 +786,15 @@ static void LenPriceEnc_UpdateTables(CLenPriceEnc *p, UInt32 numPosStates, UInt3 { UInt32 posState; for (posState = 0; posState < numPosStates; posState++) - LenPriceEnc_UpdateTable(p, posState, ProbPrices); + LenPriceEnc_UpdateTable(p, posState, ProbPrices); } static void LenEnc_Encode2(CLenPriceEnc *p, CRangeEnc *rc, UInt32 symbol, UInt32 posState, Bool updatePrice, UInt32 *ProbPrices) { LenEnc_Encode(&p->p, rc, symbol, posState); if (updatePrice) - if (--p->counters[posState] == 0) - LenPriceEnc_UpdateTable(p, posState, ProbPrices); + if (--p->counters[posState] == 0) + LenPriceEnc_UpdateTable(p, posState, ProbPrices); } @@ -808,8 +808,8 @@ static void MovePos(CLzmaEnc *p, UInt32 num) #endif if (num != 0) { - p->additionalOffset += num; - p->matchFinder.Skip(p->matchFinderObj, num); + p->additionalOffset += num; + p->matchFinder.Skip(p->matchFinderObj, num); } } @@ -822,26 +822,26 @@ static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes) printf("\n i = %d numPairs = %d ", ttt, numPairs / 2); ttt++; { - UInt32 i; - for (i = 0; i < numPairs; i += 2) - printf("%2d %6d | ", p->matches[i], p->matches[i + 1]); + UInt32 i; + for (i = 0; i < numPairs; i += 2) + printf("%2d %6d | ", p->matches[i], p->matches[i + 1]); } #endif if (numPairs > 0) { - lenRes = p->matches[numPairs - 2]; - if (lenRes == p->numFastBytes) - { - const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - UInt32 distance = p->matches[numPairs - 1] + 1; - UInt32 numAvail = p->numAvail; - if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; - { - const Byte *pby2 = pby - distance; - for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++); - } - } + lenRes = p->matches[numPairs - 2]; + if (lenRes == p->numFastBytes) + { + const Byte *pby = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; + UInt32 distance = p->matches[numPairs - 1] + 1; + UInt32 numAvail = p->numAvail; + if (numAvail > LZMA_MATCH_LEN_MAX) + numAvail = LZMA_MATCH_LEN_MAX; + { + const Byte *pby2 = pby - distance; + for (; lenRes < numAvail && pby[lenRes] == pby2[lenRes]; lenRes++); + } + } } p->additionalOffset++; *numDistancePairsRes = numPairs; @@ -856,8 +856,8 @@ static UInt32 ReadMatchDistances(CLzmaEnc *p, UInt32 *numDistancePairsRes) static UInt32 GetRepLen1Price(CLzmaEnc *p, UInt32 state, UInt32 posState) { return - GET_PRICE_0(p->isRepG0[state]) + - GET_PRICE_0(p->isRep0Long[state][posState]); + GET_PRICE_0(p->isRepG0[state]) + + GET_PRICE_0(p->isRep0Long[state][posState]); } static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 posState) @@ -865,19 +865,19 @@ static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 UInt32 price; if (repIndex == 0) { - price = GET_PRICE_0(p->isRepG0[state]); - price += GET_PRICE_1(p->isRep0Long[state][posState]); + price = GET_PRICE_0(p->isRepG0[state]); + price += GET_PRICE_1(p->isRep0Long[state][posState]); } else { - price = GET_PRICE_1(p->isRepG0[state]); - if (repIndex == 1) - price += GET_PRICE_0(p->isRepG1[state]); - else - { - price += GET_PRICE_1(p->isRepG1[state]); - price += GET_PRICE(p->isRepG2[state], repIndex - 2); - } + price = GET_PRICE_1(p->isRepG0[state]); + if (repIndex == 1) + price += GET_PRICE_0(p->isRepG1[state]); + else + { + price += GET_PRICE_1(p->isRepG1[state]); + price += GET_PRICE(p->isRepG2[state], repIndex - 2); + } } return price; } @@ -885,7 +885,7 @@ static UInt32 GetPureRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 state, UInt32 static UInt32 GetRepPrice(CLzmaEnc *p, UInt32 repIndex, UInt32 len, UInt32 state, UInt32 posState) { return p->repLenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN] + - GetPureRepPrice(p, repIndex, state, posState); + GetPureRepPrice(p, repIndex, state, posState); } static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur) @@ -895,28 +895,28 @@ static UInt32 Backward(CLzmaEnc *p, UInt32 *backRes, UInt32 cur) p->optimumEndIndex = cur; do { - if (p->opt[cur].prev1IsChar) - { - MakeAsChar(&p->opt[posMem]) - p->opt[posMem].posPrev = posMem - 1; - if (p->opt[cur].prev2) - { - p->opt[posMem - 1].prev1IsChar = False; - p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2; - p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2; - } - } - { - UInt32 posPrev = posMem; - UInt32 backCur = backMem; - - backMem = p->opt[posPrev].backPrev; - posMem = p->opt[posPrev].posPrev; - - p->opt[posPrev].backPrev = backCur; - p->opt[posPrev].posPrev = cur; - cur = posPrev; - } + if (p->opt[cur].prev1IsChar) + { + MakeAsChar(&p->opt[posMem]) + p->opt[posMem].posPrev = posMem - 1; + if (p->opt[cur].prev2) + { + p->opt[posMem - 1].prev1IsChar = False; + p->opt[posMem - 1].posPrev = p->opt[cur].posPrev2; + p->opt[posMem - 1].backPrev = p->opt[cur].backPrev2; + } + } + { + UInt32 posPrev = posMem; + UInt32 backCur = backMem; + + backMem = p->opt[posPrev].backPrev; + posMem = p->opt[posPrev].posPrev; + + p->opt[posPrev].backPrev = backCur; + p->opt[posPrev].posPrev = cur; + cur = posPrev; + } } while (cur != 0); *backRes = p->opt[0].backPrev; @@ -936,72 +936,72 @@ static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes) Byte curByte, matchByte; if (p->optimumEndIndex != p->optimumCurrentIndex) { - const COptimal *opt = &p->opt[p->optimumCurrentIndex]; - UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex; - *backRes = opt->backPrev; - p->optimumCurrentIndex = opt->posPrev; - return lenRes; + const COptimal *opt = &p->opt[p->optimumCurrentIndex]; + UInt32 lenRes = opt->posPrev - p->optimumCurrentIndex; + *backRes = opt->backPrev; + p->optimumCurrentIndex = opt->posPrev; + return lenRes; } p->optimumCurrentIndex = p->optimumEndIndex = 0; if (p->additionalOffset == 0) - mainLen = ReadMatchDistances(p, &numPairs); + mainLen = ReadMatchDistances(p, &numPairs); else { - mainLen = p->longestMatchLength; - numPairs = p->numPairs; + mainLen = p->longestMatchLength; + numPairs = p->numPairs; } numAvail = p->numAvail; if (numAvail < 2) { - *backRes = (UInt32)(-1); - return 1; + *backRes = (UInt32)(-1); + return 1; } if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; + numAvail = LZMA_MATCH_LEN_MAX; data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; repMaxIndex = 0; for (i = 0; i < LZMA_NUM_REPS; i++) { - UInt32 lenTest; - const Byte *data2; - reps[i] = p->reps[i]; - data2 = data - (reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - { - repLens[i] = 0; - continue; - } - for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); - repLens[i] = lenTest; - if (lenTest > repLens[repMaxIndex]) - repMaxIndex = i; + UInt32 lenTest; + const Byte *data2; + reps[i] = p->reps[i]; + data2 = data - (reps[i] + 1); + if (data[0] != data2[0] || data[1] != data2[1]) + { + repLens[i] = 0; + continue; + } + for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); + repLens[i] = lenTest; + if (lenTest > repLens[repMaxIndex]) + repMaxIndex = i; } if (repLens[repMaxIndex] >= p->numFastBytes) { - UInt32 lenRes; - *backRes = repMaxIndex; - lenRes = repLens[repMaxIndex]; - MovePos(p, lenRes - 1); - return lenRes; + UInt32 lenRes; + *backRes = repMaxIndex; + lenRes = repLens[repMaxIndex]; + MovePos(p, lenRes - 1); + return lenRes; } matches = p->matches; if (mainLen >= p->numFastBytes) { - *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; - MovePos(p, mainLen - 1); - return mainLen; + *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; + MovePos(p, mainLen - 1); + return mainLen; } curByte = *data; matchByte = *(data - (reps[0] + 1)); if (mainLen < 2 && curByte != matchByte && repLens[repMaxIndex] < 2) { - *backRes = (UInt32)-1; - return 1; + *backRes = (UInt32)-1; + return 1; } p->opt[0].state = (CState)p->state; @@ -1009,11 +1009,11 @@ static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes) posState = (position & p->pbMask); { - const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); - p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) + - (!IsCharState(p->state) ? - LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : - LitEnc_GetPrice(probs, curByte, p->ProbPrices)); + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); + p->opt[1].price = GET_PRICE_0(p->isMatch[p->state][posState]) + + (!IsCharState(p->state) ? + LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : + LitEnc_GetPrice(probs, curByte, p->ProbPrices)); } MakeAsChar(&p->opt[1]); @@ -1023,50 +1023,50 @@ static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes) if (matchByte == curByte) { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState); - if (shortRepPrice < p->opt[1].price) - { - p->opt[1].price = shortRepPrice; - MakeAsShortRep(&p->opt[1]); - } + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, p->state, posState); + if (shortRepPrice < p->opt[1].price) + { + p->opt[1].price = shortRepPrice; + MakeAsShortRep(&p->opt[1]); + } } lenEnd = ((mainLen >= repLens[repMaxIndex]) ? mainLen : repLens[repMaxIndex]); if (lenEnd < 2) { - *backRes = p->opt[1].backPrev; - return 1; + *backRes = p->opt[1].backPrev; + return 1; } p->opt[1].posPrev = 0; for (i = 0; i < LZMA_NUM_REPS; i++) - p->opt[0].backs[i] = reps[i]; + p->opt[0].backs[i] = reps[i]; len = lenEnd; do - p->opt[len--].price = kInfinityPrice; + p->opt[len--].price = kInfinityPrice; while (len >= 2); for (i = 0; i < LZMA_NUM_REPS; i++) { - UInt32 repLen = repLens[i]; - UInt32 price; - if (repLen < 2) - continue; - price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState); - do - { - UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2]; - COptimal *opt = &p->opt[repLen]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = 0; - opt->backPrev = i; - opt->prev1IsChar = False; - } - } - while (--repLen >= 2); + UInt32 repLen = repLens[i]; + UInt32 price; + if (repLen < 2) + continue; + price = repMatchPrice + GetPureRepPrice(p, i, p->state, posState); + do + { + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][repLen - 2]; + COptimal *opt = &p->opt[repLen]; + if (curAndLenPrice < opt->price) + { + opt->price = curAndLenPrice; + opt->posPrev = 0; + opt->backPrev = i; + opt->prev1IsChar = False; + } + } + while (--repLen >= 2); } normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[p->state]); @@ -1074,413 +1074,413 @@ static UInt32 GetOptimum(CLzmaEnc *p, UInt32 position, UInt32 *backRes) len = ((repLens[0] >= 2) ? repLens[0] + 1 : 2); if (len <= mainLen) { - UInt32 offs = 0; - while (len > matches[offs]) - offs += 2; - for (; ; len++) - { - COptimal *opt; - UInt32 distance = matches[offs + 1]; + UInt32 offs = 0; + while (len > matches[offs]) + offs += 2; + for (; ; len++) + { + COptimal *opt; + UInt32 distance = matches[offs + 1]; - UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN]; - UInt32 lenToPosState = GetLenToPosState(len); - if (distance < kNumFullDistances) - curAndLenPrice += p->distancesPrices[lenToPosState][distance]; - else - { - UInt32 slot; - GetPosSlot2(distance, slot); - curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot]; - } - opt = &p->opt[len]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = 0; - opt->backPrev = distance + LZMA_NUM_REPS; - opt->prev1IsChar = False; - } - if (len == matches[offs]) - { - offs += 2; - if (offs == numPairs) - break; - } - } + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][len - LZMA_MATCH_LEN_MIN]; + UInt32 lenToPosState = GetLenToPosState(len); + if (distance < kNumFullDistances) + curAndLenPrice += p->distancesPrices[lenToPosState][distance]; + else + { + UInt32 slot; + GetPosSlot2(distance, slot); + curAndLenPrice += p->alignPrices[distance & kAlignMask] + p->posSlotPrices[lenToPosState][slot]; + } + opt = &p->opt[len]; + if (curAndLenPrice < opt->price) + { + opt->price = curAndLenPrice; + opt->posPrev = 0; + opt->backPrev = distance + LZMA_NUM_REPS; + opt->prev1IsChar = False; + } + if (len == matches[offs]) + { + offs += 2; + if (offs == numPairs) + break; + } + } } cur = 0; - #ifdef SHOW_STAT2 - if (position >= 0) - { - unsigned i; - printf("\n pos = %4X", position); - for (i = cur; i <= lenEnd; i++) - printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price); - } - #endif + #ifdef SHOW_STAT2 + if (position >= 0) + { + unsigned i; + printf("\n pos = %4X", position); + for (i = cur; i <= lenEnd; i++) + printf("\nprice[%4X] = %d", position - cur + i, p->opt[i].price); + } + #endif for (;;) { - UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen; - UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice; - Bool nextIsChar; - Byte curByte, matchByte; - const Byte *data; - COptimal *curOpt; - COptimal *nextOpt; + UInt32 numAvailFull, newLen, numPairs, posPrev, state, posState, startLen; + UInt32 curPrice, curAnd1Price, matchPrice, repMatchPrice; + Bool nextIsChar; + Byte curByte, matchByte; + const Byte *data; + COptimal *curOpt; + COptimal *nextOpt; - cur++; - if (cur == lenEnd) - return Backward(p, backRes, cur); + cur++; + if (cur == lenEnd) + return Backward(p, backRes, cur); - newLen = ReadMatchDistances(p, &numPairs); - if (newLen >= p->numFastBytes) - { - p->numPairs = numPairs; - p->longestMatchLength = newLen; - return Backward(p, backRes, cur); - } - position++; - curOpt = &p->opt[cur]; - posPrev = curOpt->posPrev; - if (curOpt->prev1IsChar) - { - posPrev--; - if (curOpt->prev2) - { - state = p->opt[curOpt->posPrev2].state; - if (curOpt->backPrev2 < LZMA_NUM_REPS) - state = kRepNextStates[state]; - else - state = kMatchNextStates[state]; - } - else - state = p->opt[posPrev].state; - state = kLiteralNextStates[state]; - } - else - state = p->opt[posPrev].state; - if (posPrev == cur - 1) - { - if (IsShortRep(curOpt)) - state = kShortRepNextStates[state]; - else - state = kLiteralNextStates[state]; - } - else - { - UInt32 pos; - const COptimal *prevOpt; - if (curOpt->prev1IsChar && curOpt->prev2) - { - posPrev = curOpt->posPrev2; - pos = curOpt->backPrev2; - state = kRepNextStates[state]; - } - else - { - pos = curOpt->backPrev; - if (pos < LZMA_NUM_REPS) - state = kRepNextStates[state]; - else - state = kMatchNextStates[state]; - } - prevOpt = &p->opt[posPrev]; - if (pos < LZMA_NUM_REPS) - { - UInt32 i; - reps[0] = prevOpt->backs[pos]; - for (i = 1; i <= pos; i++) - reps[i] = prevOpt->backs[i - 1]; - for (; i < LZMA_NUM_REPS; i++) - reps[i] = prevOpt->backs[i]; - } - else - { - UInt32 i; - reps[0] = (pos - LZMA_NUM_REPS); - for (i = 1; i < LZMA_NUM_REPS; i++) - reps[i] = prevOpt->backs[i - 1]; - } - } - curOpt->state = (CState)state; + newLen = ReadMatchDistances(p, &numPairs); + if (newLen >= p->numFastBytes) + { + p->numPairs = numPairs; + p->longestMatchLength = newLen; + return Backward(p, backRes, cur); + } + position++; + curOpt = &p->opt[cur]; + posPrev = curOpt->posPrev; + if (curOpt->prev1IsChar) + { + posPrev--; + if (curOpt->prev2) + { + state = p->opt[curOpt->posPrev2].state; + if (curOpt->backPrev2 < LZMA_NUM_REPS) + state = kRepNextStates[state]; + else + state = kMatchNextStates[state]; + } + else + state = p->opt[posPrev].state; + state = kLiteralNextStates[state]; + } + else + state = p->opt[posPrev].state; + if (posPrev == cur - 1) + { + if (IsShortRep(curOpt)) + state = kShortRepNextStates[state]; + else + state = kLiteralNextStates[state]; + } + else + { + UInt32 pos; + const COptimal *prevOpt; + if (curOpt->prev1IsChar && curOpt->prev2) + { + posPrev = curOpt->posPrev2; + pos = curOpt->backPrev2; + state = kRepNextStates[state]; + } + else + { + pos = curOpt->backPrev; + if (pos < LZMA_NUM_REPS) + state = kRepNextStates[state]; + else + state = kMatchNextStates[state]; + } + prevOpt = &p->opt[posPrev]; + if (pos < LZMA_NUM_REPS) + { + UInt32 i; + reps[0] = prevOpt->backs[pos]; + for (i = 1; i <= pos; i++) + reps[i] = prevOpt->backs[i - 1]; + for (; i < LZMA_NUM_REPS; i++) + reps[i] = prevOpt->backs[i]; + } + else + { + UInt32 i; + reps[0] = (pos - LZMA_NUM_REPS); + for (i = 1; i < LZMA_NUM_REPS; i++) + reps[i] = prevOpt->backs[i - 1]; + } + } + curOpt->state = (CState)state; - curOpt->backs[0] = reps[0]; - curOpt->backs[1] = reps[1]; - curOpt->backs[2] = reps[2]; - curOpt->backs[3] = reps[3]; + curOpt->backs[0] = reps[0]; + curOpt->backs[1] = reps[1]; + curOpt->backs[2] = reps[2]; + curOpt->backs[3] = reps[3]; - curPrice = curOpt->price; - nextIsChar = False; - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; - curByte = *data; - matchByte = *(data - (reps[0] + 1)); + curPrice = curOpt->price; + nextIsChar = False; + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; + curByte = *data; + matchByte = *(data - (reps[0] + 1)); - posState = (position & p->pbMask); + posState = (position & p->pbMask); - curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]); - { - const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); - curAnd1Price += - (!IsCharState(state) ? - LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : - LitEnc_GetPrice(probs, curByte, p->ProbPrices)); - } + curAnd1Price = curPrice + GET_PRICE_0(p->isMatch[state][posState]); + { + const CLzmaProb *probs = LIT_PROBS(position, *(data - 1)); + curAnd1Price += + (!IsCharState(state) ? + LitEnc_GetPriceMatched(probs, curByte, matchByte, p->ProbPrices) : + LitEnc_GetPrice(probs, curByte, p->ProbPrices)); + } - nextOpt = &p->opt[cur + 1]; + nextOpt = &p->opt[cur + 1]; - if (curAnd1Price < nextOpt->price) - { - nextOpt->price = curAnd1Price; - nextOpt->posPrev = cur; - MakeAsChar(nextOpt); - nextIsChar = True; - } + if (curAnd1Price < nextOpt->price) + { + nextOpt->price = curAnd1Price; + nextOpt->posPrev = cur; + MakeAsChar(nextOpt); + nextIsChar = True; + } - matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]); - repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]); - - if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0)) - { - UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState); - if (shortRepPrice <= nextOpt->price) - { - nextOpt->price = shortRepPrice; - nextOpt->posPrev = cur; - MakeAsShortRep(nextOpt); - nextIsChar = True; - } - } - numAvailFull = p->numAvail; - { - UInt32 temp = kNumOpts - 1 - cur; - if (temp < numAvailFull) - numAvailFull = temp; - } + matchPrice = curPrice + GET_PRICE_1(p->isMatch[state][posState]); + repMatchPrice = matchPrice + GET_PRICE_1(p->isRep[state]); + + if (matchByte == curByte && !(nextOpt->posPrev < cur && nextOpt->backPrev == 0)) + { + UInt32 shortRepPrice = repMatchPrice + GetRepLen1Price(p, state, posState); + if (shortRepPrice <= nextOpt->price) + { + nextOpt->price = shortRepPrice; + nextOpt->posPrev = cur; + MakeAsShortRep(nextOpt); + nextIsChar = True; + } + } + numAvailFull = p->numAvail; + { + UInt32 temp = kNumOpts - 1 - cur; + if (temp < numAvailFull) + numAvailFull = temp; + } - if (numAvailFull < 2) - continue; - numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes); + if (numAvailFull < 2) + continue; + numAvail = (numAvailFull <= p->numFastBytes ? numAvailFull : p->numFastBytes); - if (!nextIsChar && matchByte != curByte) /* speed optimization */ - { - /* try Literal + rep0 */ - UInt32 temp; - UInt32 lenTest2; - const Byte *data2 = data - (reps[0] + 1); - UInt32 limit = p->numFastBytes + 1; - if (limit > numAvailFull) - limit = numAvailFull; + if (!nextIsChar && matchByte != curByte) /* speed optimization */ + { + /* try Literal + rep0 */ + UInt32 temp; + UInt32 lenTest2; + const Byte *data2 = data - (reps[0] + 1); + UInt32 limit = p->numFastBytes + 1; + if (limit > numAvailFull) + limit = numAvailFull; - for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++); - lenTest2 = temp - 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kLiteralNextStates[state]; - UInt32 posStateNext = (position + 1) & p->pbMask; - UInt32 nextRepMatchPrice = curAnd1Price + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 curAndLenPrice; - COptimal *opt; - UInt32 offset = cur + 1 + lenTest2; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = False; - } - } - } - } - - startLen = 2; /* speed optimization */ - { - UInt32 repIndex; - for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++) - { - UInt32 lenTest; - UInt32 lenTestTemp; - UInt32 price; - const Byte *data2 = data - (reps[repIndex] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); - while (lenEnd < cur + lenTest) - p->opt[++lenEnd].price = kInfinityPrice; - lenTestTemp = lenTest; - price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState); - do - { - UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2]; - COptimal *opt = &p->opt[cur + lenTest]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur; - opt->backPrev = repIndex; - opt->prev1IsChar = False; - } - } - while (--lenTest >= 2); - lenTest = lenTestTemp; - - if (repIndex == 0) - startLen = lenTest + 1; - - /* if (_maxMode) */ - { - UInt32 lenTest2 = lenTest + 1; - UInt32 limit = lenTest2 + p->numFastBytes; - UInt32 nextRepMatchPrice; - if (limit > numAvailFull) - limit = numAvailFull; - for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); - lenTest2 -= lenTest + 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kRepNextStates[state]; - UInt32 posStateNext = (position + lenTest) & p->pbMask; - UInt32 curAndLenCharPrice = - price + p->repLenEnc.prices[posState][lenTest - 2] + - GET_PRICE_0(p->isMatch[state2][posStateNext]) + - LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), - data[lenTest], data2[lenTest], p->ProbPrices); - state2 = kLiteralNextStates[state2]; - posStateNext = (position + lenTest + 1) & p->pbMask; - nextRepMatchPrice = curAndLenCharPrice + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 curAndLenPrice; - COptimal *opt; - UInt32 offset = cur + lenTest + 1 + lenTest2; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + lenTest + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = True; - opt->posPrev2 = cur; - opt->backPrev2 = repIndex; - } - } - } - } - } - } - /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */ - if (newLen > numAvail) - { - newLen = numAvail; - for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2); - matches[numPairs] = newLen; - numPairs += 2; - } - if (newLen >= startLen) - { - UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]); - UInt32 offs, curBack, posSlot; - UInt32 lenTest; - while (lenEnd < cur + newLen) - p->opt[++lenEnd].price = kInfinityPrice; + for (temp = 1; temp < limit && data[temp] == data2[temp]; temp++); + lenTest2 = temp - 1; + if (lenTest2 >= 2) + { + UInt32 state2 = kLiteralNextStates[state]; + UInt32 posStateNext = (position + 1) & p->pbMask; + UInt32 nextRepMatchPrice = curAnd1Price + + GET_PRICE_1(p->isMatch[state2][posStateNext]) + + GET_PRICE_1(p->isRep[state2]); + /* for (; lenTest2 >= 2; lenTest2--) */ + { + UInt32 curAndLenPrice; + COptimal *opt; + UInt32 offset = cur + 1 + lenTest2; + while (lenEnd < offset) + p->opt[++lenEnd].price = kInfinityPrice; + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); + opt = &p->opt[offset]; + if (curAndLenPrice < opt->price) + { + opt->price = curAndLenPrice; + opt->posPrev = cur + 1; + opt->backPrev = 0; + opt->prev1IsChar = True; + opt->prev2 = False; + } + } + } + } + + startLen = 2; /* speed optimization */ + { + UInt32 repIndex; + for (repIndex = 0; repIndex < LZMA_NUM_REPS; repIndex++) + { + UInt32 lenTest; + UInt32 lenTestTemp; + UInt32 price; + const Byte *data2 = data - (reps[repIndex] + 1); + if (data[0] != data2[0] || data[1] != data2[1]) + continue; + for (lenTest = 2; lenTest < numAvail && data[lenTest] == data2[lenTest]; lenTest++); + while (lenEnd < cur + lenTest) + p->opt[++lenEnd].price = kInfinityPrice; + lenTestTemp = lenTest; + price = repMatchPrice + GetPureRepPrice(p, repIndex, state, posState); + do + { + UInt32 curAndLenPrice = price + p->repLenEnc.prices[posState][lenTest - 2]; + COptimal *opt = &p->opt[cur + lenTest]; + if (curAndLenPrice < opt->price) + { + opt->price = curAndLenPrice; + opt->posPrev = cur; + opt->backPrev = repIndex; + opt->prev1IsChar = False; + } + } + while (--lenTest >= 2); + lenTest = lenTestTemp; + + if (repIndex == 0) + startLen = lenTest + 1; + + /* if (_maxMode) */ + { + UInt32 lenTest2 = lenTest + 1; + UInt32 limit = lenTest2 + p->numFastBytes; + UInt32 nextRepMatchPrice; + if (limit > numAvailFull) + limit = numAvailFull; + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); + lenTest2 -= lenTest + 1; + if (lenTest2 >= 2) + { + UInt32 state2 = kRepNextStates[state]; + UInt32 posStateNext = (position + lenTest) & p->pbMask; + UInt32 curAndLenCharPrice = + price + p->repLenEnc.prices[posState][lenTest - 2] + + GET_PRICE_0(p->isMatch[state2][posStateNext]) + + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), + data[lenTest], data2[lenTest], p->ProbPrices); + state2 = kLiteralNextStates[state2]; + posStateNext = (position + lenTest + 1) & p->pbMask; + nextRepMatchPrice = curAndLenCharPrice + + GET_PRICE_1(p->isMatch[state2][posStateNext]) + + GET_PRICE_1(p->isRep[state2]); + + /* for (; lenTest2 >= 2; lenTest2--) */ + { + UInt32 curAndLenPrice; + COptimal *opt; + UInt32 offset = cur + lenTest + 1 + lenTest2; + while (lenEnd < offset) + p->opt[++lenEnd].price = kInfinityPrice; + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); + opt = &p->opt[offset]; + if (curAndLenPrice < opt->price) + { + opt->price = curAndLenPrice; + opt->posPrev = cur + lenTest + 1; + opt->backPrev = 0; + opt->prev1IsChar = True; + opt->prev2 = True; + opt->posPrev2 = cur; + opt->backPrev2 = repIndex; + } + } + } + } + } + } + /* for (UInt32 lenTest = 2; lenTest <= newLen; lenTest++) */ + if (newLen > numAvail) + { + newLen = numAvail; + for (numPairs = 0; newLen > matches[numPairs]; numPairs += 2); + matches[numPairs] = newLen; + numPairs += 2; + } + if (newLen >= startLen) + { + UInt32 normalMatchPrice = matchPrice + GET_PRICE_0(p->isRep[state]); + UInt32 offs, curBack, posSlot; + UInt32 lenTest; + while (lenEnd < cur + newLen) + p->opt[++lenEnd].price = kInfinityPrice; - offs = 0; - while (startLen > matches[offs]) - offs += 2; - curBack = matches[offs + 1]; - GetPosSlot2(curBack, posSlot); - for (lenTest = /*2*/ startLen; ; lenTest++) - { - UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN]; - UInt32 lenToPosState = GetLenToPosState(lenTest); - COptimal *opt; - if (curBack < kNumFullDistances) - curAndLenPrice += p->distancesPrices[lenToPosState][curBack]; - else - curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask]; - - opt = &p->opt[cur + lenTest]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur; - opt->backPrev = curBack + LZMA_NUM_REPS; - opt->prev1IsChar = False; - } + offs = 0; + while (startLen > matches[offs]) + offs += 2; + curBack = matches[offs + 1]; + GetPosSlot2(curBack, posSlot); + for (lenTest = /*2*/ startLen; ; lenTest++) + { + UInt32 curAndLenPrice = normalMatchPrice + p->lenEnc.prices[posState][lenTest - LZMA_MATCH_LEN_MIN]; + UInt32 lenToPosState = GetLenToPosState(lenTest); + COptimal *opt; + if (curBack < kNumFullDistances) + curAndLenPrice += p->distancesPrices[lenToPosState][curBack]; + else + curAndLenPrice += p->posSlotPrices[lenToPosState][posSlot] + p->alignPrices[curBack & kAlignMask]; + + opt = &p->opt[cur + lenTest]; + if (curAndLenPrice < opt->price) + { + opt->price = curAndLenPrice; + opt->posPrev = cur; + opt->backPrev = curBack + LZMA_NUM_REPS; + opt->prev1IsChar = False; + } - if (/*_maxMode && */lenTest == matches[offs]) - { - /* Try Match + Literal + Rep0 */ - const Byte *data2 = data - (curBack + 1); - UInt32 lenTest2 = lenTest + 1; - UInt32 limit = lenTest2 + p->numFastBytes; - UInt32 nextRepMatchPrice; - if (limit > numAvailFull) - limit = numAvailFull; - for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); - lenTest2 -= lenTest + 1; - if (lenTest2 >= 2) - { - UInt32 state2 = kMatchNextStates[state]; - UInt32 posStateNext = (position + lenTest) & p->pbMask; - UInt32 curAndLenCharPrice = curAndLenPrice + - GET_PRICE_0(p->isMatch[state2][posStateNext]) + - LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), - data[lenTest], data2[lenTest], p->ProbPrices); - state2 = kLiteralNextStates[state2]; - posStateNext = (posStateNext + 1) & p->pbMask; - nextRepMatchPrice = curAndLenCharPrice + - GET_PRICE_1(p->isMatch[state2][posStateNext]) + - GET_PRICE_1(p->isRep[state2]); - - /* for (; lenTest2 >= 2; lenTest2--) */ - { - UInt32 offset = cur + lenTest + 1 + lenTest2; - UInt32 curAndLenPrice; - COptimal *opt; - while (lenEnd < offset) - p->opt[++lenEnd].price = kInfinityPrice; - curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); - opt = &p->opt[offset]; - if (curAndLenPrice < opt->price) - { - opt->price = curAndLenPrice; - opt->posPrev = cur + lenTest + 1; - opt->backPrev = 0; - opt->prev1IsChar = True; - opt->prev2 = True; - opt->posPrev2 = cur; - opt->backPrev2 = curBack + LZMA_NUM_REPS; - } - } - } - offs += 2; - if (offs == numPairs) - break; - curBack = matches[offs + 1]; - if (curBack >= kNumFullDistances) - GetPosSlot2(curBack, posSlot); - } - } - } + if (/*_maxMode && */lenTest == matches[offs]) + { + /* Try Match + Literal + Rep0 */ + const Byte *data2 = data - (curBack + 1); + UInt32 lenTest2 = lenTest + 1; + UInt32 limit = lenTest2 + p->numFastBytes; + UInt32 nextRepMatchPrice; + if (limit > numAvailFull) + limit = numAvailFull; + for (; lenTest2 < limit && data[lenTest2] == data2[lenTest2]; lenTest2++); + lenTest2 -= lenTest + 1; + if (lenTest2 >= 2) + { + UInt32 state2 = kMatchNextStates[state]; + UInt32 posStateNext = (position + lenTest) & p->pbMask; + UInt32 curAndLenCharPrice = curAndLenPrice + + GET_PRICE_0(p->isMatch[state2][posStateNext]) + + LitEnc_GetPriceMatched(LIT_PROBS(position + lenTest, data[lenTest - 1]), + data[lenTest], data2[lenTest], p->ProbPrices); + state2 = kLiteralNextStates[state2]; + posStateNext = (posStateNext + 1) & p->pbMask; + nextRepMatchPrice = curAndLenCharPrice + + GET_PRICE_1(p->isMatch[state2][posStateNext]) + + GET_PRICE_1(p->isRep[state2]); + + /* for (; lenTest2 >= 2; lenTest2--) */ + { + UInt32 offset = cur + lenTest + 1 + lenTest2; + UInt32 curAndLenPrice; + COptimal *opt; + while (lenEnd < offset) + p->opt[++lenEnd].price = kInfinityPrice; + curAndLenPrice = nextRepMatchPrice + GetRepPrice(p, 0, lenTest2, state2, posStateNext); + opt = &p->opt[offset]; + if (curAndLenPrice < opt->price) + { + opt->price = curAndLenPrice; + opt->posPrev = cur + lenTest + 1; + opt->backPrev = 0; + opt->prev1IsChar = True; + opt->prev2 = True; + opt->posPrev2 = cur; + opt->backPrev2 = curBack + LZMA_NUM_REPS; + } + } + } + offs += 2; + if (offs == numPairs) + break; + curBack = matches[offs + 1]; + if (curBack >= kNumFullDistances) + GetPosSlot2(curBack, posSlot); + } + } + } } } @@ -1493,101 +1493,101 @@ static UInt32 GetOptimumFast(CLzmaEnc *p, UInt32 *backRes) const UInt32 *matches; if (p->additionalOffset == 0) - mainLen = ReadMatchDistances(p, &numPairs); + mainLen = ReadMatchDistances(p, &numPairs); else { - mainLen = p->longestMatchLength; - numPairs = p->numPairs; + mainLen = p->longestMatchLength; + numPairs = p->numPairs; } numAvail = p->numAvail; *backRes = (UInt32)-1; if (numAvail < 2) - return 1; + return 1; if (numAvail > LZMA_MATCH_LEN_MAX) - numAvail = LZMA_MATCH_LEN_MAX; + numAvail = LZMA_MATCH_LEN_MAX; data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; repLen = repIndex = 0; for (i = 0; i < LZMA_NUM_REPS; i++) { - UInt32 len; - const Byte *data2 = data - (p->reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - for (len = 2; len < numAvail && data[len] == data2[len]; len++); - if (len >= p->numFastBytes) - { - *backRes = i; - MovePos(p, len - 1); - return len; - } - if (len > repLen) - { - repIndex = i; - repLen = len; - } + UInt32 len; + const Byte *data2 = data - (p->reps[i] + 1); + if (data[0] != data2[0] || data[1] != data2[1]) + continue; + for (len = 2; len < numAvail && data[len] == data2[len]; len++); + if (len >= p->numFastBytes) + { + *backRes = i; + MovePos(p, len - 1); + return len; + } + if (len > repLen) + { + repIndex = i; + repLen = len; + } } matches = p->matches; if (mainLen >= p->numFastBytes) { - *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; - MovePos(p, mainLen - 1); - return mainLen; + *backRes = matches[numPairs - 1] + LZMA_NUM_REPS; + MovePos(p, mainLen - 1); + return mainLen; } mainDist = 0; /* for GCC */ if (mainLen >= 2) { - mainDist = matches[numPairs - 1]; - while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1) - { - if (!ChangePair(matches[numPairs - 3], mainDist)) - break; - numPairs -= 2; - mainLen = matches[numPairs - 2]; - mainDist = matches[numPairs - 1]; - } - if (mainLen == 2 && mainDist >= 0x80) - mainLen = 1; + mainDist = matches[numPairs - 1]; + while (numPairs > 2 && mainLen == matches[numPairs - 4] + 1) + { + if (!ChangePair(matches[numPairs - 3], mainDist)) + break; + numPairs -= 2; + mainLen = matches[numPairs - 2]; + mainDist = matches[numPairs - 1]; + } + if (mainLen == 2 && mainDist >= 0x80) + mainLen = 1; } if (repLen >= 2 && ( - (repLen + 1 >= mainLen) || - (repLen + 2 >= mainLen && mainDist >= (1 << 9)) || - (repLen + 3 >= mainLen && mainDist >= (1 << 15)))) + (repLen + 1 >= mainLen) || + (repLen + 2 >= mainLen && mainDist >= (1 << 9)) || + (repLen + 3 >= mainLen && mainDist >= (1 << 15)))) { - *backRes = repIndex; - MovePos(p, repLen - 1); - return repLen; + *backRes = repIndex; + MovePos(p, repLen - 1); + return repLen; } if (mainLen < 2 || numAvail <= 2) - return 1; + return 1; p->longestMatchLength = ReadMatchDistances(p, &p->numPairs); if (p->longestMatchLength >= 2) { - UInt32 newDistance = matches[p->numPairs - 1]; - if ((p->longestMatchLength >= mainLen && newDistance < mainDist) || - (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) || - (p->longestMatchLength > mainLen + 1) || - (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist))) - return 1; + UInt32 newDistance = matches[p->numPairs - 1]; + if ((p->longestMatchLength >= mainLen && newDistance < mainDist) || + (p->longestMatchLength == mainLen + 1 && !ChangePair(mainDist, newDistance)) || + (p->longestMatchLength > mainLen + 1) || + (p->longestMatchLength + 1 >= mainLen && mainLen >= 3 && ChangePair(newDistance, mainDist))) + return 1; } data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - 1; for (i = 0; i < LZMA_NUM_REPS; i++) { - UInt32 len, limit; - const Byte *data2 = data - (p->reps[i] + 1); - if (data[0] != data2[0] || data[1] != data2[1]) - continue; - limit = mainLen - 1; - for (len = 2; len < limit && data[len] == data2[len]; len++); - if (len >= limit) - return 1; + UInt32 len, limit; + const Byte *data2 = data - (p->reps[i] + 1); + if (data[0] != data2[0] || data[1] != data2[1]) + continue; + limit = mainLen - 1; + for (len = 2; len < limit && data[len] == data2[len]; len++); + if (len >= limit) + return 1; } *backRes = mainDist + LZMA_NUM_REPS; MovePos(p, mainLen - 2); @@ -1610,13 +1610,13 @@ static void WriteEndMarker(CLzmaEnc *p, UInt32 posState) static SRes CheckErrors(CLzmaEnc *p) { if (p->result != SZ_OK) - return p->result; + return p->result; if (p->rc.res != SZ_OK) - p->result = SZ_ERROR_WRITE; + p->result = SZ_ERROR_WRITE; if (p->matchFinderBase.result != SZ_OK) - p->result = SZ_ERROR_READ; + p->result = SZ_ERROR_READ; if (p->result != SZ_OK) - p->finished = True; + p->finished = True; return p->result; } @@ -1625,7 +1625,7 @@ static SRes Flush(CLzmaEnc *p, UInt32 nowPos) /* ReleaseMFStream(); */ p->finished = True; if (p->writeEndMark) - WriteEndMarker(p, nowPos & p->pbMask); + WriteEndMarker(p, nowPos & p->pbMask); RangeEnc_FlushData(&p->rc); RangeEnc_FlushStream(&p->rc); return CheckErrors(p); @@ -1635,7 +1635,7 @@ static void FillAlignPrices(CLzmaEnc *p) { UInt32 i; for (i = 0; i < kAlignTableSize; i++) - p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices); + p->alignPrices[i] = RcTree_ReverseGetPrice(p->posAlignEncoder, kNumAlignBits, i, p->ProbPrices); p->alignPriceCount = 0; } @@ -1645,30 +1645,30 @@ static void FillDistancesPrices(CLzmaEnc *p) UInt32 i, lenToPosState; for (i = kStartPosModelIndex; i < kNumFullDistances; i++) { - UInt32 posSlot = GetPosSlot1(i); - UInt32 footerBits = ((posSlot >> 1) - 1); - UInt32 base = ((2 | (posSlot & 1)) << footerBits); - tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices); + UInt32 posSlot = GetPosSlot1(i); + UInt32 footerBits = ((posSlot >> 1) - 1); + UInt32 base = ((2 | (posSlot & 1)) << footerBits); + tempPrices[i] = RcTree_ReverseGetPrice(p->posEncoders + base - posSlot - 1, footerBits, i - base, p->ProbPrices); } for (lenToPosState = 0; lenToPosState < kNumLenToPosStates; lenToPosState++) { - UInt32 posSlot; - const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState]; - UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState]; - for (posSlot = 0; posSlot < p->distTableSize; posSlot++) - posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices); - for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++) - posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits); + UInt32 posSlot; + const CLzmaProb *encoder = p->posSlotEncoder[lenToPosState]; + UInt32 *posSlotPrices = p->posSlotPrices[lenToPosState]; + for (posSlot = 0; posSlot < p->distTableSize; posSlot++) + posSlotPrices[posSlot] = RcTree_GetPrice(encoder, kNumPosSlotBits, posSlot, p->ProbPrices); + for (posSlot = kEndPosModelIndex; posSlot < p->distTableSize; posSlot++) + posSlotPrices[posSlot] += ((((posSlot >> 1) - 1) - kNumAlignBits) << kNumBitPriceShiftBits); - { - UInt32 *distancesPrices = p->distancesPrices[lenToPosState]; - UInt32 i; - for (i = 0; i < kStartPosModelIndex; i++) - distancesPrices[i] = posSlotPrices[i]; - for (; i < kNumFullDistances; i++) - distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i]; - } + { + UInt32 *distancesPrices = p->distancesPrices[lenToPosState]; + UInt32 i; + for (i = 0; i < kStartPosModelIndex; i++) + distancesPrices[i] = posSlotPrices[i]; + for (; i < kNumFullDistances; i++) + distancesPrices[i] = posSlotPrices[GetPosSlot1(i)] + tempPrices[i]; + } } p->matchPriceCount = 0; } @@ -1683,9 +1683,9 @@ void LzmaEnc_Construct(CLzmaEnc *p) #endif { - CLzmaEncProps props; - LzmaEncProps_Init(&props); - LzmaEnc_SetProps(p, &props); + CLzmaEncProps props; + LzmaEncProps_Init(&props); + LzmaEnc_SetProps(p, &props); } #ifndef LZMA_LOG_BSR @@ -1702,7 +1702,7 @@ CLzmaEncHandle LzmaEnc_Create(ISzAlloc *alloc) void *p; p = alloc->Alloc(alloc, sizeof(CLzmaEnc)); if (p != 0) - LzmaEnc_Construct((CLzmaEnc *)p); + LzmaEnc_Construct((CLzmaEnc *)p); return p; } @@ -1735,12 +1735,12 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize UInt32 nowPos32, startPos32; if (p->needInit) { - p->matchFinder.Init(p->matchFinderObj); - p->needInit = 0; + p->matchFinder.Init(p->matchFinderObj); + p->needInit = 0; } if (p->finished) - return p->result; + return p->result; RINOK(CheckErrors(p)); nowPos32 = (UInt32)p->nowPos64; @@ -1748,145 +1748,145 @@ static SRes LzmaEnc_CodeOneBlock(CLzmaEnc *p, Bool useLimits, UInt32 maxPackSize if (p->nowPos64 == 0) { - UInt32 numPairs; - Byte curByte; - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) - return Flush(p, nowPos32); - ReadMatchDistances(p, &numPairs); - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0); - p->state = kLiteralNextStates[p->state]; - curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset); - LitEnc_Encode(&p->rc, p->litProbs, curByte); - p->additionalOffset--; - nowPos32++; + UInt32 numPairs; + Byte curByte; + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) + return Flush(p, nowPos32); + ReadMatchDistances(p, &numPairs); + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][0], 0); + p->state = kLiteralNextStates[p->state]; + curByte = p->matchFinder.GetIndexByte(p->matchFinderObj, 0 - p->additionalOffset); + LitEnc_Encode(&p->rc, p->litProbs, curByte); + p->additionalOffset--; + nowPos32++; } if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) != 0) for (;;) { - UInt32 pos, len, posState; + UInt32 pos, len, posState; - if (p->fastMode) - len = GetOptimumFast(p, &pos); - else - len = GetOptimum(p, nowPos32, &pos); + if (p->fastMode) + len = GetOptimumFast(p, &pos); + else + len = GetOptimum(p, nowPos32, &pos); - #ifdef SHOW_STAT2 - printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos); - #endif + #ifdef SHOW_STAT2 + printf("\n pos = %4X, len = %d pos = %d", nowPos32, len, pos); + #endif - posState = nowPos32 & p->pbMask; - if (len == 1 && pos == (UInt32)-1) - { - Byte curByte; - CLzmaProb *probs; - const Byte *data; + posState = nowPos32 & p->pbMask; + if (len == 1 && pos == (UInt32)-1) + { + Byte curByte; + CLzmaProb *probs; + const Byte *data; - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0); - data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; - curByte = *data; - probs = LIT_PROBS(nowPos32, *(data - 1)); - if (IsCharState(p->state)) - LitEnc_Encode(&p->rc, probs, curByte); - else - LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1)); - p->state = kLiteralNextStates[p->state]; - } - else - { - RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); - if (pos < LZMA_NUM_REPS) - { - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1); - if (pos == 0) - { - RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0); - RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1)); - } - else - { - UInt32 distance = p->reps[pos]; - RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1); - if (pos == 1) - RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0); - else - { - RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1); - RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2); - if (pos == 3) - p->reps[3] = p->reps[2]; - p->reps[2] = p->reps[1]; - } - p->reps[1] = p->reps[0]; - p->reps[0] = distance; - } - if (len == 1) - p->state = kShortRepNextStates[p->state]; - else - { - LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - p->state = kRepNextStates[p->state]; - } - } - else - { - UInt32 posSlot; - RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); - p->state = kMatchNextStates[p->state]; - LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); - pos -= LZMA_NUM_REPS; - GetPosSlot(pos, posSlot); - RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot); - - if (posSlot >= kStartPosModelIndex) - { - UInt32 footerBits = ((posSlot >> 1) - 1); - UInt32 base = ((2 | (posSlot & 1)) << footerBits); - UInt32 posReduced = pos - base; + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 0); + data = p->matchFinder.GetPointerToCurrentPos(p->matchFinderObj) - p->additionalOffset; + curByte = *data; + probs = LIT_PROBS(nowPos32, *(data - 1)); + if (IsCharState(p->state)) + LitEnc_Encode(&p->rc, probs, curByte); + else + LitEnc_EncodeMatched(&p->rc, probs, curByte, *(data - p->reps[0] - 1)); + p->state = kLiteralNextStates[p->state]; + } + else + { + RangeEnc_EncodeBit(&p->rc, &p->isMatch[p->state][posState], 1); + if (pos < LZMA_NUM_REPS) + { + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 1); + if (pos == 0) + { + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 0); + RangeEnc_EncodeBit(&p->rc, &p->isRep0Long[p->state][posState], ((len == 1) ? 0 : 1)); + } + else + { + UInt32 distance = p->reps[pos]; + RangeEnc_EncodeBit(&p->rc, &p->isRepG0[p->state], 1); + if (pos == 1) + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 0); + else + { + RangeEnc_EncodeBit(&p->rc, &p->isRepG1[p->state], 1); + RangeEnc_EncodeBit(&p->rc, &p->isRepG2[p->state], pos - 2); + if (pos == 3) + p->reps[3] = p->reps[2]; + p->reps[2] = p->reps[1]; + } + p->reps[1] = p->reps[0]; + p->reps[0] = distance; + } + if (len == 1) + p->state = kShortRepNextStates[p->state]; + else + { + LenEnc_Encode2(&p->repLenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); + p->state = kRepNextStates[p->state]; + } + } + else + { + UInt32 posSlot; + RangeEnc_EncodeBit(&p->rc, &p->isRep[p->state], 0); + p->state = kMatchNextStates[p->state]; + LenEnc_Encode2(&p->lenEnc, &p->rc, len - LZMA_MATCH_LEN_MIN, posState, !p->fastMode, p->ProbPrices); + pos -= LZMA_NUM_REPS; + GetPosSlot(pos, posSlot); + RcTree_Encode(&p->rc, p->posSlotEncoder[GetLenToPosState(len)], kNumPosSlotBits, posSlot); + + if (posSlot >= kStartPosModelIndex) + { + UInt32 footerBits = ((posSlot >> 1) - 1); + UInt32 base = ((2 | (posSlot & 1)) << footerBits); + UInt32 posReduced = pos - base; - if (posSlot < kEndPosModelIndex) - RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced); - else - { - RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits); - RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask); - p->alignPriceCount++; - } - } - p->reps[3] = p->reps[2]; - p->reps[2] = p->reps[1]; - p->reps[1] = p->reps[0]; - p->reps[0] = pos; - p->matchPriceCount++; - } - } - p->additionalOffset -= len; - nowPos32 += len; - if (p->additionalOffset == 0) - { - UInt32 processed; - if (!p->fastMode) - { - if (p->matchPriceCount >= (1 << 7)) - FillDistancesPrices(p); - if (p->alignPriceCount >= kAlignTableSize) - FillAlignPrices(p); - } - if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) - break; - processed = nowPos32 - startPos32; - if (useLimits) - { - if (processed + kNumOpts + 300 >= maxUnpackSize || - RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize) - break; - } - else if (processed >= (1 << 15)) - { - p->nowPos64 += nowPos32 - startPos32; - return CheckErrors(p); - } - } + if (posSlot < kEndPosModelIndex) + RcTree_ReverseEncode(&p->rc, p->posEncoders + base - posSlot - 1, footerBits, posReduced); + else + { + RangeEnc_EncodeDirectBits(&p->rc, posReduced >> kNumAlignBits, footerBits - kNumAlignBits); + RcTree_ReverseEncode(&p->rc, p->posAlignEncoder, kNumAlignBits, posReduced & kAlignMask); + p->alignPriceCount++; + } + } + p->reps[3] = p->reps[2]; + p->reps[2] = p->reps[1]; + p->reps[1] = p->reps[0]; + p->reps[0] = pos; + p->matchPriceCount++; + } + } + p->additionalOffset -= len; + nowPos32 += len; + if (p->additionalOffset == 0) + { + UInt32 processed; + if (!p->fastMode) + { + if (p->matchPriceCount >= (1 << 7)) + FillDistancesPrices(p); + if (p->alignPriceCount >= kAlignTableSize) + FillAlignPrices(p); + } + if (p->matchFinder.GetNumAvailableBytes(p->matchFinderObj) == 0) + break; + processed = nowPos32 - startPos32; + if (useLimits) + { + if (processed + kNumOpts + 300 >= maxUnpackSize || + RangeEnc_GetProcessed(&p->rc) + kNumOpts * 2 >= maxPackSize) + break; + } + else if (processed >= (1 << 15)) + { + p->nowPos64 += nowPos32 - startPos32; + return CheckErrors(p); + } + } } p->nowPos64 += nowPos32 - startPos32; return Flush(p, nowPos32); @@ -1899,47 +1899,47 @@ static SRes LzmaEnc_Alloc(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *alloc, I UInt32 beforeSize = kNumOpts; Bool btMode; if (!RangeEnc_Alloc(&p->rc, alloc)) - return SZ_ERROR_MEM; + return SZ_ERROR_MEM; btMode = (p->matchFinderBase.btMode != 0); #ifndef _7ZIP_ST p->mtMode = (p->multiThread && !p->fastMode && btMode); #endif { - unsigned lclp = p->lc + p->lp; - if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp) - { - LzmaEnc_FreeLits(p, alloc); - p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); - p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); - if (p->litProbs == 0 || p->saveState.litProbs == 0) - { - LzmaEnc_FreeLits(p, alloc); - return SZ_ERROR_MEM; - } - p->lclp = lclp; - } + unsigned lclp = p->lc + p->lp; + if (p->litProbs == 0 || p->saveState.litProbs == 0 || p->lclp != lclp) + { + LzmaEnc_FreeLits(p, alloc); + p->litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); + p->saveState.litProbs = (CLzmaProb *)alloc->Alloc(alloc, (0x300 << lclp) * sizeof(CLzmaProb)); + if (p->litProbs == 0 || p->saveState.litProbs == 0) + { + LzmaEnc_FreeLits(p, alloc); + return SZ_ERROR_MEM; + } + p->lclp = lclp; + } } p->matchFinderBase.bigHash = (p->dictSize > kBigHashDicLimit); if (beforeSize + p->dictSize < keepWindowSize) - beforeSize = keepWindowSize - p->dictSize; + beforeSize = keepWindowSize - p->dictSize; #ifndef _7ZIP_ST if (p->mtMode) { - RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)); - p->matchFinderObj = &p->matchFinderMt; - MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); + RINOK(MatchFinderMt_Create(&p->matchFinderMt, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)); + p->matchFinderObj = &p->matchFinderMt; + MatchFinderMt_CreateVTable(&p->matchFinderMt, &p->matchFinder); } else #endif { - if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)) - return SZ_ERROR_MEM; - p->matchFinderObj = &p->matchFinderBase; - MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder); + if (!MatchFinder_Create(&p->matchFinderBase, p->dictSize, beforeSize, p->numFastBytes, LZMA_MATCH_LEN_MAX, allocBig)) + return SZ_ERROR_MEM; + p->matchFinderObj = &p->matchFinderBase; + MatchFinder_CreateVTable(&p->matchFinderBase, &p->matchFinder); } return SZ_OK; } @@ -1949,50 +1949,50 @@ void LzmaEnc_Init(CLzmaEnc *p) UInt32 i; p->state = 0; for (i = 0 ; i < LZMA_NUM_REPS; i++) - p->reps[i] = 0; + p->reps[i] = 0; RangeEnc_Init(&p->rc); for (i = 0; i < kNumStates; i++) { - UInt32 j; - for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++) - { - p->isMatch[i][j] = kProbInitValue; - p->isRep0Long[i][j] = kProbInitValue; - } - p->isRep[i] = kProbInitValue; - p->isRepG0[i] = kProbInitValue; - p->isRepG1[i] = kProbInitValue; - p->isRepG2[i] = kProbInitValue; + UInt32 j; + for (j = 0; j < LZMA_NUM_PB_STATES_MAX; j++) + { + p->isMatch[i][j] = kProbInitValue; + p->isRep0Long[i][j] = kProbInitValue; + } + p->isRep[i] = kProbInitValue; + p->isRepG0[i] = kProbInitValue; + p->isRepG1[i] = kProbInitValue; + p->isRepG2[i] = kProbInitValue; } { - UInt32 num = 0x300 << (p->lp + p->lc); - for (i = 0; i < num; i++) - p->litProbs[i] = kProbInitValue; + UInt32 num = 0x300 << (p->lp + p->lc); + for (i = 0; i < num; i++) + p->litProbs[i] = kProbInitValue; } { - for (i = 0; i < kNumLenToPosStates; i++) - { - CLzmaProb *probs = p->posSlotEncoder[i]; - UInt32 j; - for (j = 0; j < (1 << kNumPosSlotBits); j++) - probs[j] = kProbInitValue; - } + for (i = 0; i < kNumLenToPosStates; i++) + { + CLzmaProb *probs = p->posSlotEncoder[i]; + UInt32 j; + for (j = 0; j < (1 << kNumPosSlotBits); j++) + probs[j] = kProbInitValue; + } } { - for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++) - p->posEncoders[i] = kProbInitValue; + for (i = 0; i < kNumFullDistances - kEndPosModelIndex; i++) + p->posEncoders[i] = kProbInitValue; } LenEnc_Init(&p->lenEnc.p); LenEnc_Init(&p->repLenEnc.p); for (i = 0; i < (1 << kNumAlignBits); i++) - p->posAlignEncoder[i] = kProbInitValue; + p->posAlignEncoder[i] = kProbInitValue; p->optimumEndIndex = 0; p->optimumCurrentIndex = 0; @@ -2006,13 +2006,13 @@ void LzmaEnc_InitPrices(CLzmaEnc *p) { if (!p->fastMode) { - FillDistancesPrices(p); - FillAlignPrices(p); + FillDistancesPrices(p); + FillAlignPrices(p); } p->lenEnc.tableSize = p->repLenEnc.tableSize = - p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN; + p->numFastBytes + 1 - LZMA_MATCH_LEN_MIN; LenPriceEnc_UpdateTables(&p->lenEnc, 1 << p->pb, p->ProbPrices); LenPriceEnc_UpdateTables(&p->repLenEnc, 1 << p->pb, p->ProbPrices); } @@ -2021,8 +2021,8 @@ static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *a { UInt32 i; for (i = 0; i < (UInt32)kDicLogSizeMaxCompress; i++) - if (p->dictSize <= ((UInt32)1 << i)) - break; + if (p->dictSize <= ((UInt32)1 << i)) + break; p->distTableSize = i * 2; p->finished = False; @@ -2035,7 +2035,7 @@ static SRes LzmaEnc_AllocAndInit(CLzmaEnc *p, UInt32 keepWindowSize, ISzAlloc *a } static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, - ISzAlloc *alloc, ISzAlloc *allocBig) + ISzAlloc *alloc, ISzAlloc *allocBig) { CLzmaEnc *p = (CLzmaEnc *)pp; p->matchFinderBase.stream = inStream; @@ -2045,8 +2045,8 @@ static SRes LzmaEnc_Prepare(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInS } SRes LzmaEnc_PrepareForLzma2(CLzmaEncHandle pp, - ISeqInStream *inStream, UInt32 keepWindowSize, - ISzAlloc *alloc, ISzAlloc *allocBig) + ISeqInStream *inStream, UInt32 keepWindowSize, + ISzAlloc *alloc, ISzAlloc *allocBig) { CLzmaEnc *p = (CLzmaEnc *)pp; p->matchFinderBase.stream = inStream; @@ -2062,7 +2062,7 @@ static void LzmaEnc_SetInputBuf(CLzmaEnc *p, const Byte *src, SizeT srcLen) } SRes LzmaEnc_MemPrepare(CLzmaEncHandle pp, const Byte *src, SizeT srcLen, - UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) + UInt32 keepWindowSize, ISzAlloc *alloc, ISzAlloc *allocBig) { CLzmaEnc *p = (CLzmaEnc *)pp; LzmaEnc_SetInputBuf(p, src, srcLen); @@ -2076,9 +2076,9 @@ void LzmaEnc_Finish(CLzmaEncHandle pp) #ifndef _7ZIP_ST CLzmaEnc *p = (CLzmaEnc *)pp; if (p->mtMode) - MatchFinderMt_ReleaseStream(&p->matchFinderMt); + MatchFinderMt_ReleaseStream(&p->matchFinderMt); #else - pp = pp; + pp = pp; #endif } @@ -2095,8 +2095,8 @@ static size_t MyWrite(void *pp, const void *data, size_t size) CSeqOutStreamBuf *p = (CSeqOutStreamBuf *)pp; if (p->rem < size) { - size = p->rem; - p->overflow = True; + size = p->rem; + p->overflow = True; } memcpy(p->data, data, size); p->rem -= size; @@ -2118,7 +2118,7 @@ const Byte *LzmaEnc_GetCurBuf(CLzmaEncHandle pp) } SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit, - Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize) + Byte *dest, size_t *destLen, UInt32 desiredPackSize, UInt32 *unpackSize) { CLzmaEnc *p = (CLzmaEnc *)pp; UInt64 nowPos64; @@ -2135,7 +2135,7 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit, p->result = SZ_OK; if (reInit) - LzmaEnc_Init(p); + LzmaEnc_Init(p); LzmaEnc_InitPrices(p); nowPos64 = p->nowPos64; RangeEnc_Init(&p->rc); @@ -2146,7 +2146,7 @@ SRes LzmaEnc_CodeOneMemBlock(CLzmaEncHandle pp, Bool reInit, *unpackSize = (UInt32)(p->nowPos64 - nowPos64); *destLen -= outStream.rem; if (outStream.overflow) - return SZ_ERROR_OUTPUT_EOF; + return SZ_ERROR_OUTPUT_EOF; return res; } @@ -2159,30 +2159,30 @@ static SRes LzmaEnc_Encode2(CLzmaEnc *p, ICompressProgress *progress) Byte allocaDummy[0x300]; int i = 0; for (i = 0; i < 16; i++) - allocaDummy[i] = (Byte)i; + allocaDummy[i] = (Byte)i; #endif for (;;) { - res = LzmaEnc_CodeOneBlock(p, False, 0, 0); - if (res != SZ_OK || p->finished != 0) - break; - if (progress != 0) - { - res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc)); - if (res != SZ_OK) - { - res = SZ_ERROR_PROGRESS; - break; - } - } + res = LzmaEnc_CodeOneBlock(p, False, 0, 0); + if (res != SZ_OK || p->finished != 0) + break; + if (progress != 0) + { + res = progress->Progress(progress, p->nowPos64, RangeEnc_GetProcessed(&p->rc)); + if (res != SZ_OK) + { + res = SZ_ERROR_PROGRESS; + break; + } + } } LzmaEnc_Finish(p); return res; } SRes LzmaEnc_Encode(CLzmaEncHandle pp, ISeqOutStream *outStream, ISeqInStream *inStream, ICompressProgress *progress, - ISzAlloc *alloc, ISzAlloc *allocBig) + ISzAlloc *alloc, ISzAlloc *allocBig) { RINOK(LzmaEnc_Prepare(pp, outStream, inStream, alloc, allocBig)); return LzmaEnc_Encode2((CLzmaEnc *)pp, progress); @@ -2194,31 +2194,31 @@ SRes LzmaEnc_WriteProperties(CLzmaEncHandle pp, Byte *props, SizeT *size) int i; UInt32 dictSize = p->dictSize; if (*size < LZMA_PROPS_SIZE) - return SZ_ERROR_PARAM; + return SZ_ERROR_PARAM; *size = LZMA_PROPS_SIZE; props[0] = (Byte)((p->pb * 5 + p->lp) * 9 + p->lc); for (i = 11; i <= 30; i++) { - if (dictSize <= ((UInt32)2 << i)) - { - dictSize = (2 << i); - break; - } - if (dictSize <= ((UInt32)3 << i)) - { - dictSize = (3 << i); - break; - } + if (dictSize <= ((UInt32)2 << i)) + { + dictSize = (2 << i); + break; + } + if (dictSize <= ((UInt32)3 << i)) + { + dictSize = (3 << i); + break; + } } for (i = 0; i < 4; i++) - props[1 + i] = (Byte)(dictSize >> (8 * i)); + props[1 + i] = (Byte)(dictSize >> (8 * i)); return SZ_OK; } SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) + int writeEndMark, ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) { SRes res; CLzmaEnc *p = (CLzmaEnc *)pp; @@ -2237,30 +2237,30 @@ SRes LzmaEnc_MemEncode(CLzmaEncHandle pp, Byte *dest, SizeT *destLen, const Byte p->rc.outStream = &outStream.funcTable; res = LzmaEnc_MemPrepare(pp, src, srcLen, 0, alloc, allocBig); if (res == SZ_OK) - res = LzmaEnc_Encode2(p, progress); + res = LzmaEnc_Encode2(p, progress); *destLen -= outStream.rem; if (outStream.overflow) - return SZ_ERROR_OUTPUT_EOF; + return SZ_ERROR_OUTPUT_EOF; return res; } SRes LzmaEncode(Byte *dest, SizeT *destLen, const Byte *src, SizeT srcLen, - const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, - ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) + const CLzmaEncProps *props, Byte *propsEncoded, SizeT *propsSize, int writeEndMark, + ICompressProgress *progress, ISzAlloc *alloc, ISzAlloc *allocBig) { CLzmaEnc *p = (CLzmaEnc *)LzmaEnc_Create(alloc); SRes res; if (p == 0) - return SZ_ERROR_MEM; + return SZ_ERROR_MEM; res = LzmaEnc_SetProps(p, props); if (res == SZ_OK) { - res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize); - if (res == SZ_OK) - res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen, - writeEndMark, progress, alloc, allocBig); + res = LzmaEnc_WriteProperties(p, propsEncoded, propsSize); + if (res == SZ_OK) + res = LzmaEnc_MemEncode(p, dest, destLen, src, srcLen, + writeEndMark, progress, alloc, allocBig); } LzmaEnc_Destroy(p, alloc, allocBig); diff --git a/Tiano/EfiCompress.c b/Tiano/EfiCompress.c index 1437c05..af05b53 100644 --- a/Tiano/EfiCompress.c +++ b/Tiano/EfiCompress.c @@ -5,7 +5,7 @@ This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php - + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. @@ -254,8 +254,8 @@ STATIC UINT32 mBufSiz = 0, mOutputPos, mOutputMask, mSubBitBuf, mCrc; STATIC UINT32 mCompSize, mOrigSize; STATIC UINT16 *mFreq, *mSortPtr, mLenCnt[17], mLeft[2 * NC - 1], mRight[2 * NC - 1], - mCrcTable[UINT8_MAX + 1], mCFreq[2 * NC - 1], mCTable[4096], mCCode[NC], - mPFreq[2 * NP - 1], mPTCode[NPT], mTFreq[2 * NT - 1]; + mCrcTable[UINT8_MAX + 1], mCFreq[2 * NC - 1], mCTable[4096], mCCode[NC], + mPFreq[2 * NP - 1], mPTCode[NPT], mTFreq[2 * NT - 1]; STATIC NODE mPos, mMatchPos, mAvail, *mPosition, *mParent, *mPrev, *mNext = NULL; @@ -266,10 +266,10 @@ STATIC NODE mPos, mMatchPos, mAvail, *mPosition, *mParent, *mPrev, *mNext = NU INT32 EfiCompress ( - UINT8 *SrcBuffer, - UINT32 SrcSize, - UINT8 *DstBuffer, - UINT32 *DstSize + UINT8 *SrcBuffer, + UINT32 SrcSize, + UINT8 *DstBuffer, + UINT32 *DstSize ) /*++ @@ -283,12 +283,12 @@ Arguments: SrcSize - The size of source data DstBuffer - The buffer to store the compressed data DstSize - On input, the size of DstBuffer; On output, - the size of the actual compressed data. + the size of the actual compressed data. Returns: EFI_BUFFER_TOO_SMALL - The DstBuffer is too small.this case, - DstSize contains the size needed. + DstSize contains the size needed. EFI_SUCCESS - Compression is successful. --*/ @@ -328,14 +328,14 @@ Returns: Status = Encode(); if (Status) { - return ERR_OUT_OF_RESOURCES; + return ERR_OUT_OF_RESOURCES; } // // Null terminate the compressed data // if (mDst < mDstUpperLimit) { - *mDst++ = 0; + *mDst++ = 0; } // @@ -350,11 +350,11 @@ Returns: // if (mCompSize + 1 + 8 > *DstSize) { - *DstSize = mCompSize + 1 + 8; - return ERR_BUFFER_TOO_SMALL; + *DstSize = mCompSize + 1 + 8; + return ERR_BUFFER_TOO_SMALL; } else { - *DstSize = mCompSize + 1 + 8; - return ERR_SUCCESS; + *DstSize = mCompSize + 1 + 8; + return ERR_SUCCESS; } } @@ -379,19 +379,19 @@ Returns: (VOID) --*/ { if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8)(((UINT8)(Data )) & 0xff); + *mDst++ = (UINT8)(((UINT8)(Data )) & 0xff); } if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8)(((UINT8)(Data >> 0x08)) & 0xff); + *mDst++ = (UINT8)(((UINT8)(Data >> 0x08)) & 0xff); } if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8)(((UINT8)(Data >> 0x10)) & 0xff); + *mDst++ = (UINT8)(((UINT8)(Data >> 0x10)) & 0xff); } if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8)(((UINT8)(Data >> 0x18)) & 0xff); + *mDst++ = (UINT8)(((UINT8)(Data >> 0x18)) & 0xff); } } @@ -420,7 +420,7 @@ Returns: return ERR_OUT_OF_MEMORY; for (i = 0 ; i < WNDSIZ * 2 + MAXMATCH; i ++) { - mText[i] = 0; + mText[i] = 0; } mLevel = malloc ((WNDSIZ + UINT8_MAX + 1) * sizeof(*mLevel)); @@ -432,10 +432,10 @@ Returns: mBufSiz = 16 * 1024U; while ((mBuf = malloc(mBufSiz)) == NULL) { - mBufSiz = (mBufSiz / 10U) * 9U; - if (mBufSiz < 4 * 1024U) { - return ERR_OUT_OF_RESOURCES; - } + mBufSiz = (mBufSiz / 10U) * 9U; + if (mBufSiz < 4 * 1024U) { + return ERR_OUT_OF_RESOURCES; + } } mBuf[0] = 0; @@ -457,35 +457,35 @@ Returns: (VOID) --*/ { if (mText) { - free (mText); + free (mText); } if (mLevel) { - free (mLevel); + free (mLevel); } if (mChildCount) { - free (mChildCount); + free (mChildCount); } if (mPosition) { - free (mPosition); + free (mPosition); } if (mParent) { - free (mParent); + free (mParent); } if (mPrev) { - free (mPrev); + free (mPrev); } if (mNext) { - free (mNext); + free (mNext); } if (mBuf) { - free (mBuf); + free (mBuf); } return; @@ -510,20 +510,20 @@ Returns: (VOID) NODE i; for (i = WNDSIZ; i <= WNDSIZ + UINT8_MAX; i++) { - mLevel[i] = 1; - mPosition[i] = NIL; /* sentinel */ + mLevel[i] = 1; + mPosition[i] = NIL; /* sentinel */ } for (i = WNDSIZ; i < WNDSIZ * 2; i++) { - mParent[i] = NIL; + mParent[i] = NIL; } mAvail = 1; for (i = 1; i < WNDSIZ - 1; i++) { - mNext[i] = (NODE)(i + 1); + mNext[i] = (NODE)(i + 1); } mNext[WNDSIZ - 1] = NIL; for (i = WNDSIZ * 2; i <= MAX_HASH_VAL; i++) { - mNext[i] = NIL; + mNext[i] = NIL; } } @@ -556,7 +556,7 @@ Returns: r = mNext[HASH(q, c)]; mParent[NIL] = q; /* sentinel */ while (mParent[r] != q) { - r = mNext[r]; + r = mNext[r]; } return r; @@ -653,45 +653,45 @@ Returns: (VOID) UINT8 c, *t1, *t2; if (mMatchLen >= 4) { - - // - // We have just got a long match, the target tree - // can be located by MatchPos + 1. Travese the tree - // from bottom up to get to a proper starting point. - // The usage of PERC_FLAG ensures proper node deletion - //DeleteNode() later. - // - - mMatchLen--; - r = (INT16)((mMatchPos + 1) | WNDSIZ); - while ((q = mParent[r]) == NIL) { - r = mNext[r]; - } - while (mLevel[q] >= mMatchLen) { - r = q; q = mParent[q]; - } - t = q; - while (mPosition[t] < 0) { - mPosition[t] = mPos; - t = mParent[t]; - } - if (t < WNDSIZ) { - mPosition[t] = (NODE)(mPos | PERC_FLAG); - } + + // + // We have just got a long match, the target tree + // can be located by MatchPos + 1. Travese the tree + // from bottom up to get to a proper starting point. + // The usage of PERC_FLAG ensures proper node deletion + //DeleteNode() later. + // + + mMatchLen--; + r = (INT16)((mMatchPos + 1) | WNDSIZ); + while ((q = mParent[r]) == NIL) { + r = mNext[r]; + } + while (mLevel[q] >= mMatchLen) { + r = q; q = mParent[q]; + } + t = q; + while (mPosition[t] < 0) { + mPosition[t] = mPos; + t = mParent[t]; + } + if (t < WNDSIZ) { + mPosition[t] = (NODE)(mPos | PERC_FLAG); + } } else { - - // - // Locate the target tree - // - - q = (INT16)(mText[mPos] + WNDSIZ); - c = mText[mPos + 1]; - if ((r = Child(q, c)) == NIL) { - MakeChild(q, c, mPos); - mMatchLen = 1; - return; - } - mMatchLen = 2; + + // + // Locate the target tree + // + + q = (INT16)(mText[mPos] + WNDSIZ); + c = mText[mPos + 1]; + if ((r = Child(q, c)) == NIL) { + MakeChild(q, c, mPos); + mMatchLen = 1; + return; + } + mMatchLen = 2; } // @@ -701,37 +701,37 @@ Returns: (VOID) // for ( ; ; ) { - if (r >= WNDSIZ) { - j = MAXMATCH; - mMatchPos = r; - } else { - j = mLevel[r]; - mMatchPos = (NODE)(mPosition[r] & ~PERC_FLAG); - } - if (mMatchPos >= mPos) { - mMatchPos -= WNDSIZ; - } - t1 = &mText[mPos + mMatchLen]; - t2 = &mText[mMatchPos + mMatchLen]; - while (mMatchLen < j) { - if (*t1 != *t2) { - Split(r); - return; - } - mMatchLen++; - t1++; - t2++; - } - if (mMatchLen >= MAXMATCH) { - break; - } - mPosition[r] = mPos; - q = r; - if ((r = Child(q, *t1)) == NIL) { - MakeChild(q, *t1, mPos); - return; - } - mMatchLen++; + if (r >= WNDSIZ) { + j = MAXMATCH; + mMatchPos = r; + } else { + j = mLevel[r]; + mMatchPos = (NODE)(mPosition[r] & ~PERC_FLAG); + } + if (mMatchPos >= mPos) { + mMatchPos -= WNDSIZ; + } + t1 = &mText[mPos + mMatchLen]; + t2 = &mText[mMatchPos + mMatchLen]; + while (mMatchLen < j) { + if (*t1 != *t2) { + Split(r); + return; + } + mMatchLen++; + t1++; + t2++; + } + if (mMatchLen >= MAXMATCH) { + break; + } + mPosition[r] = mPos; + q = r; + if ((r = Child(q, *t1)) == NIL) { + MakeChild(q, *t1, mPos); + return; + } + mMatchLen++; } t = mPrev[r]; mPrev[mPos] = t; @@ -768,7 +768,7 @@ Returns: (VOID) NODE q, r, s, t, u; if (mParent[mPos] == NIL) { - return; + return; } r = mPrev[mPos]; @@ -778,33 +778,33 @@ Returns: (VOID) r = mParent[mPos]; mParent[mPos] = NIL; if (r >= WNDSIZ || --mChildCount[r] > 1) { - return; + return; } t = (NODE)(mPosition[r] & ~PERC_FLAG); if (t >= mPos) { - t -= WNDSIZ; + t -= WNDSIZ; } s = t; q = mParent[r]; while ((u = mPosition[q]) & PERC_FLAG) { - u &= ~PERC_FLAG; - if (u >= mPos) { - u -= WNDSIZ; - } - if (u > s) { - s = u; - } - mPosition[q] = (INT16)(s | WNDSIZ); - q = mParent[q]; + u &= ~PERC_FLAG; + if (u >= mPos) { + u -= WNDSIZ; + } + if (u > s) { + s = u; + } + mPosition[q] = (INT16)(s | WNDSIZ); + q = mParent[q]; } if (q < WNDSIZ) { - if (u >= mPos) { - u -= WNDSIZ; - } - if (u > s) { - s = u; - } - mPosition[q] = (INT16)(s | WNDSIZ | PERC_FLAG); + if (u >= mPos) { + u -= WNDSIZ; + } + if (u > s) { + s = u; + } + mPosition[q] = (INT16)(s | WNDSIZ | PERC_FLAG); } s = Child(r, mText[t + mLevel[r]]); t = mPrev[s]; @@ -843,10 +843,10 @@ Returns: (VOID) mRemainder--; if (++mPos == WNDSIZ * 2) { - memmove(&mText[0], &mText[WNDSIZ], WNDSIZ + MAXMATCH); - n = FreadCrc(&mText[WNDSIZ + MAXMATCH], WNDSIZ); - mRemainder += n; - mPos = WNDSIZ; + memmove(&mText[0], &mText[WNDSIZ], WNDSIZ + MAXMATCH); + n = FreadCrc(&mText[WNDSIZ + MAXMATCH], WNDSIZ); + mRemainder += n; + mPos = WNDSIZ; } DeleteNode(); InsertNode(); @@ -876,8 +876,8 @@ Returns: Status = AllocateMemory(); if (Status) { - FreeMemory(); - return Status; + FreeMemory(); + return Status; } InitSlide(); @@ -890,39 +890,39 @@ Returns: mPos = WNDSIZ; InsertNode(); if (mMatchLen > mRemainder) { - mMatchLen = mRemainder; + mMatchLen = mRemainder; } while (mRemainder > 0) { - LastMatchLen = mMatchLen; - LastMatchPos = mMatchPos; - GetNextMatch(); - if (mMatchLen > mRemainder) { - mMatchLen = mRemainder; - } - - if (mMatchLen > LastMatchLen || LastMatchLen < THRESHOLD) { - - // - // Not enough benefits are gained by outputting a pointer, - // so just output the original character - // - - Output(mText[mPos - 1], 0); - } else { - - // - // Outputting a pointer is beneficial enough, do it. - // - - Output(LastMatchLen + (UINT8_MAX + 1 - THRESHOLD), - (mPos - LastMatchPos - 2) & (WNDSIZ - 1)); - while (--LastMatchLen > 0) { - GetNextMatch(); - } - if (mMatchLen > mRemainder) { - mMatchLen = mRemainder; - } - } + LastMatchLen = mMatchLen; + LastMatchPos = mMatchPos; + GetNextMatch(); + if (mMatchLen > mRemainder) { + mMatchLen = mRemainder; + } + + if (mMatchLen > LastMatchLen || LastMatchLen < THRESHOLD) { + + // + // Not enough benefits are gained by outputting a pointer, + // so just output the original character + // + + Output(mText[mPos - 1], 0); + } else { + + // + // Outputting a pointer is beneficial enough, do it. + // + + Output(LastMatchLen + (UINT8_MAX + 1 - THRESHOLD), + (mPos - LastMatchPos - 2) & (WNDSIZ - 1)); + while (--LastMatchLen > 0) { + GetNextMatch(); + } + if (mMatchLen > mRemainder) { + mMatchLen = mRemainder; + } + } } HufEncodeEnd(); @@ -948,34 +948,34 @@ Returns: (VOID) INT32 i, k, n, Count; for (i = 0; i < NT; i++) { - mTFreq[i] = 0; + mTFreq[i] = 0; } n = NC; while (n > 0 && mCLen[n - 1] == 0) { - n--; + n--; } i = 0; while (i < n) { - k = mCLen[i++]; - if (k == 0) { - Count = 1; - while (i < n && mCLen[i] == 0) { - i++; - Count++; - } - if (Count <= 2) { - mTFreq[0] = (UINT16)(mTFreq[0] + Count); - } else if (Count <= 18) { - mTFreq[1]++; - } else if (Count == 19) { - mTFreq[0]++; - mTFreq[1]++; - } else { - mTFreq[2]++; - } - } else { - mTFreq[k + 2]++; - } + k = mCLen[i++]; + if (k == 0) { + Count = 1; + while (i < n && mCLen[i] == 0) { + i++; + Count++; + } + if (Count <= 2) { + mTFreq[0] = (UINT16)(mTFreq[0] + Count); + } else if (Count <= 18) { + mTFreq[1]++; + } else if (Count == 19) { + mTFreq[0]++; + mTFreq[1]++; + } else { + mTFreq[2]++; + } + } else { + mTFreq[k + 2]++; + } } } @@ -1005,23 +1005,23 @@ Returns: (VOID) INT32 i, k; while (n > 0 && mPTLen[n - 1] == 0) { - n--; + n--; } PutBits(nbit, n); i = 0; while (i < n) { - k = mPTLen[i++]; - if (k <= 6) { - PutBits(3, k); - } else { - PutBits(k - 3, (1U << (k - 3)) - 2); - } - if (i == Special) { - while (i < 6 && mPTLen[i] == 0) { - i++; - } - PutBits(2, (i - 3) & 3); - } + k = mPTLen[i++]; + if (k <= 6) { + PutBits(3, k); + } else { + PutBits(k - 3, (1U << (k - 3)) - 2); + } + if (i == Special) { + while (i < 6 && mPTLen[i] == 0) { + i++; + } + PutBits(2, (i - 3) & 3); + } } } @@ -1044,36 +1044,36 @@ Returns: (VOID) n = NC; while (n > 0 && mCLen[n - 1] == 0) { - n--; + n--; } PutBits(CBIT, n); i = 0; while (i < n) { - k = mCLen[i++]; - if (k == 0) { - Count = 1; - while (i < n && mCLen[i] == 0) { - i++; - Count++; - } - if (Count <= 2) { - for (k = 0; k < Count; k++) { - PutBits(mPTLen[0], mPTCode[0]); - } - } else if (Count <= 18) { - PutBits(mPTLen[1], mPTCode[1]); - PutBits(4, Count - 3); - } else if (Count == 19) { - PutBits(mPTLen[0], mPTCode[0]); - PutBits(mPTLen[1], mPTCode[1]); - PutBits(4, 15); - } else { - PutBits(mPTLen[2], mPTCode[2]); - PutBits(CBIT, Count - 20); - } - } else { - PutBits(mPTLen[k + 2], mPTCode[k + 2]); - } + k = mCLen[i++]; + if (k == 0) { + Count = 1; + while (i < n && mCLen[i] == 0) { + i++; + Count++; + } + if (Count <= 2) { + for (k = 0; k < Count; k++) { + PutBits(mPTLen[0], mPTCode[0]); + } + } else if (Count <= 18) { + PutBits(mPTLen[1], mPTCode[1]); + PutBits(4, Count - 3); + } else if (Count == 19) { + PutBits(mPTLen[0], mPTCode[0]); + PutBits(mPTLen[1], mPTCode[1]); + PutBits(4, 15); + } else { + PutBits(mPTLen[2], mPTCode[2]); + PutBits(CBIT, Count - 20); + } + } else { + PutBits(mPTLen[k + 2], mPTCode[k + 2]); + } } } @@ -1097,12 +1097,12 @@ EncodeP ( c = 0; q = p; while (q) { - q >>= 1; - c++; + q >>= 1; + c++; } PutBits(mPTLen[c], mPTCode[c]); if (c > 1) { - PutBits(c - 1, p & (0xFFFFU >> (17 - c))); + PutBits(c - 1, p & (0xFFFFU >> (17 - c))); } } @@ -1128,49 +1128,49 @@ Returns: (VOID) Size = mCFreq[Root]; PutBits(16, Size); if (Root >= NC) { - CountTFreq(); - Root = MakeTree(NT, mTFreq, mPTLen, mPTCode); - if (Root >= NT) { - WritePTLen(NT, TBIT, 3); - } else { - PutBits(TBIT, 0); - PutBits(TBIT, Root); - } - WriteCLen(); + CountTFreq(); + Root = MakeTree(NT, mTFreq, mPTLen, mPTCode); + if (Root >= NT) { + WritePTLen(NT, TBIT, 3); + } else { + PutBits(TBIT, 0); + PutBits(TBIT, Root); + } + WriteCLen(); } else { - PutBits(TBIT, 0); - PutBits(TBIT, 0); - PutBits(CBIT, 0); - PutBits(CBIT, Root); + PutBits(TBIT, 0); + PutBits(TBIT, 0); + PutBits(CBIT, 0); + PutBits(CBIT, Root); } Root = MakeTree(NP, mPFreq, mPTLen, mPTCode); if (Root >= NP) { - WritePTLen(NP, PBIT, -1); + WritePTLen(NP, PBIT, -1); } else { - PutBits(PBIT, 0); - PutBits(PBIT, Root); + PutBits(PBIT, 0); + PutBits(PBIT, Root); } Pos = 0; for (i = 0; i < Size; i++) { - if (i % UINT8_BIT == 0) { - Flags = mBuf[Pos++]; - } else { - Flags <<= 1; - } - if (Flags & (1U << (UINT8_BIT - 1))) { - EncodeC(mBuf[Pos++] + (1U << UINT8_BIT)); - k = mBuf[Pos++] << UINT8_BIT; - k += mBuf[Pos++]; - EncodeP(k); - } else { - EncodeC(mBuf[Pos++]); - } + if (i % UINT8_BIT == 0) { + Flags = mBuf[Pos++]; + } else { + Flags <<= 1; + } + if (Flags & (1U << (UINT8_BIT - 1))) { + EncodeC(mBuf[Pos++] + (1U << UINT8_BIT)); + k = mBuf[Pos++] << UINT8_BIT; + k += mBuf[Pos++]; + EncodeP(k); + } else { + EncodeC(mBuf[Pos++]); + } } for (i = 0; i < NC; i++) { - mCFreq[i] = 0; + mCFreq[i] = 0; } for (i = 0; i < NP; i++) { - mPFreq[i] = 0; + mPFreq[i] = 0; } } @@ -1199,26 +1199,26 @@ Returns: (VOID) STATIC UINT32 CPos; if ((mOutputMask >>= 1) == 0) { - mOutputMask = 1U << (UINT8_BIT - 1); - if (mOutputPos >= mBufSiz - 3 * UINT8_BIT) { - SendBlock(); - mOutputPos = 0; - } - CPos = mOutputPos++; - mBuf[CPos] = 0; + mOutputMask = 1U << (UINT8_BIT - 1); + if (mOutputPos >= mBufSiz - 3 * UINT8_BIT) { + SendBlock(); + mOutputPos = 0; + } + CPos = mOutputPos++; + mBuf[CPos] = 0; } mBuf[mOutputPos++] = (UINT8) c; mCFreq[c]++; if (c >= (1U << UINT8_BIT)) { - mBuf[CPos] |= mOutputMask; - mBuf[mOutputPos++] = (UINT8)(p >> UINT8_BIT); - mBuf[mOutputPos++] = (UINT8) p; - c = 0; - while (p) { - p >>= 1; - c++; - } - mPFreq[c]++; + mBuf[CPos] |= mOutputMask; + mBuf[mOutputPos++] = (UINT8)(p >> UINT8_BIT); + mBuf[mOutputPos++] = (UINT8) p; + c = 0; + while (p) { + p >>= 1; + c++; + } + mPFreq[c]++; } } @@ -1229,10 +1229,10 @@ HufEncodeStart () INT32 i; for (i = 0; i < NC; i++) { - mCFreq[i] = 0; + mCFreq[i] = 0; } for (i = 0; i < NP; i++) { - mPFreq[i] = 0; + mPFreq[i] = 0; } mOutputPos = mOutputMask = 0; InitPutBits(); @@ -1261,15 +1261,15 @@ MakeCrcTable () UINT32 i, j, r; for (i = 0; i <= UINT8_MAX; i++) { - r = i; - for (j = 0; j < UINT8_BIT; j++) { - if (r & 1) { - r = (r >> 1) ^ CRCPOLY; - } else { - r >>= 1; - } - } - mCrcTable[i] = (UINT16)r; + r = i; + for (j = 0; j < UINT8_BIT; j++) { + if (r & 1) { + r = (r >> 1) ^ CRCPOLY; + } else { + r >>= 1; + } + } + mCrcTable[i] = (UINT16)r; } } @@ -1297,27 +1297,27 @@ Returns: (VOID) UINT8 Temp; if (n < mBitCount) { - mSubBitBuf |= x << (mBitCount -= n); + mSubBitBuf |= x << (mBitCount -= n); } else { - - Temp = (UINT8)(mSubBitBuf | (x >> (n -= mBitCount))); - if (mDst < mDstUpperLimit) { - *mDst++ = Temp; - } - mCompSize++; + + Temp = (UINT8)(mSubBitBuf | (x >> (n -= mBitCount))); + if (mDst < mDstUpperLimit) { + *mDst++ = Temp; + } + mCompSize++; - if (n < UINT8_BIT) { - mSubBitBuf = x << (mBitCount = UINT8_BIT - n); - } else { - - Temp = (UINT8)(x >> (n - UINT8_BIT)); - if (mDst < mDstUpperLimit) { - *mDst++ = Temp; - } - mCompSize++; - - mSubBitBuf = x << (mBitCount = 2 * UINT8_BIT - n); - } + if (n < UINT8_BIT) { + mSubBitBuf = x << (mBitCount = UINT8_BIT - n); + } else { + + Temp = (UINT8)(x >> (n - UINT8_BIT)); + if (mDst < mDstUpperLimit) { + *mDst++ = Temp; + } + mCompSize++; + + mSubBitBuf = x << (mBitCount = 2 * UINT8_BIT - n); + } } } @@ -1347,14 +1347,14 @@ Returns: INT32 i; for (i = 0; mSrc < mSrcUpperLimit && i < n; i++) { - *p++ = *mSrc++; + *p++ = *mSrc++; } n = i; p -= n; mOrigSize += n; while (--i >= 0) { - UPDATE_CRC(*p++); + UPDATE_CRC(*p++); } return n; } @@ -1390,12 +1390,12 @@ Returns: (VOID) STATIC INT32 Depth = 0; if (i < mN) { - mLenCnt[(Depth < 16) ? Depth : 16]++; + mLenCnt[(Depth < 16) ? Depth : 16]++; } else { - Depth++; - CountLen(mLeft [i]); - CountLen(mRight[i]); - Depth--; + Depth++; + CountLen(mLeft [i]); + CountLen(mRight[i]); + Depth--; } } @@ -1420,7 +1420,7 @@ Arguments: UINT32 Cum; for (i = 0; i <= 16; i++) { - mLenCnt[i] = 0; + mLenCnt[i] = 0; } CountLen(Root); @@ -1431,24 +1431,24 @@ Arguments: Cum = 0; for (i = 16; i > 0; i--) { - Cum += mLenCnt[i] << (16 - i); + Cum += mLenCnt[i] << (16 - i); } while (Cum != (1U << 16)) { - mLenCnt[16]--; - for (i = 15; i > 0; i--) { - if (mLenCnt[i] != 0) { - mLenCnt[i]--; - mLenCnt[i+1] += 2; - break; - } - } - Cum--; + mLenCnt[16]--; + for (i = 15; i > 0; i--) { + if (mLenCnt[i] != 0) { + mLenCnt[i]--; + mLenCnt[i+1] += 2; + break; + } + } + Cum--; } for (i = 16; i > 0; i--) { - k = mLenCnt[i]; - while (--k >= 0) { - mLen[*mSortPtr++] = (UINT8)i; - } + k = mLenCnt[i]; + while (--k >= 0) { + mLen[*mSortPtr++] = (UINT8)i; + } } } @@ -1466,14 +1466,14 @@ DownHeap ( k = mHeap[i]; while ((j = 2 * i) <= mHeapSize) { - if (j < mHeapSize && mFreq[mHeap[j]] > mFreq[mHeap[j + 1]]) { - j++; - } - if (mFreq[k] <= mFreq[mHeap[j]]) { - break; - } - mHeap[i] = mHeap[j]; - i = j; + if (j < mHeapSize && mFreq[mHeap[j]] > mFreq[mHeap[j + 1]]) { + j++; + } + if (mFreq[k] <= mFreq[mHeap[j]]) { + break; + } + mHeap[i] = mHeap[j]; + i = j; } mHeap[i] = (INT16)k; } @@ -1506,10 +1506,10 @@ Returns: (VOID) Start[1] = 0; for (i = 1; i <= 16; i++) { - Start[i + 1] = (UINT16)((Start[i] + mLenCnt[i]) << 1); + Start[i + 1] = (UINT16)((Start[i] + mLenCnt[i]) << 1); } for (i = 0; i < n; i++) { - Code[i] = Start[Len[i]]++; + Code[i] = Start[Len[i]]++; } } @@ -1553,40 +1553,40 @@ Returns: mHeapSize = 0; mHeap[1] = 0; for (i = 0; i < mN; i++) { - mLen[i] = 0; - if (mFreq[i]) { - mHeap[++mHeapSize] = (INT16)i; - } + mLen[i] = 0; + if (mFreq[i]) { + mHeap[++mHeapSize] = (INT16)i; + } } if (mHeapSize < 2) { - CodeParm[mHeap[1]] = 0; - return mHeap[1]; + CodeParm[mHeap[1]] = 0; + return mHeap[1]; } for (i = mHeapSize / 2; i >= 1; i--) { - - // - // make priority queue - // - DownHeap(i); + + // + // make priority queue + // + DownHeap(i); } mSortPtr = CodeParm; do { - i = mHeap[1]; - if (i < mN) { - *mSortPtr++ = (UINT16)i; - } - mHeap[1] = mHeap[mHeapSize--]; - DownHeap(1); - j = mHeap[1]; - if (j < mN) { - *mSortPtr++ = (UINT16)j; - } - k = Avail++; - mFreq[k] = (UINT16)(mFreq[i] + mFreq[j]); - mHeap[1] = (INT16)k; - DownHeap(1); - mLeft[k] = (UINT16)i; - mRight[k] = (UINT16)j; + i = mHeap[1]; + if (i < mN) { + *mSortPtr++ = (UINT16)i; + } + mHeap[1] = mHeap[mHeapSize--]; + DownHeap(1); + j = mHeap[1]; + if (j < mN) { + *mSortPtr++ = (UINT16)j; + } + k = Avail++; + mFreq[k] = (UINT16)(mFreq[i] + mFreq[j]); + mHeap[1] = (INT16)k; + DownHeap(1); + mLeft[k] = (UINT16)i; + mRight[k] = (UINT16)j; } while (mHeapSize > 1); mSortPtr = CodeParm; diff --git a/Tiano/EfiTianoCompress.h b/Tiano/EfiTianoCompress.h index edc860a..c5e026a 100644 --- a/Tiano/EfiTianoCompress.h +++ b/Tiano/EfiTianoCompress.h @@ -5,7 +5,7 @@ This program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License which accompanies this distribution. The full text of the license may be found at http://opensource.org/licenses/bsd-license.php - + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, WITHWARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. @@ -43,12 +43,12 @@ Arguments: SrcSize - The size of source data DstBuffer - The buffer to store the compressed data DstSize - On input, the size of DstBuffer; On output, - the size of the actual compressed data. + the size of the actual compressed data. Returns: EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. this case, - DstSize contains the size needed. + DstSize contains the size needed. EFI_SUCCESS - Compression is successful. EFI_OUT_OF_RESOURCES - No resource to complete function. EFI_INVALID_PARAMETER - Parameter supplied is wrong. @@ -75,12 +75,12 @@ Arguments: SrcSize - The size of source data DstBuffer - The buffer to store the compressed data DstSize - On input, the size of DstBuffer; On output, - the size of the actual compressed data. + the size of the actual compressed data. Returns: EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. this case, - DstSize contains the size needed. + DstSize contains the size needed. EFI_SUCCESS - Compression is successful. EFI_OUT_OF_RESOURCES - No resource to complete function. EFI_INVALID_PARAMETER - Parameter supplied is wrong. diff --git a/Tiano/EfiTianoDecompress.c b/Tiano/EfiTianoDecompress.c index 4c4652f..cfba739 100644 --- a/Tiano/EfiTianoDecompress.c +++ b/Tiano/EfiTianoDecompress.c @@ -101,25 +101,25 @@ Sd->mBitBuf = (UINT32) (Sd->mBitBuf << NumOfBits); while (NumOfBits > Sd->mBitCount) { - Sd->mBitBuf |= (UINT32) (Sd->mSubBitBuf << (NumOfBits = (UINT16) (NumOfBits - Sd->mBitCount))); + Sd->mBitBuf |= (UINT32) (Sd->mSubBitBuf << (NumOfBits = (UINT16) (NumOfBits - Sd->mBitCount))); - if (Sd->mCompSize > 0) { - // - // Get 1 byte into SubBitBuf - // - Sd->mCompSize--; - Sd->mSubBitBuf = 0; - Sd->mSubBitBuf = Sd->mSrcBase[Sd->mInBuf++]; - Sd->mBitCount = 8; + if (Sd->mCompSize > 0) { + // + // Get 1 byte into SubBitBuf + // + Sd->mCompSize--; + Sd->mSubBitBuf = 0; + Sd->mSubBitBuf = Sd->mSrcBase[Sd->mInBuf++]; + Sd->mBitCount = 8; - } else { - // - // No more bits from the source, just pad zero bit. - // - Sd->mSubBitBuf = 0; - Sd->mBitCount = 8; + } else { + // + // No more bits from the source, just pad zero bit. + // + Sd->mSubBitBuf = 0; + Sd->mBitCount = 8; - } + } } Sd->mBitCount = (UINT16) (Sd->mBitCount - NumOfBits); @@ -204,43 +204,43 @@ UINT16 NextCode; UINT16 Mask; for (Index = 1; Index <= 16; Index++) { - Count[Index] = 0; + Count[Index] = 0; } for (Index = 0; Index < NumOfChar; Index++) { - Count[BitLen[Index]]++; + Count[BitLen[Index]]++; } Start[1] = 0; for (Index = 1; Index <= 16; Index++) { - Start[Index + 1] = (UINT16) (Start[Index] + (Count[Index] << (16 - Index))); + Start[Index + 1] = (UINT16) (Start[Index] + (Count[Index] << (16 - Index))); } if (Start[17] != 0) { - /*(1U << 16)*/ - return (UINT16) BAD_TABLE; + /*(1U << 16)*/ + return (UINT16) BAD_TABLE; } JuBits = (UINT16) (16 - TableBits); for (Index = 1; Index <= TableBits; Index++) { - Start[Index] >>= JuBits; - Weight[Index] = (UINT16) (1U << (TableBits - Index)); + Start[Index] >>= JuBits; + Weight[Index] = (UINT16) (1U << (TableBits - Index)); } while (Index <= 16) { - Weight[Index] = (UINT16) (1U << (16 - Index)); - Index++; + Weight[Index] = (UINT16) (1U << (16 - Index)); + Index++; } Index = (UINT16) (Start[TableBits + 1] >> JuBits); if (Index != 0) { - Index3 = (UINT16) (1U << TableBits); - while (Index != Index3) { - Table[Index++] = 0; - } + Index3 = (UINT16) (1U << TableBits); + while (Index != Index3) { + Table[Index++] = 0; + } } Avail = NumOfChar; @@ -248,46 +248,46 @@ Mask = (UINT16) (1U << (15 - TableBits)); for (Char = 0; Char < NumOfChar; Char++) { - Len = BitLen[Char]; - if (Len == 0) { - continue; - } + Len = BitLen[Char]; + if (Len == 0) { + continue; + } - NextCode = (UINT16) (Start[Len] + Weight[Len]); + NextCode = (UINT16) (Start[Len] + Weight[Len]); - if (Len <= TableBits) { + if (Len <= TableBits) { - for (Index = Start[Len]; Index < NextCode; Index++) { - Table[Index] = Char; - } + for (Index = Start[Len]; Index < NextCode; Index++) { + Table[Index] = Char; + } - } else { + } else { - Index3 = Start[Len]; - Pointer = &Table[Index3 >> JuBits]; - Index = (UINT16) (Len - TableBits); + Index3 = Start[Len]; + Pointer = &Table[Index3 >> JuBits]; + Index = (UINT16) (Len - TableBits); - while (Index != 0) { - if (*Pointer == 0) { - Sd->mRight[Avail] = Sd->mLeft[Avail] = 0; - *Pointer = Avail++; - } + while (Index != 0) { + if (*Pointer == 0) { + Sd->mRight[Avail] = Sd->mLeft[Avail] = 0; + *Pointer = Avail++; + } - if (Index3 & Mask) { - Pointer = &Sd->mRight[*Pointer]; - } else { - Pointer = &Sd->mLeft[*Pointer]; - } + if (Index3 & Mask) { + Pointer = &Sd->mRight[*Pointer]; + } else { + Pointer = &Sd->mLeft[*Pointer]; + } - Index3 <<= 1; - Index--; - } + Index3 <<= 1; + Index--; + } - *Pointer = Char; + *Pointer = Char; - } + } - Start[Len] = NextCode; + Start[Len] = NextCode; } // // Succeeds @@ -323,18 +323,18 @@ UINT32 Pos; Val = Sd->mPTTable[Sd->mBitBuf >> (BITBUFSIZ - 8)]; if (Val >= MAXNP) { - Mask = 1U << (BITBUFSIZ - 1 - 8); + Mask = 1U << (BITBUFSIZ - 1 - 8); - do { + do { - if (Sd->mBitBuf & Mask) { - Val = Sd->mRight[Val]; - } else { - Val = Sd->mLeft[Val]; - } + if (Sd->mBitBuf & Mask) { + Val = Sd->mRight[Val]; + } else { + Val = Sd->mLeft[Val]; + } - Mask >>= 1; - } while (Val >= MAXNP); + Mask >>= 1; + } while (Val >= MAXNP); } // // Advance what we have read @@ -343,7 +343,7 @@ FillBuf (Sd, Sd->mPTLen[Val]); Pos = Val; if (Val > 1) { - Pos = (UINT32) ((1U << (Val - 1)) + GetBits (Sd, (UINT16) (Val - 1))); + Pos = (UINT32) ((1U << (Val - 1)) + GetBits (Sd, (UINT16) (Val - 1))); } return Pos; @@ -385,47 +385,47 @@ UINT32 Mask; Number = (UINT16) GetBits (Sd, nbit); if (Number == 0) { - CharC = (UINT16) GetBits (Sd, nbit); + CharC = (UINT16) GetBits (Sd, nbit); - for (Index = 0; Index < 256; Index++) { - Sd->mPTTable[Index] = CharC; - } + for (Index = 0; Index < 256; Index++) { + Sd->mPTTable[Index] = CharC; + } - for (Index = 0; Index < nn; Index++) { - Sd->mPTLen[Index] = 0; - } + for (Index = 0; Index < nn; Index++) { + Sd->mPTLen[Index] = 0; + } - return 0; + return 0; } Index = 0; while (Index < Number) { - CharC = (UINT16) (Sd->mBitBuf >> (BITBUFSIZ - 3)); + CharC = (UINT16) (Sd->mBitBuf >> (BITBUFSIZ - 3)); - if (CharC == 7) { - Mask = 1U << (BITBUFSIZ - 1 - 3); - while (Mask & Sd->mBitBuf) { - Mask >>= 1; - CharC += 1; - } - } + if (CharC == 7) { + Mask = 1U << (BITBUFSIZ - 1 - 3); + while (Mask & Sd->mBitBuf) { + Mask >>= 1; + CharC += 1; + } + } - FillBuf (Sd, (UINT16) ((CharC < 7) ? 3 : CharC - 3)); + FillBuf (Sd, (UINT16) ((CharC < 7) ? 3 : CharC - 3)); - Sd->mPTLen[Index++] = (UINT8) CharC; + Sd->mPTLen[Index++] = (UINT8) CharC; - if (Index == Special) { - CharC = (UINT16) GetBits (Sd, 2); - while ((INT16) (--CharC) >= 0) { - Sd->mPTLen[Index++] = 0; - } - } + if (Index == Special) { + CharC = (UINT16) GetBits (Sd, 2); + while ((INT16) (--CharC) >= 0) { + Sd->mPTLen[Index++] = 0; + } + } } while (Index < nn) { - Sd->mPTLen[Index++] = 0; + Sd->mPTLen[Index++] = 0; } return MakeTable (Sd, nn, Sd->mPTLen, 8, Sd->mPTTable); @@ -458,66 +458,66 @@ UINT32 Mask; Number = (UINT16) GetBits (Sd, CBIT); if (Number == 0) { - CharC = (UINT16) GetBits (Sd, CBIT); + CharC = (UINT16) GetBits (Sd, CBIT); - for (Index = 0; Index < NC; Index++) { - Sd->mCLen[Index] = 0; - } + for (Index = 0; Index < NC; Index++) { + Sd->mCLen[Index] = 0; + } - for (Index = 0; Index < 4096; Index++) { - Sd->mCTable[Index] = CharC; - } + for (Index = 0; Index < 4096; Index++) { + Sd->mCTable[Index] = CharC; + } - return ; + return ; } Index = 0; while (Index < Number) { - CharC = Sd->mPTTable[Sd->mBitBuf >> (BITBUFSIZ - 8)]; - if (CharC >= NT) { - Mask = 1U << (BITBUFSIZ - 1 - 8); + CharC = Sd->mPTTable[Sd->mBitBuf >> (BITBUFSIZ - 8)]; + if (CharC >= NT) { + Mask = 1U << (BITBUFSIZ - 1 - 8); - do { + do { - if (Mask & Sd->mBitBuf) { - CharC = Sd->mRight[CharC]; - } else { - CharC = Sd->mLeft[CharC]; - } + if (Mask & Sd->mBitBuf) { + CharC = Sd->mRight[CharC]; + } else { + CharC = Sd->mLeft[CharC]; + } - Mask >>= 1; + Mask >>= 1; - } while (CharC >= NT); - } - // - // Advance what we have read - // - FillBuf (Sd, Sd->mPTLen[CharC]); + } while (CharC >= NT); + } + // + // Advance what we have read + // + FillBuf (Sd, Sd->mPTLen[CharC]); - if (CharC <= 2) { + if (CharC <= 2) { - if (CharC == 0) { - CharC = 1; - } else if (CharC == 1) { - CharC = (UINT16) (GetBits (Sd, 4) + 3); - } else if (CharC == 2) { - CharC = (UINT16) (GetBits (Sd, CBIT) + 20); - } + if (CharC == 0) { + CharC = 1; + } else if (CharC == 1) { + CharC = (UINT16) (GetBits (Sd, 4) + 3); + } else if (CharC == 2) { + CharC = (UINT16) (GetBits (Sd, CBIT) + 20); + } - while ((INT16) (--CharC) >= 0) { - Sd->mCLen[Index++] = 0; - } + while ((INT16) (--CharC) >= 0) { + Sd->mCLen[Index++] = 0; + } - } else { + } else { - Sd->mCLen[Index++] = (UINT8) (CharC - 2); + Sd->mCLen[Index++] = (UINT8) (CharC - 2); - } + } } while (Index < NC) { - Sd->mCLen[Index++] = 0; + Sd->mCLen[Index++] = 0; } MakeTable (Sd, NC, Sd->mCLen, 12, Sd->mCTable); @@ -550,38 +550,38 @@ UINT16 Index2; UINT32 Mask; if (Sd->mBlockSize == 0) { - // - // Starting a new block - // - Sd->mBlockSize = (UINT16) GetBits (Sd, 16); - Sd->mBadTableFlag = ReadPTLen (Sd, NT, TBIT, 3); - if (Sd->mBadTableFlag != 0) { - return 0; - } + // + // Starting a new block + // + Sd->mBlockSize = (UINT16) GetBits (Sd, 16); + Sd->mBadTableFlag = ReadPTLen (Sd, NT, TBIT, 3); + if (Sd->mBadTableFlag != 0) { + return 0; + } - ReadCLen (Sd); + ReadCLen (Sd); - Sd->mBadTableFlag = ReadPTLen (Sd, MAXNP, Sd->mPBit, (UINT16) (-1)); - if (Sd->mBadTableFlag != 0) { - return 0; - } + Sd->mBadTableFlag = ReadPTLen (Sd, MAXNP, Sd->mPBit, (UINT16) (-1)); + if (Sd->mBadTableFlag != 0) { + return 0; + } } Sd->mBlockSize--; Index2 = Sd->mCTable[Sd->mBitBuf >> (BITBUFSIZ - 12)]; if (Index2 >= NC) { - Mask = 1U << (BITBUFSIZ - 1 - 12); + Mask = 1U << (BITBUFSIZ - 1 - 12); - do { - if (Sd->mBitBuf & Mask) { - Index2 = Sd->mRight[Index2]; - } else { - Index2 = Sd->mLeft[Index2]; - } + do { + if (Sd->mBitBuf & Mask) { + Index2 = Sd->mRight[Index2]; + } else { + Index2 = Sd->mLeft[Index2]; + } - Mask >>= 1; - } while (Index2 >= NC); + Mask >>= 1; + } while (Index2 >= NC); } // // Advance what we have read @@ -619,41 +619,41 @@ BytesRemain = (UINT16) (-1); DataIdx = 0; for (;;) { - CharC = DecodeC (Sd); - if (Sd->mBadTableFlag != 0) { - return ; - } + CharC = DecodeC (Sd); + if (Sd->mBadTableFlag != 0) { + return ; + } - if (CharC < 256) { - // - // Process an Original character - // - if (Sd->mOutBuf >= Sd->mOrigSize) { - return ; - } else { - Sd->mDstBase[Sd->mOutBuf++] = (UINT8) CharC; - } + if (CharC < 256) { + // + // Process an Original character + // + if (Sd->mOutBuf >= Sd->mOrigSize) { + return ; + } else { + Sd->mDstBase[Sd->mOutBuf++] = (UINT8) CharC; + } - } else { - // - // Process a Pointer - // - CharC = (UINT16) (CharC - (UINT8_MAX + 1 - THRESHOLD)); + } else { + // + // Process a Pointer + // + CharC = (UINT16) (CharC - (UINT8_MAX + 1 - THRESHOLD)); - BytesRemain = CharC; + BytesRemain = CharC; - DataIdx = Sd->mOutBuf - DecodeP (Sd) - 1; + DataIdx = Sd->mOutBuf - DecodeP (Sd) - 1; - BytesRemain--; - while ((INT16) (BytesRemain) >= 0) { - Sd->mDstBase[Sd->mOutBuf++] = Sd->mDstBase[DataIdx++]; - if (Sd->mOutBuf >= Sd->mOrigSize) { - return ; - } + BytesRemain--; + while ((INT16) (BytesRemain) >= 0) { + Sd->mDstBase[Sd->mOutBuf++] = Sd->mDstBase[DataIdx++]; + if (Sd->mOutBuf >= Sd->mOrigSize) { + return ; + } - BytesRemain--; - } - } + BytesRemain--; + } + } } return ; @@ -692,7 +692,7 @@ UINT8 *Src; Src = Source; if (SrcSize < 8) { - return ERR_INVALID_PARAMETER; + return ERR_INVALID_PARAMETER; } *DstSize = Src[4] + (Src[5] << 8) + (Src[6] << 16) + (Src[7] << 24); @@ -747,13 +747,13 @@ Src = Source; Dst = Destination; if (ScratchSize < sizeof (SCRATCH_DATA)) { - return ERR_INVALID_PARAMETER; + return ERR_INVALID_PARAMETER; } Sd = (SCRATCH_DATA *) Scratch; if (SrcSize < 8) { - return ERR_INVALID_PARAMETER; + return ERR_INVALID_PARAMETER; } CompSize = Src[0] + (Src[1] << 8) + (Src[2] << 16) + (Src[3] << 24); @@ -763,21 +763,21 @@ OrigSize = Src[4] + (Src[5] << 8) + (Src[6] << 16) + (Src[7] << 24); // If compressed file size is 0, return // if (OrigSize == 0) { - return Status; + return Status; } if (SrcSize < CompSize + 8) { - return ERR_INVALID_PARAMETER; + return ERR_INVALID_PARAMETER; } if (DstSize != OrigSize) { - return ERR_INVALID_PARAMETER; + return ERR_INVALID_PARAMETER; } Src = Src + 8; for (Index = 0; Index < sizeof (SCRATCH_DATA); Index++) { - ((UINT8 *) Sd)[Index] = 0; + ((UINT8 *) Sd)[Index] = 0; } // // The length of the field 'Position Set Code Length Array Size'Block Header. @@ -786,18 +786,18 @@ for (Index = 0; Index < sizeof (SCRATCH_DATA); Index++) { // switch (Version) { case 1: - Sd->mPBit = 4; - break; + Sd->mPBit = 4; + break; case 2: - Sd->mPBit = 5; - break; + Sd->mPBit = 5; + break; default: - // - // Currently, only have 2 versions - // - return ERR_INVALID_PARAMETER; + // + // Currently, only have 2 versions + // + return ERR_INVALID_PARAMETER; } Sd->mSrcBase = Src; @@ -816,10 +816,10 @@ FillBuf (Sd, BITBUFSIZ); Decode (Sd); if (Sd->mBadTableFlag != 0) { - // - // Something wrong with the source - // - Status = ERR_INVALID_PARAMETER; + // + // Something wrong with the source + // + Status = ERR_INVALID_PARAMETER; } return Status; @@ -862,14 +862,14 @@ EFI_INVALID_PARAMETER - The source data is corrupted // For EFI 1.1 de/compression algorithm, the version is 1. // return Decompress ( - Source, - SrcSize, - Destination, - DstSize, - Scratch, - ScratchSize, - 1 - ); + Source, + SrcSize, + Destination, + DstSize, + Scratch, + ScratchSize, + 1 + ); } UINT32 @@ -909,13 +909,13 @@ EFI_INVALID_PARAMETER - The source data is corrupted // For Tiano de/compression algorithm, the version is 2. // return Decompress ( - Source, - SrcSize, - Destination, - DstSize, - Scratch, - ScratchSize, - 2 - ); + Source, + SrcSize, + Destination, + DstSize, + Scratch, + ScratchSize, + 2 + ); } diff --git a/Tiano/EfiTianoDecompress.h b/Tiano/EfiTianoDecompress.h index aa1896f..512aa1b 100644 --- a/Tiano/EfiTianoDecompress.h +++ b/Tiano/EfiTianoDecompress.h @@ -31,8 +31,8 @@ Providing both EFI and Tiano decompress algorithms. extern "C" { #endif typedef struct { - UINT32 CompSize; - UINT32 OrigSize; + UINT32 CompSize; + UINT32 OrigSize; } EFI_TIANO_HEADER; UINT32 diff --git a/Tiano/TianoCompress.c b/Tiano/TianoCompress.c index 4d50af1..970f7a9 100644 --- a/Tiano/TianoCompress.c +++ b/Tiano/TianoCompress.c @@ -65,190 +65,190 @@ typedef INT32 NODE; // STATIC - VOID - PutDword( - UINT32 Data - ); + VOID + PutDword( + UINT32 Data + ); STATIC - INT32 - AllocateMemory ( - VOID - ); + INT32 + AllocateMemory ( + VOID + ); STATIC - VOID - FreeMemory ( - VOID - ); + VOID + FreeMemory ( + VOID + ); STATIC - VOID - InitSlide ( - VOID - ); + VOID + InitSlide ( + VOID + ); STATIC - NODE - Child ( - NODE NodeQ, - UINT8 CharC - ); + NODE + Child ( + NODE NodeQ, + UINT8 CharC + ); STATIC - VOID - MakeChild ( - NODE NodeQ, - UINT8 CharC, - NODE NodeR - ); + VOID + MakeChild ( + NODE NodeQ, + UINT8 CharC, + NODE NodeR + ); STATIC - VOID - Split ( - NODE Old - ); + VOID + Split ( + NODE Old + ); STATIC - VOID - InsertNode ( - VOID - ); + VOID + InsertNode ( + VOID + ); STATIC - VOID - DeleteNode ( - VOID - ); + VOID + DeleteNode ( + VOID + ); STATIC - VOID - GetNextMatch ( - VOID - ); + VOID + GetNextMatch ( + VOID + ); STATIC - INT32 - Encode ( - VOID - ); + INT32 + Encode ( + VOID + ); STATIC - VOID - CountTFreq ( - VOID - ); + VOID + CountTFreq ( + VOID + ); STATIC - VOID - WritePTLen ( - INT32 Number, - INT32 nbit, - INT32 Special - ); + VOID + WritePTLen ( + INT32 Number, + INT32 nbit, + INT32 Special + ); STATIC - VOID - WriteCLen ( - VOID - ); + VOID + WriteCLen ( + VOID + ); STATIC - VOID - EncodeC ( - INT32 Value - ); + VOID + EncodeC ( + INT32 Value + ); STATIC - VOID - EncodeP ( - UINT32 Value - ); + VOID + EncodeP ( + UINT32 Value + ); STATIC - VOID - SendBlock ( - VOID - ); + VOID + SendBlock ( + VOID + ); STATIC - VOID - Output ( - UINT32 c, - UINT32 p - ); + VOID + Output ( + UINT32 c, + UINT32 p + ); STATIC - VOID - HufEncodeStart ( - VOID - ); + VOID + HufEncodeStart ( + VOID + ); STATIC - VOID - HufEncodeEnd ( - VOID - ); + VOID + HufEncodeEnd ( + VOID + ); STATIC - VOID - MakeCrcTable ( - VOID - ); + VOID + MakeCrcTable ( + VOID + ); STATIC - VOID - PutBits ( - INT32 Number, - UINT32 Value - ); + VOID + PutBits ( + INT32 Number, + UINT32 Value + ); STATIC - INT32 - FreadCrc ( - UINT8 *Pointer, - INT32 Number - ); + INT32 + FreadCrc ( + UINT8 *Pointer, + INT32 Number + ); STATIC - VOID - InitPutBits ( - VOID - ); + VOID + InitPutBits ( + VOID + ); STATIC - VOID - CountLen ( - INT32 Index - ); + VOID + CountLen ( + INT32 Index + ); STATIC - VOID - MakeLen ( - INT32 Root - ); + VOID + MakeLen ( + INT32 Root + ); STATIC - VOID - DownHeap ( - INT32 Index - ); + VOID + DownHeap ( + INT32 Index + ); STATIC - VOID - MakeCode ( - INT32 Number, - UINT8 Len[ ], - UINT16 Code[] + VOID + MakeCode ( + INT32 Number, + UINT8 Len[ ], + UINT16 Code[] ); STATIC - INT32 - MakeTree ( - INT32 NParm, - UINT16 FreqParm[], - UINT8 LenParm[ ], - UINT16 CodeParm[] + INT32 + MakeTree ( + INT32 NParm, + UINT16 FreqParm[], + UINT8 LenParm[ ], + UINT16 CodeParm[] ); // @@ -263,7 +263,7 @@ STATIC UINT32 mBufSiz = 0, mOutputPos, mOutputMask, mSubBitBuf, mCrc; STATIC UINT32 mCompSize, mOrigSize; STATIC UINT16 *mFreq, *mSortPtr, mLenCnt[17], mLeft[2 * NC - 1], mRight[2 * NC - 1], mCrcTable[UINT8_MAX + 1], - mCFreq[2 * NC - 1], mCCode[NC], mPFreq[2 * NP - 1], mPTCode[NPT], mTFreq[2 * NT - 1]; + mCFreq[2 * NC - 1], mCCode[NC], mPFreq[2 * NP - 1], mPTCode[NPT], mTFreq[2 * NT - 1]; STATIC NODE mPos, mMatchPos, mAvail, *mPosition, *mParent, *mPrev, *mNext = NULL; @@ -271,1483 +271,1483 @@ STATIC NODE mPos, mMatchPos, mAvail, *mPosition, *mParent, *mPrev, *mNext = NU // functions // INT32 - TianoCompress ( - UINT8 *SrcBuffer, - UINT32 SrcSize, - UINT8 *DstBuffer, - UINT32 *DstSize - ) - /*++ + TianoCompress ( + UINT8 *SrcBuffer, + UINT32 SrcSize, + UINT8 *DstBuffer, + UINT32 *DstSize + ) + /*++ - Routine Description: + Routine Description: - The internal implementation of [Efi/Tiano]Compress(). + The internal implementation of [Efi/Tiano]Compress(). - Arguments: + Arguments: - SrcBuffer - The buffer storing the source data - SrcSize - The size of source data - DstBuffer - The buffer to store the compressed data - DstSize - On input, the size of DstBuffer; On output, - the size of the actual compressed data. - Version - The version of de/compression algorithm. - Version 1 for UEFI 2.0 de/compression algorithm. - Version 2 for Tiano de/compression algorithm. + SrcBuffer - The buffer storing the source data + SrcSize - The size of source data + DstBuffer - The buffer to store the compressed data + DstSize - On input, the size of DstBuffer; On output, + the size of the actual compressed data. + Version - The version of de/compression algorithm. + Version 1 for UEFI 2.0 de/compression algorithm. + Version 2 for Tiano de/compression algorithm. - Returns: + Returns: - EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. this case, - DstSize contains the size needed. - EFI_SUCCESS - Compression is successful. - EFI_OUT_OF_RESOURCES - No resource to complete function. - EFI_INVALID_PARAMETER - Parameter supplied is wrong. + EFI_BUFFER_TOO_SMALL - The DstBuffer is too small. this case, + DstSize contains the size needed. + EFI_SUCCESS - Compression is successful. + EFI_OUT_OF_RESOURCES - No resource to complete function. + EFI_INVALID_PARAMETER - Parameter supplied is wrong. - --*/ + --*/ { - INT32 Status; + INT32 Status; - // - // Initializations - // - mBufSiz = 0; - mBuf = NULL; - mText = NULL; - mLevel = NULL; - mChildCount = NULL; - mPosition = NULL; - mParent = NULL; - mPrev = NULL; - mNext = NULL; + // + // Initializations + // + mBufSiz = 0; + mBuf = NULL; + mText = NULL; + mLevel = NULL; + mChildCount = NULL; + mPosition = NULL; + mParent = NULL; + mPrev = NULL; + mNext = NULL; - mSrc = SrcBuffer; - mSrcUpperLimit = mSrc + SrcSize; - mDst = DstBuffer; - mDstUpperLimit = mDst +*DstSize; + mSrc = SrcBuffer; + mSrcUpperLimit = mSrc + SrcSize; + mDst = DstBuffer; + mDstUpperLimit = mDst +*DstSize; - PutDword (0L); - PutDword (0L); + PutDword (0L); + PutDword (0L); - MakeCrcTable (); + MakeCrcTable (); - mOrigSize = mCompSize = 0; - mCrc = INIT_CRC; + mOrigSize = mCompSize = 0; + mCrc = INIT_CRC; - // - // Compress it - // - Status = Encode (); - if (Status) { - return ERR_OUT_OF_RESOURCES; - } - // - // Null terminate the compressed data - // - if (mDst < mDstUpperLimit) { - *mDst++ = 0; - } - // - // Fill compressed size and original size - // - mDst = DstBuffer; - PutDword (mCompSize + 1); - PutDword (mOrigSize); + // + // Compress it + // + Status = Encode (); + if (Status) { + return ERR_OUT_OF_RESOURCES; + } + // + // Null terminate the compressed data + // + if (mDst < mDstUpperLimit) { + *mDst++ = 0; + } + // + // Fill compressed size and original size + // + mDst = DstBuffer; + PutDword (mCompSize + 1); + PutDword (mOrigSize); - // - // Return - // - if (mCompSize + 1 + 8 > *DstSize) { - *DstSize = mCompSize + 1 + 8; - return ERR_BUFFER_TOO_SMALL; - } else { - *DstSize = mCompSize + 1 + 8; - return ERR_SUCCESS; - } + // + // Return + // + if (mCompSize + 1 + 8 > *DstSize) { + *DstSize = mCompSize + 1 + 8; + return ERR_BUFFER_TOO_SMALL; + } else { + *DstSize = mCompSize + 1 + 8; + return ERR_SUCCESS; + } } STATIC - VOID - PutDword ( - UINT32 Data - ) - /*++ + VOID + PutDword ( + UINT32 Data + ) + /*++ - Routine Description: + Routine Description: - Put a dword to output stream + Put a dword to output stream - Arguments: + Arguments: - Data - the dword to put + Data - the dword to put - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8) (((UINT8) (Data)) & 0xff); - } + if (mDst < mDstUpperLimit) { + *mDst++ = (UINT8) (((UINT8) (Data)) & 0xff); + } - if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8) (((UINT8) (Data >> 0x08)) & 0xff); - } + if (mDst < mDstUpperLimit) { + *mDst++ = (UINT8) (((UINT8) (Data >> 0x08)) & 0xff); + } - if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8) (((UINT8) (Data >> 0x10)) & 0xff); - } + if (mDst < mDstUpperLimit) { + *mDst++ = (UINT8) (((UINT8) (Data >> 0x10)) & 0xff); + } - if (mDst < mDstUpperLimit) { - *mDst++ = (UINT8) (((UINT8) (Data >> 0x18)) & 0xff); - } + if (mDst < mDstUpperLimit) { + *mDst++ = (UINT8) (((UINT8) (Data >> 0x18)) & 0xff); + } } STATIC - INT32 - AllocateMemory ( - VOID - ) - /*++ + INT32 + AllocateMemory ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Allocate memory spaces for data structures used compression process + Allocate memory spaces for data structures used compression process - Argements: - VOID + Argements: + VOID - Returns: + Returns: - EFI_SUCCESS - Memory is allocated successfully - EFI_OUT_OF_RESOURCES - Allocation fails + EFI_SUCCESS - Memory is allocated successfully + EFI_OUT_OF_RESOURCES - Allocation fails - --*/ + --*/ { - UINT32 Index; + UINT32 Index; - mText = malloc (WNDSIZ * 2 + MAXMATCH); - for (Index = 0; Index < WNDSIZ * 2 + MAXMATCH; Index++) { - mText[Index] = 0; - } + mText = malloc (WNDSIZ * 2 + MAXMATCH); + for (Index = 0; Index < WNDSIZ * 2 + MAXMATCH; Index++) { + mText[Index] = 0; + } - mLevel = malloc ((WNDSIZ + UINT8_MAX + 1) * sizeof (*mLevel)); - mChildCount = malloc ((WNDSIZ + UINT8_MAX + 1) * sizeof (*mChildCount)); - mPosition = malloc ((WNDSIZ + UINT8_MAX + 1) * sizeof (*mPosition)); - mParent = malloc (WNDSIZ * 2 * sizeof (*mParent)); - mPrev = malloc (WNDSIZ * 2 * sizeof (*mPrev)); - mNext = malloc ((MAX_HASH_VAL + 1) * sizeof (*mNext)); + mLevel = malloc ((WNDSIZ + UINT8_MAX + 1) * sizeof (*mLevel)); + mChildCount = malloc ((WNDSIZ + UINT8_MAX + 1) * sizeof (*mChildCount)); + mPosition = malloc ((WNDSIZ + UINT8_MAX + 1) * sizeof (*mPosition)); + mParent = malloc (WNDSIZ * 2 * sizeof (*mParent)); + mPrev = malloc (WNDSIZ * 2 * sizeof (*mPrev)); + mNext = malloc ((MAX_HASH_VAL + 1) * sizeof (*mNext)); - mBufSiz = BLKSIZ; - mBuf = malloc (mBufSiz); - while (mBuf == NULL) { - mBufSiz = (mBufSiz / 10U) * 9U; - if (mBufSiz < 4 * 1024U) { - return ERR_OUT_OF_RESOURCES; - } + mBufSiz = BLKSIZ; + mBuf = malloc (mBufSiz); + while (mBuf == NULL) { + mBufSiz = (mBufSiz / 10U) * 9U; + if (mBufSiz < 4 * 1024U) { + return ERR_OUT_OF_RESOURCES; + } - mBuf = malloc (mBufSiz); - } + mBuf = malloc (mBufSiz); + } - mBuf[0] = 0; + mBuf[0] = 0; - return ERR_SUCCESS; + return ERR_SUCCESS; } VOID - FreeMemory ( - VOID - ) - /*++ + FreeMemory ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Called when compression is completed to free memory previously allocated. + Called when compression is completed to free memory previously allocated. - Arguments: (VOID) + Arguments: (VOID) - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - if (mText != NULL) { - free (mText); - } + if (mText != NULL) { + free (mText); + } - if (mLevel != NULL) { - free (mLevel); - } + if (mLevel != NULL) { + free (mLevel); + } - if (mChildCount != NULL) { - free (mChildCount); - } + if (mChildCount != NULL) { + free (mChildCount); + } - if (mPosition != NULL) { - free (mPosition); - } + if (mPosition != NULL) { + free (mPosition); + } - if (mParent != NULL) { - free (mParent); - } + if (mParent != NULL) { + free (mParent); + } - if (mPrev != NULL) { - free (mPrev); - } + if (mPrev != NULL) { + free (mPrev); + } - if (mNext != NULL) { - free (mNext); - } + if (mNext != NULL) { + free (mNext); + } - if (mBuf != NULL) { - free (mBuf); - } + if (mBuf != NULL) { + free (mBuf); + } - return ; + return ; } STATIC - VOID - InitSlide ( - VOID - ) - /*++ + VOID + InitSlide ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Initialize String Info Log data structures + Initialize String Info Log data structures - Arguments: (VOID) + Arguments: (VOID) - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - NODE Index; + NODE Index; - for (Index = WNDSIZ; Index <= WNDSIZ + UINT8_MAX; Index++) { - mLevel[Index] = 1; - mPosition[Index] = NIL; // sentinel - } + for (Index = WNDSIZ; Index <= WNDSIZ + UINT8_MAX; Index++) { + mLevel[Index] = 1; + mPosition[Index] = NIL; // sentinel + } - for (Index = WNDSIZ; Index < WNDSIZ * 2; Index++) { - mParent[Index] = NIL; - } + for (Index = WNDSIZ; Index < WNDSIZ * 2; Index++) { + mParent[Index] = NIL; + } - mAvail = 1; - for (Index = 1; Index < WNDSIZ - 1; Index++) { - mNext[Index] = (NODE) (Index + 1); - } + mAvail = 1; + for (Index = 1; Index < WNDSIZ - 1; Index++) { + mNext[Index] = (NODE) (Index + 1); + } - mNext[WNDSIZ - 1] = NIL; - for (Index = WNDSIZ * 2; Index <= MAX_HASH_VAL; Index++) { - mNext[Index] = NIL; - } + mNext[WNDSIZ - 1] = NIL; + for (Index = WNDSIZ * 2; Index <= MAX_HASH_VAL; Index++) { + mNext[Index] = NIL; + } } STATIC - NODE - Child ( - NODE NodeQ, - UINT8 CharC - ) - /*++ + NODE + Child ( + NODE NodeQ, + UINT8 CharC + ) + /*++ - Routine Description: + Routine Description: - Find child node given the parent node and the edge character + Find child node given the parent node and the edge character - Arguments: + Arguments: - NodeQ - the parent node - CharC - the edge character + NodeQ - the parent node + CharC - the edge character - Returns: + Returns: - The child node (NIL if not found) + The child node (NIL if not found) - --*/ + --*/ { - NODE NodeR; + NODE NodeR; - NodeR = mNext[HASH (NodeQ, CharC)]; - // - // sentinel - // - mParent[NIL] = NodeQ; - while (mParent[NodeR] != NodeQ) { - NodeR = mNext[NodeR]; - } + NodeR = mNext[HASH (NodeQ, CharC)]; + // + // sentinel + // + mParent[NIL] = NodeQ; + while (mParent[NodeR] != NodeQ) { + NodeR = mNext[NodeR]; + } - return NodeR; + return NodeR; } STATIC - VOID - MakeChild ( - NODE Parent, - UINT8 CharC, - NODE Child - ) - /*++ + VOID + MakeChild ( + NODE Parent, + UINT8 CharC, + NODE Child + ) + /*++ - Routine Description: + Routine Description: - Create a new child for a given parent node. + Create a new child for a given parent node. - Arguments: + Arguments: - Parent - the parent node - CharC - the edge character - Child - the child node + Parent - the parent node + CharC - the edge character + Child - the child node - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - NODE Node1; - NODE Node2; + NODE Node1; + NODE Node2; - Node1 = (NODE) HASH (Parent, CharC); - Node2 = mNext[Node1]; - mNext[Node1] = Child; - mNext[Child] = Node2; - mPrev[Node2] = Child; - mPrev[Child] = Node1; - mParent[Child] = Parent; - mChildCount[Parent]++; + Node1 = (NODE) HASH (Parent, CharC); + Node2 = mNext[Node1]; + mNext[Node1] = Child; + mNext[Child] = Node2; + mPrev[Node2] = Child; + mPrev[Child] = Node1; + mParent[Child] = Parent; + mChildCount[Parent]++; } STATIC - VOID - Split ( - NODE Old - ) - /*++ + VOID + Split ( + NODE Old + ) + /*++ - Routine Description: + Routine Description: - Split a node. + Split a node. - Arguments: + Arguments: - Old - the node to split + Old - the node to split - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - NODE New; - NODE TempNode; + NODE New; + NODE TempNode; - New = mAvail; - mAvail = mNext[New]; - mChildCount[New] = 0; - TempNode = mPrev[Old]; - mPrev[New] = TempNode; - mNext[TempNode] = New; - TempNode = mNext[Old]; - mNext[New] = TempNode; - mPrev[TempNode] = New; - mParent[New] = mParent[Old]; - mLevel[New] = (UINT8) mMatchLen; - mPosition[New] = mPos; - MakeChild (New, mText[mMatchPos + mMatchLen], Old); - MakeChild (New, mText[mPos + mMatchLen], mPos); + New = mAvail; + mAvail = mNext[New]; + mChildCount[New] = 0; + TempNode = mPrev[Old]; + mPrev[New] = TempNode; + mNext[TempNode] = New; + TempNode = mNext[Old]; + mNext[New] = TempNode; + mPrev[TempNode] = New; + mParent[New] = mParent[Old]; + mLevel[New] = (UINT8) mMatchLen; + mPosition[New] = mPos; + MakeChild (New, mText[mMatchPos + mMatchLen], Old); + MakeChild (New, mText[mPos + mMatchLen], mPos); } STATIC - VOID - InsertNode ( - VOID - ) - /*++ + VOID + InsertNode ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Insert string info for current position into the String Info Log + Insert string info for current position into the String Info Log - Arguments: (VOID) + Arguments: (VOID) - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - NODE NodeQ; - NODE NodeR; - NODE Index2; - NODE NodeT; - UINT8 CharC; - UINT8 *t1; - UINT8 *t2; + NODE NodeQ; + NODE NodeR; + NODE Index2; + NODE NodeT; + UINT8 CharC; + UINT8 *t1; + UINT8 *t2; - if (mMatchLen >= 4) { - // - // We have just got a long match, the target tree - // can be located by MatchPos + 1. Travese the tree - // from bottom up to get to a proper starting point. - // The usage of PERC_FLAG ensures proper node deletion - // DeleteNode() later. - // - mMatchLen--; - NodeR = (NODE) ((mMatchPos + 1) | WNDSIZ); - NodeQ = mParent[NodeR]; - while (NodeQ == NIL) { - NodeR = mNext[NodeR]; - NodeQ = mParent[NodeR]; - } + if (mMatchLen >= 4) { + // + // We have just got a long match, the target tree + // can be located by MatchPos + 1. Travese the tree + // from bottom up to get to a proper starting point. + // The usage of PERC_FLAG ensures proper node deletion + // DeleteNode() later. + // + mMatchLen--; + NodeR = (NODE) ((mMatchPos + 1) | WNDSIZ); + NodeQ = mParent[NodeR]; + while (NodeQ == NIL) { + NodeR = mNext[NodeR]; + NodeQ = mParent[NodeR]; + } - while (mLevel[NodeQ] >= mMatchLen) { - NodeR = NodeQ; - NodeQ = mParent[NodeQ]; - } + while (mLevel[NodeQ] >= mMatchLen) { + NodeR = NodeQ; + NodeQ = mParent[NodeQ]; + } - NodeT = NodeQ; - while (mPosition[NodeT] < 0) { - mPosition[NodeT] = mPos; - NodeT = mParent[NodeT]; - } + NodeT = NodeQ; + while (mPosition[NodeT] < 0) { + mPosition[NodeT] = mPos; + NodeT = mParent[NodeT]; + } - if (NodeT < WNDSIZ) { - mPosition[NodeT] = (NODE) (mPos | (UINT32) PERC_FLAG); - } - } else { - // - // Locate the target tree - // - NodeQ = (NODE) (mText[mPos] + WNDSIZ); - CharC = mText[mPos + 1]; - NodeR = Child (NodeQ, CharC); - if (NodeR == NIL) { - MakeChild (NodeQ, CharC, mPos); - mMatchLen = 1; - return ; - } + if (NodeT < WNDSIZ) { + mPosition[NodeT] = (NODE) (mPos | (UINT32) PERC_FLAG); + } + } else { + // + // Locate the target tree + // + NodeQ = (NODE) (mText[mPos] + WNDSIZ); + CharC = mText[mPos + 1]; + NodeR = Child (NodeQ, CharC); + if (NodeR == NIL) { + MakeChild (NodeQ, CharC, mPos); + mMatchLen = 1; + return ; + } - mMatchLen = 2; - } - // - // Traverse down the tree to find a match. - // Update Position value along the route. - // Node split or creation is involved. - // - for (;;) { - if (NodeR >= WNDSIZ) { - Index2 = MAXMATCH; - mMatchPos = NodeR; - } else { - Index2 = mLevel[NodeR]; - mMatchPos = (NODE) (mPosition[NodeR] & (UINT32)~PERC_FLAG); - } + mMatchLen = 2; + } + // + // Traverse down the tree to find a match. + // Update Position value along the route. + // Node split or creation is involved. + // + for (;;) { + if (NodeR >= WNDSIZ) { + Index2 = MAXMATCH; + mMatchPos = NodeR; + } else { + Index2 = mLevel[NodeR]; + mMatchPos = (NODE) (mPosition[NodeR] & (UINT32)~PERC_FLAG); + } - if (mMatchPos >= mPos) { - mMatchPos -= WNDSIZ; - } + if (mMatchPos >= mPos) { + mMatchPos -= WNDSIZ; + } - t1 = &mText[mPos + mMatchLen]; - t2 = &mText[mMatchPos + mMatchLen]; - while (mMatchLen < Index2) { - if (*t1 != *t2) { - Split (NodeR); - return ; - } + t1 = &mText[mPos + mMatchLen]; + t2 = &mText[mMatchPos + mMatchLen]; + while (mMatchLen < Index2) { + if (*t1 != *t2) { + Split (NodeR); + return ; + } - mMatchLen++; - t1++; - t2++; - } + mMatchLen++; + t1++; + t2++; + } - if (mMatchLen >= MAXMATCH) { - break; - } + if (mMatchLen >= MAXMATCH) { + break; + } - mPosition[NodeR] = mPos; - NodeQ = NodeR; - NodeR = Child (NodeQ, *t1); - if (NodeR == NIL) { - MakeChild (NodeQ, *t1, mPos); - return ; - } + mPosition[NodeR] = mPos; + NodeQ = NodeR; + NodeR = Child (NodeQ, *t1); + if (NodeR == NIL) { + MakeChild (NodeQ, *t1, mPos); + return ; + } - mMatchLen++; - } + mMatchLen++; + } - NodeT = mPrev[NodeR]; - mPrev[mPos] = NodeT; - mNext[NodeT] = mPos; - NodeT = mNext[NodeR]; - mNext[mPos] = NodeT; - mPrev[NodeT] = mPos; - mParent[mPos] = NodeQ; - mParent[NodeR] = NIL; + NodeT = mPrev[NodeR]; + mPrev[mPos] = NodeT; + mNext[NodeT] = mPos; + NodeT = mNext[NodeR]; + mNext[mPos] = NodeT; + mPrev[NodeT] = mPos; + mParent[mPos] = NodeQ; + mParent[NodeR] = NIL; - // - // Special usage of 'next' - // - mNext[NodeR] = mPos; + // + // Special usage of 'next' + // + mNext[NodeR] = mPos; } STATIC - VOID - DeleteNode ( - VOID - ) - /*++ + VOID + DeleteNode ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Delete outdated string info. (The Usage of PERC_FLAG - ensures a clean deletion) + Delete outdated string info. (The Usage of PERC_FLAG + ensures a clean deletion) - Arguments: (VOID) + Arguments: (VOID) - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - NODE NodeQ; - NODE NodeR; - NODE NodeS; - NODE NodeT; - NODE NodeU; + NODE NodeQ; + NODE NodeR; + NODE NodeS; + NODE NodeT; + NODE NodeU; - if (mParent[mPos] == NIL) { - return ; - } + if (mParent[mPos] == NIL) { + return ; + } - NodeR = mPrev[mPos]; - NodeS = mNext[mPos]; - mNext[NodeR] = NodeS; - mPrev[NodeS] = NodeR; - NodeR = mParent[mPos]; - mParent[mPos] = NIL; - if (NodeR >= WNDSIZ) { - return ; - } + NodeR = mPrev[mPos]; + NodeS = mNext[mPos]; + mNext[NodeR] = NodeS; + mPrev[NodeS] = NodeR; + NodeR = mParent[mPos]; + mParent[mPos] = NIL; + if (NodeR >= WNDSIZ) { + return ; + } - mChildCount[NodeR]--; - if (mChildCount[NodeR] > 1) { - return ; - } + mChildCount[NodeR]--; + if (mChildCount[NodeR] > 1) { + return ; + } - NodeT = (NODE) (mPosition[NodeR] & (UINT32)~PERC_FLAG); - if (NodeT >= mPos) { - NodeT -= WNDSIZ; - } + NodeT = (NODE) (mPosition[NodeR] & (UINT32)~PERC_FLAG); + if (NodeT >= mPos) { + NodeT -= WNDSIZ; + } - NodeS = NodeT; - NodeQ = mParent[NodeR]; - NodeU = mPosition[NodeQ]; - while (NodeU & (UINT32) PERC_FLAG) { - NodeU &= (UINT32)~PERC_FLAG; - if (NodeU >= mPos) { - NodeU -= WNDSIZ; - } + NodeS = NodeT; + NodeQ = mParent[NodeR]; + NodeU = mPosition[NodeQ]; + while (NodeU & (UINT32) PERC_FLAG) { + NodeU &= (UINT32)~PERC_FLAG; + if (NodeU >= mPos) { + NodeU -= WNDSIZ; + } - if (NodeU > NodeS) { - NodeS = NodeU; - } + if (NodeU > NodeS) { + NodeS = NodeU; + } - mPosition[NodeQ] = (NODE) (NodeS | WNDSIZ); - NodeQ = mParent[NodeQ]; - NodeU = mPosition[NodeQ]; - } + mPosition[NodeQ] = (NODE) (NodeS | WNDSIZ); + NodeQ = mParent[NodeQ]; + NodeU = mPosition[NodeQ]; + } - if (NodeQ < WNDSIZ) { - if (NodeU >= mPos) { - NodeU -= WNDSIZ; - } + if (NodeQ < WNDSIZ) { + if (NodeU >= mPos) { + NodeU -= WNDSIZ; + } - if (NodeU > NodeS) { - NodeS = NodeU; - } + if (NodeU > NodeS) { + NodeS = NodeU; + } - mPosition[NodeQ] = (NODE) (NodeS | WNDSIZ | (UINT32) PERC_FLAG); - } + mPosition[NodeQ] = (NODE) (NodeS | WNDSIZ | (UINT32) PERC_FLAG); + } - NodeS = Child (NodeR, mText[NodeT + mLevel[NodeR]]); - NodeT = mPrev[NodeS]; - NodeU = mNext[NodeS]; - mNext[NodeT] = NodeU; - mPrev[NodeU] = NodeT; - NodeT = mPrev[NodeR]; - mNext[NodeT] = NodeS; - mPrev[NodeS] = NodeT; - NodeT = mNext[NodeR]; - mPrev[NodeT] = NodeS; - mNext[NodeS] = NodeT; - mParent[NodeS] = mParent[NodeR]; - mParent[NodeR] = NIL; - mNext[NodeR] = mAvail; - mAvail = NodeR; + NodeS = Child (NodeR, mText[NodeT + mLevel[NodeR]]); + NodeT = mPrev[NodeS]; + NodeU = mNext[NodeS]; + mNext[NodeT] = NodeU; + mPrev[NodeU] = NodeT; + NodeT = mPrev[NodeR]; + mNext[NodeT] = NodeS; + mPrev[NodeS] = NodeT; + NodeT = mNext[NodeR]; + mPrev[NodeT] = NodeS; + mNext[NodeS] = NodeT; + mParent[NodeS] = mParent[NodeR]; + mParent[NodeR] = NIL; + mNext[NodeR] = mAvail; + mAvail = NodeR; } STATIC - VOID - GetNextMatch ( - VOID - ) - /*++ + VOID + GetNextMatch ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Advance the current position (read new data if needed). - Delete outdated string info. Find a match string for current position. + Advance the current position (read new data if needed). + Delete outdated string info. Find a match string for current position. - Arguments: (VOID) + Arguments: (VOID) - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - INT32 Number; + INT32 Number; - mRemainder--; - mPos++; - if (mPos == WNDSIZ * 2) { - memmove (&mText[0], &mText[WNDSIZ], WNDSIZ + MAXMATCH); - Number = FreadCrc (&mText[WNDSIZ + MAXMATCH], WNDSIZ); - mRemainder += Number; - mPos = WNDSIZ; - } + mRemainder--; + mPos++; + if (mPos == WNDSIZ * 2) { + memmove (&mText[0], &mText[WNDSIZ], WNDSIZ + MAXMATCH); + Number = FreadCrc (&mText[WNDSIZ + MAXMATCH], WNDSIZ); + mRemainder += Number; + mPos = WNDSIZ; + } - DeleteNode (); - InsertNode (); + DeleteNode (); + InsertNode (); } STATIC - INT32 - Encode ( - VOID - ) - /*++ + INT32 + Encode ( + VOID + ) + /*++ - Routine Description: + Routine Description: - The macontrolling routine for compression process. + The macontrolling routine for compression process. - Arguments: (VOID) + Arguments: (VOID) - Returns: + Returns: - EFI_SUCCESS - The compression is successful - EFI_OUT_0F_RESOURCES - Not enough memory for compression process + EFI_SUCCESS - The compression is successful + EFI_OUT_0F_RESOURCES - Not enough memory for compression process - --*/ + --*/ { - INT32 Status; - INT32 LastMatchLen; - NODE LastMatchPos; + INT32 Status; + INT32 LastMatchLen; + NODE LastMatchPos; - Status = AllocateMemory (); - if (Status) { - FreeMemory (); - return Status; - } + Status = AllocateMemory (); + if (Status) { + FreeMemory (); + return Status; + } - InitSlide (); + InitSlide (); - HufEncodeStart (); + HufEncodeStart (); - mRemainder = FreadCrc (&mText[WNDSIZ], WNDSIZ + MAXMATCH); + mRemainder = FreadCrc (&mText[WNDSIZ], WNDSIZ + MAXMATCH); - mMatchLen = 0; - mPos = WNDSIZ; - InsertNode (); - if (mMatchLen > mRemainder) { - mMatchLen = mRemainder; - } + mMatchLen = 0; + mPos = WNDSIZ; + InsertNode (); + if (mMatchLen > mRemainder) { + mMatchLen = mRemainder; + } - while (mRemainder > 0) { - LastMatchLen = mMatchLen; - LastMatchPos = mMatchPos; - GetNextMatch (); - if (mMatchLen > mRemainder) { - mMatchLen = mRemainder; - } + while (mRemainder > 0) { + LastMatchLen = mMatchLen; + LastMatchPos = mMatchPos; + GetNextMatch (); + if (mMatchLen > mRemainder) { + mMatchLen = mRemainder; + } - if (mMatchLen > LastMatchLen || LastMatchLen < THRESHOLD) { - // - // Not enough benefits are gained by outputting a pointer, - // so just output the original character - // - Output (mText[mPos - 1], 0); + if (mMatchLen > LastMatchLen || LastMatchLen < THRESHOLD) { + // + // Not enough benefits are gained by outputting a pointer, + // so just output the original character + // + Output (mText[mPos - 1], 0); - } else { + } else { - if (LastMatchLen == THRESHOLD) { - if (((mPos - LastMatchPos - 2) & (WNDSIZ - 1)) > (1U << 11)) { - Output (mText[mPos - 1], 0); - continue; - } - } - // - // Outputting a pointer is beneficial enough, do it. - // - Output ( - LastMatchLen + (UINT8_MAX + 1 - THRESHOLD), - (mPos - LastMatchPos - 2) & (WNDSIZ - 1) - ); - LastMatchLen--; - while (LastMatchLen > 0) { - GetNextMatch (); - LastMatchLen--; - } + if (LastMatchLen == THRESHOLD) { + if (((mPos - LastMatchPos - 2) & (WNDSIZ - 1)) > (1U << 11)) { + Output (mText[mPos - 1], 0); + continue; + } + } + // + // Outputting a pointer is beneficial enough, do it. + // + Output ( + LastMatchLen + (UINT8_MAX + 1 - THRESHOLD), + (mPos - LastMatchPos - 2) & (WNDSIZ - 1) + ); + LastMatchLen--; + while (LastMatchLen > 0) { + GetNextMatch (); + LastMatchLen--; + } - if (mMatchLen > mRemainder) { - mMatchLen = mRemainder; - } - } - } + if (mMatchLen > mRemainder) { + mMatchLen = mRemainder; + } + } + } - HufEncodeEnd (); - FreeMemory (); - return ERR_SUCCESS; + HufEncodeEnd (); + FreeMemory (); + return ERR_SUCCESS; } STATIC - VOID - CountTFreq ( - VOID - ) - /*++ + VOID + CountTFreq ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Count the frequencies for the Extra Set + Count the frequencies for the Extra Set - Arguments: (VOID) + Arguments: (VOID) - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - INT32 Index; - INT32 Index3; - INT32 Number; - INT32 Count; + INT32 Index; + INT32 Index3; + INT32 Number; + INT32 Count; - for (Index = 0; Index < NT; Index++) { - mTFreq[Index] = 0; - } + for (Index = 0; Index < NT; Index++) { + mTFreq[Index] = 0; + } - Number = NC; - while (Number > 0 && mCLen[Number - 1] == 0) { - Number--; - } + Number = NC; + while (Number > 0 && mCLen[Number - 1] == 0) { + Number--; + } - Index = 0; - while (Index < Number) { - Index3 = mCLen[Index++]; - if (Index3 == 0) { - Count = 1; - while (Index < Number && mCLen[Index] == 0) { - Index++; - Count++; - } + Index = 0; + while (Index < Number) { + Index3 = mCLen[Index++]; + if (Index3 == 0) { + Count = 1; + while (Index < Number && mCLen[Index] == 0) { + Index++; + Count++; + } - if (Count <= 2) { - mTFreq[0] = (UINT16) (mTFreq[0] + Count); - } else if (Count <= 18) { - mTFreq[1]++; - } else if (Count == 19) { - mTFreq[0]++; - mTFreq[1]++; - } else { - mTFreq[2]++; - } - } else { - mTFreq[Index3 + 2]++; - } - } + if (Count <= 2) { + mTFreq[0] = (UINT16) (mTFreq[0] + Count); + } else if (Count <= 18) { + mTFreq[1]++; + } else if (Count == 19) { + mTFreq[0]++; + mTFreq[1]++; + } else { + mTFreq[2]++; + } + } else { + mTFreq[Index3 + 2]++; + } + } } STATIC - VOID - WritePTLen ( - INT32 Number, - INT32 nbit, - INT32 Special - ) - /*++ + VOID + WritePTLen ( + INT32 Number, + INT32 nbit, + INT32 Special + ) + /*++ - Routine Description: + Routine Description: - Outputs the code length array for the Extra Set or the Position Set. + Outputs the code length array for the Extra Set or the Position Set. - Arguments: + Arguments: - Number - the number of symbols - nbit - the number of bits needed to represent 'n' - Special - the special symbol that needs to be take care of + Number - the number of symbols + nbit - the number of bits needed to represent 'n' + Special - the special symbol that needs to be take care of - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - INT32 Index; - INT32 Index3; + INT32 Index; + INT32 Index3; - while (Number > 0 && mPTLen[Number - 1] == 0) { - Number--; - } + while (Number > 0 && mPTLen[Number - 1] == 0) { + Number--; + } - PutBits (nbit, Number); - Index = 0; - while (Index < Number) { - Index3 = mPTLen[Index++]; - if (Index3 <= 6) { - PutBits (3, Index3); - } else { - PutBits (Index3 - 3, (1U << (Index3 - 3)) - 2); - } + PutBits (nbit, Number); + Index = 0; + while (Index < Number) { + Index3 = mPTLen[Index++]; + if (Index3 <= 6) { + PutBits (3, Index3); + } else { + PutBits (Index3 - 3, (1U << (Index3 - 3)) - 2); + } - if (Index == Special) { - while (Index < 6 && mPTLen[Index] == 0) { - Index++; - } + if (Index == Special) { + while (Index < 6 && mPTLen[Index] == 0) { + Index++; + } - PutBits (2, (Index - 3) & 3); - } - } + PutBits (2, (Index - 3) & 3); + } + } } STATIC - VOID - WriteCLen ( - VOID - ) - /*++ + VOID + WriteCLen ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Outputs the code length array for Char&Length Set + Outputs the code length array for Char&Length Set - Arguments: (VOID) + Arguments: (VOID) - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - INT32 Index; - INT32 Index3; - INT32 Number; - INT32 Count; + INT32 Index; + INT32 Index3; + INT32 Number; + INT32 Count; - Number = NC; - while (Number > 0 && mCLen[Number - 1] == 0) { - Number--; - } + Number = NC; + while (Number > 0 && mCLen[Number - 1] == 0) { + Number--; + } - PutBits (CBIT, Number); - Index = 0; - while (Index < Number) { - Index3 = mCLen[Index++]; - if (Index3 == 0) { - Count = 1; - while (Index < Number && mCLen[Index] == 0) { - Index++; - Count++; - } + PutBits (CBIT, Number); + Index = 0; + while (Index < Number) { + Index3 = mCLen[Index++]; + if (Index3 == 0) { + Count = 1; + while (Index < Number && mCLen[Index] == 0) { + Index++; + Count++; + } - if (Count <= 2) { - for (Index3 = 0; Index3 < Count; Index3++) { - PutBits (mPTLen[0], mPTCode[0]); - } - } else if (Count <= 18) { - PutBits (mPTLen[1], mPTCode[1]); - PutBits (4, Count - 3); - } else if (Count == 19) { - PutBits (mPTLen[0], mPTCode[0]); - PutBits (mPTLen[1], mPTCode[1]); - PutBits (4, 15); - } else { - PutBits (mPTLen[2], mPTCode[2]); - PutBits (CBIT, Count - 20); - } - } else { - PutBits (mPTLen[Index3 + 2], mPTCode[Index3 + 2]); - } - } + if (Count <= 2) { + for (Index3 = 0; Index3 < Count; Index3++) { + PutBits (mPTLen[0], mPTCode[0]); + } + } else if (Count <= 18) { + PutBits (mPTLen[1], mPTCode[1]); + PutBits (4, Count - 3); + } else if (Count == 19) { + PutBits (mPTLen[0], mPTCode[0]); + PutBits (mPTLen[1], mPTCode[1]); + PutBits (4, 15); + } else { + PutBits (mPTLen[2], mPTCode[2]); + PutBits (CBIT, Count - 20); + } + } else { + PutBits (mPTLen[Index3 + 2], mPTCode[Index3 + 2]); + } + } } STATIC - VOID - EncodeC ( - INT32 Value - ) + VOID + EncodeC ( + INT32 Value + ) { - PutBits (mCLen[Value], mCCode[Value]); + PutBits (mCLen[Value], mCCode[Value]); } STATIC - VOID - EncodeP ( - UINT32 Value - ) + VOID + EncodeP ( + UINT32 Value + ) { - UINT32 Index; - UINT32 NodeQ; + UINT32 Index; + UINT32 NodeQ; - Index = 0; - NodeQ = Value; - while (NodeQ) { - NodeQ >>= 1; - Index++; - } + Index = 0; + NodeQ = Value; + while (NodeQ) { + NodeQ >>= 1; + Index++; + } - PutBits (mPTLen[Index], mPTCode[Index]); - if (Index > 1) { - PutBits (Index - 1, Value & (0xFFFFFFFFU >> (32 - Index + 1))); - } + PutBits (mPTLen[Index], mPTCode[Index]); + if (Index > 1) { + PutBits (Index - 1, Value & (0xFFFFFFFFU >> (32 - Index + 1))); + } } STATIC - VOID - SendBlock ( - VOID - ) - /*++ + VOID + SendBlock ( + VOID + ) + /*++ - Routine Description: + Routine Description: - Huffman code the block and output it. + Huffman code the block and output it. - Arguments: - (VOID) + Arguments: + (VOID) - Returns: - (VOID) + Returns: + (VOID) - --*/ + --*/ { - UINT32 Index; - UINT32 Index2; - UINT32 Index3; - UINT32 Flags; - UINT32 Root; - UINT32 Pos; - UINT32 Size; - Flags = 0; + UINT32 Index; + UINT32 Index2; + UINT32 Index3; + UINT32 Flags; + UINT32 Root; + UINT32 Pos; + UINT32 Size; + Flags = 0; - Root = MakeTree (NC, mCFreq, mCLen, mCCode); - Size = mCFreq[Root]; - PutBits (16, Size); - if (Root >= NC) { - CountTFreq (); - Root = MakeTree (NT, mTFreq, mPTLen, mPTCode); - if (Root >= NT) { - WritePTLen (NT, TBIT, 3); - } else { - PutBits (TBIT, 0); - PutBits (TBIT, Root); - } + Root = MakeTree (NC, mCFreq, mCLen, mCCode); + Size = mCFreq[Root]; + PutBits (16, Size); + if (Root >= NC) { + CountTFreq (); + Root = MakeTree (NT, mTFreq, mPTLen, mPTCode); + if (Root >= NT) { + WritePTLen (NT, TBIT, 3); + } else { + PutBits (TBIT, 0); + PutBits (TBIT, Root); + } - WriteCLen (); - } else { - PutBits (TBIT, 0); - PutBits (TBIT, 0); - PutBits (CBIT, 0); - PutBits (CBIT, Root); - } + WriteCLen (); + } else { + PutBits (TBIT, 0); + PutBits (TBIT, 0); + PutBits (CBIT, 0); + PutBits (CBIT, Root); + } - Root = MakeTree (NP, mPFreq, mPTLen, mPTCode); - if (Root >= NP) { - WritePTLen (NP, PBIT, -1); - } else { - PutBits (PBIT, 0); - PutBits (PBIT, Root); - } + Root = MakeTree (NP, mPFreq, mPTLen, mPTCode); + if (Root >= NP) { + WritePTLen (NP, PBIT, -1); + } else { + PutBits (PBIT, 0); + PutBits (PBIT, Root); + } - Pos = 0; - for (Index = 0; Index < Size; Index++) { - if (Index % UINT8_BIT == 0) { - Flags = mBuf[Pos++]; - } else { - Flags <<= 1; - } + Pos = 0; + for (Index = 0; Index < Size; Index++) { + if (Index % UINT8_BIT == 0) { + Flags = mBuf[Pos++]; + } else { + Flags <<= 1; + } - if (Flags & (1U << (UINT8_BIT - 1))) { - EncodeC (mBuf[Pos++] + (1U << UINT8_BIT)); - Index3 = mBuf[Pos++]; - for (Index2 = 0; Index2 < 3; Index2++) { - Index3 <<= UINT8_BIT; - Index3 += mBuf[Pos++]; - } + if (Flags & (1U << (UINT8_BIT - 1))) { + EncodeC (mBuf[Pos++] + (1U << UINT8_BIT)); + Index3 = mBuf[Pos++]; + for (Index2 = 0; Index2 < 3; Index2++) { + Index3 <<= UINT8_BIT; + Index3 += mBuf[Pos++]; + } - EncodeP (Index3); - } else { - EncodeC (mBuf[Pos++]); - } - } + EncodeP (Index3); + } else { + EncodeC (mBuf[Pos++]); + } + } - for (Index = 0; Index < NC; Index++) { - mCFreq[Index] = 0; - } + for (Index = 0; Index < NC; Index++) { + mCFreq[Index] = 0; + } - for (Index = 0; Index < NP; Index++) { - mPFreq[Index] = 0; - } + for (Index = 0; Index < NP; Index++) { + mPFreq[Index] = 0; + } } STATIC - VOID - Output ( - UINT32 CharC, - UINT32 Pos - ) - /*++ + VOID + Output ( + UINT32 CharC, + UINT32 Pos + ) + /*++ - Routine Description: + Routine Description: - Outputs an Original Character or a Pointer + Outputs an Original Character or a Pointer - Arguments: + Arguments: - CharC - The original character or the 'String Length' element of a Pointer - Pos - The 'Position' field of a Pointer + CharC - The original character or the 'String Length' element of a Pointer + Pos - The 'Position' field of a Pointer - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - STATIC UINT32 CPos; + STATIC UINT32 CPos; - if ((mOutputMask >>= 1) == 0) { - mOutputMask = 1U << (UINT8_BIT - 1); - // - // Check the buffer overflow per outputing UINT8_BIT symbols - // which is an Original Character or a Pointer. The biggest - // symbol is a Pointer which occupies 5 bytes. - // - if (mOutputPos >= mBufSiz - 5 * UINT8_BIT) { - SendBlock (); - mOutputPos = 0; - } + if ((mOutputMask >>= 1) == 0) { + mOutputMask = 1U << (UINT8_BIT - 1); + // + // Check the buffer overflow per outputing UINT8_BIT symbols + // which is an Original Character or a Pointer. The biggest + // symbol is a Pointer which occupies 5 bytes. + // + if (mOutputPos >= mBufSiz - 5 * UINT8_BIT) { + SendBlock (); + mOutputPos = 0; + } - CPos = mOutputPos++; - mBuf[CPos] = 0; - } + CPos = mOutputPos++; + mBuf[CPos] = 0; + } - mBuf[mOutputPos++] = (UINT8) CharC; - mCFreq[CharC]++; - if (CharC >= (1U << UINT8_BIT)) { - mBuf[CPos] |= mOutputMask; - mBuf[mOutputPos++] = (UINT8) (Pos >> 24); - mBuf[mOutputPos++] = (UINT8) (Pos >> 16); - mBuf[mOutputPos++] = (UINT8) (Pos >> (UINT8_BIT)); - mBuf[mOutputPos++] = (UINT8) Pos; - CharC = 0; - while (Pos) { - Pos >>= 1; - CharC++; - } + mBuf[mOutputPos++] = (UINT8) CharC; + mCFreq[CharC]++; + if (CharC >= (1U << UINT8_BIT)) { + mBuf[CPos] |= mOutputMask; + mBuf[mOutputPos++] = (UINT8) (Pos >> 24); + mBuf[mOutputPos++] = (UINT8) (Pos >> 16); + mBuf[mOutputPos++] = (UINT8) (Pos >> (UINT8_BIT)); + mBuf[mOutputPos++] = (UINT8) Pos; + CharC = 0; + while (Pos) { + Pos >>= 1; + CharC++; + } - mPFreq[CharC]++; - } + mPFreq[CharC]++; + } } STATIC - VOID - HufEncodeStart ( - VOID - ) + VOID + HufEncodeStart ( + VOID + ) { - INT32 Index; + INT32 Index; - for (Index = 0; Index < NC; Index++) { - mCFreq[Index] = 0; - } + for (Index = 0; Index < NC; Index++) { + mCFreq[Index] = 0; + } - for (Index = 0; Index < NP; Index++) { - mPFreq[Index] = 0; - } + for (Index = 0; Index < NP; Index++) { + mPFreq[Index] = 0; + } - mOutputPos = mOutputMask = 0; - InitPutBits (); - return ; + mOutputPos = mOutputMask = 0; + InitPutBits (); + return ; } STATIC - VOID - HufEncodeEnd ( - VOID - ) + VOID + HufEncodeEnd ( + VOID + ) { - SendBlock (); + SendBlock (); - // - // Flush remaining bits - // - PutBits (UINT8_BIT - 1, 0); + // + // Flush remaining bits + // + PutBits (UINT8_BIT - 1, 0); - return ; + return ; } STATIC - VOID - MakeCrcTable ( - VOID - ) + VOID + MakeCrcTable ( + VOID + ) { - UINT32 Index; - UINT32 Index2; - UINT32 Temp; + UINT32 Index; + UINT32 Index2; + UINT32 Temp; - for (Index = 0; Index <= UINT8_MAX; Index++) { - Temp = Index; - for (Index2 = 0; Index2 < UINT8_BIT; Index2++) { - if (Temp & 1) { - Temp = (Temp >> 1) ^ CRCPOLY; - } else { - Temp >>= 1; - } - } + for (Index = 0; Index <= UINT8_MAX; Index++) { + Temp = Index; + for (Index2 = 0; Index2 < UINT8_BIT; Index2++) { + if (Temp & 1) { + Temp = (Temp >> 1) ^ CRCPOLY; + } else { + Temp >>= 1; + } + } - mCrcTable[Index] = (UINT16) Temp; - } + mCrcTable[Index] = (UINT16) Temp; + } } STATIC - VOID - PutBits ( - INT32 Number, - UINT32 Value - ) - /*++ + VOID + PutBits ( + INT32 Number, + UINT32 Value + ) + /*++ - Routine Description: + Routine Description: - Outputs rightmost n bits of x + Outputs rightmost n bits of x - Arguments: + Arguments: - Number - the rightmost n bits of the data is used - x - the data + Number - the rightmost n bits of the data is used + x - the data - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - UINT8 Temp; + UINT8 Temp; - while (Number >= mBitCount) { - // - // Number -= mBitCount should never equal to 32 - // - Temp = (UINT8) (mSubBitBuf | (Value >> (Number -= mBitCount))); - if (mDst < mDstUpperLimit) { - *mDst++ = Temp; - } + while (Number >= mBitCount) { + // + // Number -= mBitCount should never equal to 32 + // + Temp = (UINT8) (mSubBitBuf | (Value >> (Number -= mBitCount))); + if (mDst < mDstUpperLimit) { + *mDst++ = Temp; + } - mCompSize++; - mSubBitBuf = 0; - mBitCount = UINT8_BIT; - } + mCompSize++; + mSubBitBuf = 0; + mBitCount = UINT8_BIT; + } - mSubBitBuf |= Value << (mBitCount -= Number); + mSubBitBuf |= Value << (mBitCount -= Number); } STATIC - INT32 - FreadCrc ( - UINT8 *Pointer, - INT32 Number - ) - /*++ + INT32 + FreadCrc ( + UINT8 *Pointer, + INT32 Number + ) + /*++ - Routine Description: + Routine Description: - Read source data + Read source data - Arguments: + Arguments: - Pointer - the buffer to hold the data - Number - number of bytes to read + Pointer - the buffer to hold the data + Number - number of bytes to read - Returns: + Returns: - number of bytes actually read + number of bytes actually read - --*/ + --*/ { - INT32 Index; + INT32 Index; - for (Index = 0; mSrc < mSrcUpperLimit && Index < Number; Index++) { - *Pointer++ = *mSrc++; - } + for (Index = 0; mSrc < mSrcUpperLimit && Index < Number; Index++) { + *Pointer++ = *mSrc++; + } - Number = Index; + Number = Index; - Pointer -= Number; - mOrigSize += Number; - Index--; - while (Index >= 0) { - UPDATE_CRC (*Pointer++); - Index--; - } + Pointer -= Number; + mOrigSize += Number; + Index--; + while (Index >= 0) { + UPDATE_CRC (*Pointer++); + Index--; + } - return Number; + return Number; } STATIC - VOID - InitPutBits ( - VOID - ) + VOID + InitPutBits ( + VOID + ) { - mBitCount = UINT8_BIT; - mSubBitBuf = 0; + mBitCount = UINT8_BIT; + mSubBitBuf = 0; } STATIC - VOID - CountLen ( - INT32 Index - ) - /*++ + VOID + CountLen ( + INT32 Index + ) + /*++ - Routine Description: + Routine Description: - Count the number of each code length for a Huffman tree. + Count the number of each code length for a Huffman tree. - Arguments: + Arguments: - Index - the top node + Index - the top node - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - STATIC INT32 Depth = 0; + STATIC INT32 Depth = 0; - if (Index < mN) { - mLenCnt[(Depth < 16) ? Depth : 16]++; - } else { - Depth++; - CountLen (mLeft[Index]); - CountLen (mRight[Index]); - Depth--; - } + if (Index < mN) { + mLenCnt[(Depth < 16) ? Depth : 16]++; + } else { + Depth++; + CountLen (mLeft[Index]); + CountLen (mRight[Index]); + Depth--; + } } STATIC - VOID - MakeLen ( - INT32 Root - ) - /*++ + VOID + MakeLen ( + INT32 Root + ) + /*++ - Routine Description: + Routine Description: - Create code length array for a Huffman tree + Create code length array for a Huffman tree - Arguments: + Arguments: - Root - the root of the tree + Root - the root of the tree - Returns: + Returns: - VOID + VOID - --*/ + --*/ { - INT32 Index; - INT32 Index3; - UINT32 Cum; + INT32 Index; + INT32 Index3; + UINT32 Cum; - for (Index = 0; Index <= 16; Index++) { - mLenCnt[Index] = 0; - } + for (Index = 0; Index <= 16; Index++) { + mLenCnt[Index] = 0; + } - CountLen (Root); + CountLen (Root); - // - // Adjust the length count array so that - // no code will be generated longer than its designated length - // - Cum = 0; - for (Index = 16; Index > 0; Index--) { - Cum += mLenCnt[Index] << (16 - Index); - } + // + // Adjust the length count array so that + // no code will be generated longer than its designated length + // + Cum = 0; + for (Index = 16; Index > 0; Index--) { + Cum += mLenCnt[Index] << (16 - Index); + } - while (Cum != (1U << 16)) { - mLenCnt[16]--; - for (Index = 15; Index > 0; Index--) { - if (mLenCnt[Index] != 0) { - mLenCnt[Index]--; - mLenCnt[Index + 1] += 2; - break; - } - } + while (Cum != (1U << 16)) { + mLenCnt[16]--; + for (Index = 15; Index > 0; Index--) { + if (mLenCnt[Index] != 0) { + mLenCnt[Index]--; + mLenCnt[Index + 1] += 2; + break; + } + } - Cum--; - } + Cum--; + } - for (Index = 16; Index > 0; Index--) { - Index3 = mLenCnt[Index]; - Index3--; - while (Index3 >= 0) { - mLen[*mSortPtr++] = (UINT8) Index; - Index3--; - } - } + for (Index = 16; Index > 0; Index--) { + Index3 = mLenCnt[Index]; + Index3--; + while (Index3 >= 0) { + mLen[*mSortPtr++] = (UINT8) Index; + Index3--; + } + } } STATIC - VOID - DownHeap ( - INT32 Index - ) + VOID + DownHeap ( + INT32 Index + ) { - INT32 Index2; - INT32 Index3; + INT32 Index2; + INT32 Index3; - // - // priority queue: send Index-th entry down heap - // - Index3 = mHeap[Index]; - Index2 = 2 * Index; - while (Index2 <= mHeapSize) { - if (Index2 < mHeapSize && mFreq[mHeap[Index2]] > mFreq[mHeap[Index2 + 1]]) { - Index2++; - } + // + // priority queue: send Index-th entry down heap + // + Index3 = mHeap[Index]; + Index2 = 2 * Index; + while (Index2 <= mHeapSize) { + if (Index2 < mHeapSize && mFreq[mHeap[Index2]] > mFreq[mHeap[Index2 + 1]]) { + Index2++; + } - if (mFreq[Index3] <= mFreq[mHeap[Index2]]) { - break; - } + if (mFreq[Index3] <= mFreq[mHeap[Index2]]) { + break; + } - mHeap[Index] = mHeap[Index2]; - Index = Index2; - Index2 = 2 * Index; - } + mHeap[Index] = mHeap[Index2]; + Index = Index2; + Index2 = 2 * Index; + } - mHeap[Index] = (INT16) Index3; + mHeap[Index] = (INT16) Index3; } STATIC - VOID - MakeCode ( - INT32 Number, - UINT8 Len[ ], - UINT16 Code[] + VOID + MakeCode ( + INT32 Number, + UINT8 Len[ ], + UINT16 Code[] ) - /*++ + /*++ - Routine Description: + Routine Description: - Assign code to each symbol based on the code length array + Assign code to each symbol based on the code length array - Arguments: + Arguments: - Number - number of symbols - Len - the code length array - Code - stores codes for each symbol + Number - number of symbols + Len - the code length array + Code - stores codes for each symbol - Returns: (VOID) + Returns: (VOID) - --*/ + --*/ { - INT32 Index; - UINT16 Start[18]; + INT32 Index; + UINT16 Start[18]; - Start[1] = 0; - for (Index = 1; Index <= 16; Index++) { - Start[Index + 1] = (UINT16) ((Start[Index] + mLenCnt[Index]) << 1); - } + Start[1] = 0; + for (Index = 1; Index <= 16; Index++) { + Start[Index + 1] = (UINT16) ((Start[Index] + mLenCnt[Index]) << 1); + } - for (Index = 0; Index < Number; Index++) { - Code[Index] = Start[Len[Index]]++; - } + for (Index = 0; Index < Number; Index++) { + Code[Index] = Start[Len[Index]]++; + } } STATIC - INT32 - MakeTree ( - INT32 NParm, - UINT16 FreqParm[], - UINT8 LenParm[ ], - UINT16 CodeParm[] + INT32 + MakeTree ( + INT32 NParm, + UINT16 FreqParm[], + UINT8 LenParm[ ], + UINT16 CodeParm[] ) - /*++ + /*++ - Routine Description: + Routine Description: - Generates Huffman codes given a frequency distribution of symbols + Generates Huffman codes given a frequency distribution of symbols - Arguments: + Arguments: - NParm - number of symbols - FreqParm - frequency of each symbol - LenParm - code length for each symbol - CodeParm - code for each symbol + NParm - number of symbols + FreqParm - frequency of each symbol + LenParm - code length for each symbol + CodeParm - code for each symbol - Returns: + Returns: - Root of the Huffman tree. + Root of the Huffman tree. - --*/ + --*/ { - INT32 Index; - INT32 Index2; - INT32 Index3; - INT32 Avail; + INT32 Index; + INT32 Index2; + INT32 Index3; + INT32 Avail; - // - // make tree, calculate len[], return root - // - mN = NParm; - mFreq = FreqParm; - mLen = LenParm; - Avail = mN; - mHeapSize = 0; - mHeap[1] = 0; - for (Index = 0; Index < mN; Index++) { - mLen[Index] = 0; - if (mFreq[Index]) { - mHeapSize++; - mHeap[mHeapSize] = (INT16) Index; - } - } + // + // make tree, calculate len[], return root + // + mN = NParm; + mFreq = FreqParm; + mLen = LenParm; + Avail = mN; + mHeapSize = 0; + mHeap[1] = 0; + for (Index = 0; Index < mN; Index++) { + mLen[Index] = 0; + if (mFreq[Index]) { + mHeapSize++; + mHeap[mHeapSize] = (INT16) Index; + } + } - if (mHeapSize < 2) { - CodeParm[mHeap[1]] = 0; - return mHeap[1]; - } + if (mHeapSize < 2) { + CodeParm[mHeap[1]] = 0; + return mHeap[1]; + } - for (Index = mHeapSize / 2; Index >= 1; Index--) { - // - // make priority queue - // - DownHeap (Index); - } + for (Index = mHeapSize / 2; Index >= 1; Index--) { + // + // make priority queue + // + DownHeap (Index); + } - mSortPtr = CodeParm; - do { - Index = mHeap[1]; - if (Index < mN) { - *mSortPtr++ = (UINT16) Index; - } + mSortPtr = CodeParm; + do { + Index = mHeap[1]; + if (Index < mN) { + *mSortPtr++ = (UINT16) Index; + } - mHeap[1] = mHeap[mHeapSize--]; - DownHeap (1); - Index2 = mHeap[1]; - if (Index2 < mN) { - *mSortPtr++ = (UINT16) Index2; - } + mHeap[1] = mHeap[mHeapSize--]; + DownHeap (1); + Index2 = mHeap[1]; + if (Index2 < mN) { + *mSortPtr++ = (UINT16) Index2; + } - Index3 = Avail++; - mFreq[Index3] = (UINT16) (mFreq[Index] + mFreq[Index2]); - mHeap[1] = (INT16) Index3; - DownHeap (1); - mLeft[Index3] = (UINT16) Index; - mRight[Index3] = (UINT16) Index2; - } while (mHeapSize > 1); + Index3 = Avail++; + mFreq[Index3] = (UINT16) (mFreq[Index] + mFreq[Index2]); + mHeap[1] = (INT16) Index3; + DownHeap (1); + mLeft[Index3] = (UINT16) Index; + mRight[Index3] = (UINT16) Index2; + } while (mHeapSize > 1); - mSortPtr = CodeParm; - MakeLen (Index3); - MakeCode (NParm, LenParm, CodeParm); + mSortPtr = CodeParm; + MakeLen (Index3); + MakeCode (NParm, LenParm, CodeParm); - // - // return root - // - return Index3; + // + // return root + // + return Index3; } diff --git a/basetypes.h b/basetypes.h index d8f4197..5a47865 100644 --- a/basetypes.h +++ b/basetypes.h @@ -111,6 +111,11 @@ typedef uint16_t CHAR16; #define ERASE_POLARITY_TRUE 1 #define ERASE_POLARITY_UNKNOWN 0xFF +// Search modes +#define SEARCH_MODE_HEX 0 +#define SEARCH_MODE_ASCII 1 +#define SEARCH_MODE_UNICODE 2 + // EFI GUID typedef struct{ UINT8 Data[16]; diff --git a/ffs.cpp b/ffs.cpp index 1560150..e6fd8d4 100644 --- a/ffs.cpp +++ b/ffs.cpp @@ -19,9 +19,9 @@ const UINT8 ffsAlignmentTable[] = UINT8 calculateChecksum8(UINT8* buffer, UINT32 bufferSize) { if(!buffer) - return 0; - - UINT8 counter = 0; + return 0; + + UINT8 counter = 0; while(bufferSize--) counter += buffer[bufferSize]; @@ -32,16 +32,16 @@ UINT8 calculateChecksum8(UINT8* buffer, UINT32 bufferSize) UINT16 calculateChecksum16(UINT16* buffer, UINT32 bufferSize) { if(!buffer) - return 0; + return 0; - UINT16 counter = 0; - UINT32 index = 0; + UINT16 counter = 0; + UINT32 index = 0; - bufferSize /= sizeof(UINT16); + bufferSize /= sizeof(UINT16); - for (; index < bufferSize; index++) { - counter = (UINT16) (counter + buffer[index]); - } + for (; index < bufferSize; index++) { + counter = (UINT16) (counter + buffer[index]); + } return (UINT16) 0x10000 - counter; } @@ -167,7 +167,7 @@ QString sectionTypeToQString(const UINT8 type) UINT32 sizeOfSectionHeaderOfType(const UINT8 type) { - switch (type) + switch (type) { case EFI_SECTION_COMPRESSION: return sizeof(EFI_COMMON_SECTION_HEADER); diff --git a/ffs.h b/ffs.h index 663112c..8ca26ea 100644 --- a/ffs.h +++ b/ffs.h @@ -56,7 +56,7 @@ typedef struct { UINT16 RomImageOffset; // offset in bytes from the beginning of the capsule header to the start of // the capsule volume //!TODO: Enable certificate and rom layout reading - //UINT16 RomLayoutOffset; // offset to the table of the module descriptors in the capsule's volume + //UINT16 RomLayoutOffset; // offset to the table of the module descriptors in the capsule's volume // that are included in the signature calculation //FW_CERTIFICATE FWCert; //ROM_AREA RomAreaMap[1]; @@ -77,17 +77,17 @@ typedef struct { // Volume header typedef struct { - UINT8 ZeroVector[16]; - EFI_GUID FileSystemGuid; - UINT64 FvLength; - UINT32 Signature; - UINT32 Attributes; - UINT16 HeaderLength; - UINT16 Checksum; + UINT8 ZeroVector[16]; + EFI_GUID FileSystemGuid; + UINT64 FvLength; + UINT32 Signature; + UINT32 Attributes; + UINT16 HeaderLength; + UINT16 Checksum; UINT16 ExtHeaderOffset; //Reserved in Revision 1 UINT8 Reserved; - UINT8 Revision; - //EFI_FV_BLOCK_MAP_ENTRY FvBlockMap[1]; + UINT8 Revision; + //EFI_FV_BLOCK_MAP_ENTRY FvBlockMap[1]; } EFI_FIRMWARE_VOLUME_HEADER; // Filesystem GUIDs @@ -229,12 +229,12 @@ typedef union { } EFI_FFS_INTEGRITY_CHECK; // File header typedef struct { - EFI_GUID Name; + EFI_GUID Name; EFI_FFS_INTEGRITY_CHECK IntegrityCheck; - UINT8 Type; - UINT8 Attributes; - UINT8 Size[3]; - UINT8 State; + UINT8 Type; + UINT8 Attributes; + UINT8 Size[3]; + UINT8 State; } EFI_FFS_FILE_HEADER; // Large file header diff --git a/ffsengine.cpp b/ffsengine.cpp index 93945bc..a42a981 100644 --- a/ffsengine.cpp +++ b/ffsengine.cpp @@ -51,11 +51,16 @@ void FfsEngine::msg(const QString & message, const QModelIndex index) messageItems.enqueue(MessageListItem(message, NULL, 0, index)); } -QQueue FfsEngine::message() +QQueue FfsEngine::messages() { return messageItems; } +void FfsEngine::clearMessages() +{ + messageItems.clear(); +} + QModelIndex FfsEngine::findParentOfType(UINT8 type, const QModelIndex& index) const { if(!index.isValid()) @@ -911,7 +916,7 @@ UINT8 FfsEngine::parseFile(const QByteArray & file, UINT8 revision, const UINT8 // Add tree item QModelIndex index = treeModel->addItem(TreeItem::File, fileHeader->Type, COMPRESSION_ALGORITHM_NONE, name, "", info, header, body, tail, parent, mode); - + if (!parseCurrentFile) return ERR_SUCCESS; @@ -1298,7 +1303,7 @@ UINT8 FfsEngine::changeCompression(const QModelIndex & index, const UINT8 algori // Set compression for the item treeModel->setItemCompression(algorithm, index); - // Set action for the item + // Set action for the item treeModel->setItemAction(TreeItem::Modify, index); return ERR_SUCCESS; @@ -1341,46 +1346,20 @@ UINT8 FfsEngine::decompress(const QByteArray & compressedData, const UINT8 compr scratch = new UINT8[scratchSize]; // Decompress section data - //!TODO: better check needed - // Try EFI1.1 decompression first - if (ERR_SUCCESS != EfiDecompress(data, dataSize, decompressed, decompressedSize, scratch, scratchSize)) { - // Not EFI 1.1, try Tiano - if (ERR_SUCCESS != TianoDecompress(data, dataSize, decompressed, decompressedSize, scratch, scratchSize)) { + // Try Tiano decompression first + if (ERR_SUCCESS != TianoDecompress(data, dataSize, decompressed, decompressedSize, scratch, scratchSize)) { + // Not Tiano, try EFI 1.1 + if (ERR_SUCCESS != EfiDecompress(data, dataSize, decompressed, decompressedSize, scratch, scratchSize)) { if (algorithm) *algorithm = COMPRESSION_ALGORITHM_UNKNOWN; return ERR_STANDARD_DECOMPRESSION_FAILED; } else if (algorithm) - *algorithm = COMPRESSION_ALGORITHM_TIANO; - } - else { - // Possible EFI 1.1 - // Try decompressing it as Tiano - UINT8* tianoDecompressed = new UINT8[decompressedSize]; - UINT8* tianoScratch = new UINT8[scratchSize]; - if (ERR_SUCCESS != TianoDecompress(data, dataSize, tianoDecompressed, decompressedSize, tianoScratch, scratchSize)) { - // Not Tiano, definitely EFI 1.1 - if (algorithm) - *algorithm = COMPRESSION_ALGORITHM_EFI11; - } - else { - // Both algorithms work - if(memcmp(decompressed, tianoDecompressed, decompressedSize)) { - // If decompressed data are different - it's Tiano for sure - delete[] decompressed; - delete[] scratch; - decompressed = tianoDecompressed; - scratch = tianoScratch; - if (algorithm) - *algorithm = COMPRESSION_ALGORITHM_TIANO; - } - else { - // Data are same - it's EFI 1.1 - if (algorithm) - *algorithm = COMPRESSION_ALGORITHM_EFI11; - } - } + *algorithm = COMPRESSION_ALGORITHM_EFI11; } + else if (algorithm) + *algorithm = COMPRESSION_ALGORITHM_TIANO; + decompressedData = QByteArray((const char*) decompressed, decompressedSize); // Free allocated memory @@ -1572,7 +1551,7 @@ UINT8 FfsEngine::reconstruct(const QModelIndex & index, QQueue & que QByteArray reconstructed; UINT8 result; - // No action is needed, just return header + body + // No action is needed, just return header + body + tail if (item->action() == TreeItem::NoAction) { reconstructed = item->header().append(item->body()).append(item->tail()); queue.enqueue(reconstructed); @@ -1872,7 +1851,7 @@ UINT8 FfsEngine::reconstruct(const QModelIndex & index, QQueue & que } } - // Append last file and fill the rest with empty char + // Append last file and fill the rest with empty char else { reconstructed.append(file); UINT32 volumeBodySize = volumeSize - header.size(); @@ -1903,7 +1882,7 @@ UINT8 FfsEngine::reconstruct(const QModelIndex & index, QQueue & que // Append current file to new volume body reconstructed.append(file); - // Change current file offset + // Change current file offset offset += file.size(); } @@ -2188,85 +2167,93 @@ UINT8 FfsEngine::growVolume(QByteArray & header, const UINT32 size, UINT32 & new return ERR_SUCCESS; } -// Will be refactored later -/*QByteArray FfsEngine::decompressFile(const QModelIndex& index) const +// Search routines +UINT8 FfsEngine::findHexPattern(const QByteArray & pattern, const bool bodyOnly) { -if (!index.isValid()) -return QByteArray(); - -// Check index item to be FFS file -TreeItem *item = static_cast(index.internalPointer()); -if(item->type() != TreeItem::File) -return QByteArray(); - -QByteArray file; -UINT32 offset = 0; -// Construct new item body -for (int i = 0; i < item->childCount(); i++) { -// If section is not compressed, add it to new body as is -TreeItem* sectionItem = item->child(i); -if (sectionItem->subtype() != EFI_SECTION_COMPRESSION) { -QByteArray section = sectionItem->header().append(sectionItem->body()); -UINT32 align = ALIGN4(offset) - offset; -file.append(QByteArray(align, '\x00')).append(section); -offset += align + section.size(); + return findHexPatternIn(treeModel->index(0,0), pattern, bodyOnly); } -else { -// Construct new section body by adding all child sections to this new section -QByteArray section; -UINT32 subOffset = 0; -for (int j = 0; j < sectionItem->childCount(); j++) + +UINT8 FfsEngine::findHexPatternIn(const QModelIndex & index, const QByteArray & pattern, const bool bodyOnly) { -TreeItem* subSectionItem = sectionItem->child(j); -QByteArray subSection = subSectionItem->header().append(subSectionItem->body()); -UINT32 align = ALIGN4(subOffset) - subOffset; -section.append(QByteArray(align, '\x00')).append(subSection); -subOffset += align + subSection.size(); -} -// Add newly constructed section to file body + if (pattern.isEmpty()) + return ERR_INVALID_PARAMETER; + + if (!index.isValid()) + return ERR_SUCCESS; -EFI_COMPRESSION_SECTION sectionHeader; -sectionHeader.Type = EFI_SECTION_COMPRESSION; -sectionHeader.CompressionType = EFI_NOT_COMPRESSED; -sectionHeader.UncompressedLength = section.size(); -uint32ToUint24(section.size() + sizeof(EFI_COMPRESSION_SECTION), sectionHeader.Size); -UINT32 align = ALIGN4(offset) - offset; -file.append(QByteArray(align, '\x00')) -.append(QByteArray((const char*) §ionHeader, sizeof(EFI_COMPRESSION_SECTION))) -.append(section); -offset += align + section.size(); -} + TreeItem* item = static_cast(index.internalPointer()); + if (item == rootItem) + return ERR_SUCCESS; + + bool hasChildren = (item->childCount() > 0); + for (int i = 0; i < item->childCount(); i++) { + findHexPatternIn(index.child(i, index.column()), pattern, bodyOnly); + } + + QByteArray data; + if (hasChildren) { + if(!bodyOnly) + data = item->header(); + } + else { + if (bodyOnly) + data = item->body(); + else + data = item->header().append(item->body()).append(item->tail()); + } + + int offset = -1; + while ((offset = data.indexOf(pattern, offset + 1)) >= 0) { + msg(tr("Hex pattern \"%1\" found in %2 at offset %3") + .arg(QString(pattern.toHex())) + .arg(item->data(0).toString()) + .arg(offset, 8, 16, QChar('0')), + index); + } + + return ERR_SUCCESS; } -QByteArray header = item->header(); -EFI_FFS_FILE_HEADER* fileHeader = (EFI_FFS_FILE_HEADER*) header.data(); - -// Correct file data checksum, if needed -if (fileHeader->Attributes & FFS_ATTRIB_CHECKSUM) { -UINT32 bufferSize = file.size() - sizeof(EFI_FFS_FILE_HEADER); -fileHeader->IntegrityCheck.Checksum.File = calculateChecksum8((UINT8*)(file.data() + sizeof(EFI_FFS_FILE_HEADER)), bufferSize); -} - -// Add file tail, if needed -if(fileHeader->Attributes & FFS_ATTRIB_TAIL_PRESENT) -file.append(!fileHeader->IntegrityCheck.TailReference); - -return header.append(file); -}*/ - -/*bool FfsEngine::isCompressedFile(const QModelIndex& index) const +UINT8 FfsEngine::findTextPattern(const QString & pattern, const bool unicode, const Qt::CaseSensitivity caseSensitive) { -if (!index.isValid()) -return false; - -TreeItem *item = static_cast(index.internalPointer()); -if(item->type() != TreeItem::File) -return false; - -for (int i = 0; i < item->childCount(); i++) { -if (item->child(i)->subtype() == EFI_SECTION_COMPRESSION) -return true; + return findTextPatternIn(treeModel->index(0,0), pattern, unicode, caseSensitive); } -return false; -}*/ +UINT8 FfsEngine::findTextPatternIn(const QModelIndex & index, const QString & pattern, const bool unicode, const Qt::CaseSensitivity caseSensitive) +{ + if (pattern.isEmpty()) + return ERR_INVALID_PARAMETER; + + if (!index.isValid()) + return ERR_SUCCESS; + + TreeItem* item = static_cast(index.internalPointer()); + if (item == rootItem) + return ERR_SUCCESS; + + bool hasChildren = (item->childCount() > 0); + for (int i = 0; i < item->childCount(); i++) { + findTextPatternIn(index.child(i, index.column()), pattern, unicode, caseSensitive); + } + + if (hasChildren) + return ERR_SUCCESS; + + QString data; + if (unicode) + data = QString::fromUtf16((const ushort*) item->body().data(), item->body().length()/2); + else + data = QString::fromAscii((const char*) item->body().data(), item->body().length()); + + int offset = -1; + while ((offset = data.indexOf(pattern, offset + 1, caseSensitive)) >= 0) { + msg(tr("%1 text pattern \"%2\" found in %3 at offset %4") + .arg(unicode ? "Unicode" : "ASCII") + .arg(pattern) + .arg(item->data(0).toString()) + .arg(unicode ? offset*2 : offset, 8, 16, QChar('0')), + index); + } + + return ERR_SUCCESS; +} \ No newline at end of file diff --git a/ffsengine.h b/ffsengine.h index 8961b17..1ba6ebc 100644 --- a/ffsengine.h +++ b/ffsengine.h @@ -38,7 +38,10 @@ public: TreeModel* model() const; // Returns message items queue - QQueue message(); + QQueue messages(); + + // Clears message items queue + void clearMessages(); // Firmware image parsing UINT8 parseInputFile(const QByteArray & buffer); @@ -74,6 +77,11 @@ public: UINT8 rebuild(const QModelIndex & index); UINT8 changeCompression(const QModelIndex & index, const UINT8 algorithm); + // Search routines + UINT8 findHexPattern(const QByteArray & pattern, const bool bodyOnly); + UINT8 findHexPatternIn(const QModelIndex & index, const QByteArray & pattern, const bool bodyOnly); + UINT8 findTextPattern(const QString & pattern, const bool unicode, const Qt::CaseSensitivity caseSensitive); + UINT8 findTextPatternIn(const QModelIndex & index, const QString & pattern, const bool unicode, const Qt::CaseSensitivity caseSensitive); private: TreeItem *rootItem; TreeModel *treeModel; diff --git a/main.cpp b/main.cpp index 0526d5e..f535c9f 100644 --- a/main.cpp +++ b/main.cpp @@ -20,6 +20,10 @@ int main(int argc, char *argv[]) QApplication a(argc, argv); UEFITool w; + QCoreApplication::setOrganizationName("CodeRush"); + QCoreApplication::setOrganizationDomain("coderush.me"); + QCoreApplication::setApplicationName("UEFITool"); + if (a.arguments().length() > 1) w.openImageFile(a.arguments().at(1)); w.show(); diff --git a/searchdialog.cpp b/searchdialog.cpp new file mode 100644 index 0000000..46d2a1b --- /dev/null +++ b/searchdialog.cpp @@ -0,0 +1,48 @@ +/* searchdialog.cpp + + Copyright (c) 2013, Nikolaj Schlej. All rights reserved. + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +*/ + +#include "searchdialog.h" + +SearchDialog::SearchDialog(QWidget *parent) : + QDialog(parent), + ui(new Ui::SearchDialog) +{ + // Create UI + ui->setupUi(this); + + // Connect + //connect(ui->dataTypeComboBox, SIGNAL(currentIndexChanged(int)), this, SLOT(setEditMask())); + //connect(ui->translateFromHexCheckBox, SIGNAL(stateChanged(int)), this, SLOT(setEditMask())); +} + +SearchDialog::~SearchDialog() +{ + delete ui; +} + +/*void SearchDialog::setEditMask() +{ + int index = ui->dataTypeComboBox->currentIndex(); + QString mask; + if (index == 0) // Hex pattern, max 48 bytes long + mask = ""; + else if (index == 1) { + if (ui->translateFromHexCheckBox->isChecked()) + mask = "searchEdit->setInputMask(mask); +}*/ \ No newline at end of file diff --git a/searchdialog.h b/searchdialog.h new file mode 100644 index 0000000..39fc660 --- /dev/null +++ b/searchdialog.h @@ -0,0 +1,34 @@ +/* searchdialog.h + + Copyright (c) 2013, Nikolaj Schlej. All rights reserved. + This program and the accompanying materials + are licensed and made available under the terms and conditions of the BSD License + which accompanies this distribution. The full text of the license may be found at + http://opensource.org/licenses/bsd-license.php + + THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN "AS IS" BASIS, + WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED. + +*/ + +#ifndef SEARCHDIALOG_H +#define SEARCHDIALOG_H + +#include +#include "ui_searchdialog.h" + +class SearchDialog : public QDialog +{ + Q_OBJECT + +public: + SearchDialog(QWidget *parent = 0); + ~SearchDialog(); + Ui::SearchDialog* ui; + +private slots: + //void setEditMask(); + +}; + +#endif \ No newline at end of file diff --git a/searchdialog.ui b/searchdialog.ui new file mode 100644 index 0000000..ae1a5ef --- /dev/null +++ b/searchdialog.ui @@ -0,0 +1,199 @@ + + + SearchDialog + + + + 0 + 0 + 290 + 172 + + + + Search + + + + + + Search for: + + + + + + + Data type: + + + + + + + Qt::Horizontal + + + QDialogButtonBox::Cancel|QDialogButtonBox::Ok + + + + + + + + + + + Hex pattern + + + + + Text string + + + + + + + + 1 + + + + + 0 + + + 0 + + + + + Hex pattern search scope + + + + + + Header, data and footer + + + + + + + Data only + + + true + + + + + + + + + + + + 0 + + + 0 + + + + + Text string options + + + + + + Unicode + + + true + + + + + + + Case sensitive + + + + + + + + + + + + + + searchEdit + dataTypeComboBox + allRadioButton + dataOnlyRadioButton + unicodeCheckBox + caseSensitiveCheckBox + buttonBox + + + + + buttonBox + accepted() + SearchDialog + accept() + + + 173 + 162 + + + 157 + 216 + + + + + buttonBox + rejected() + SearchDialog + reject() + + + 173 + 162 + + + 286 + 216 + + + + + dataTypeComboBox + activated(int) + stackedWidget + setCurrentIndex(int) + + + 151 + 42 + + + 88 + 68 + + + + + diff --git a/treeitem.cpp b/treeitem.cpp index b7b19f5..6503b2c 100644 --- a/treeitem.cpp +++ b/treeitem.cpp @@ -172,7 +172,7 @@ QVariant TreeItem::data(int column) const case 0: //Name return itemName; case 1: //Action - if (itemAction == TreeItem::Modify) + if (itemAction == TreeItem::Modify) return "M"; if (itemAction == TreeItem::Remove) return "X"; diff --git a/treeitem.h b/treeitem.h index 508907c..3229c7f 100644 --- a/treeitem.h +++ b/treeitem.h @@ -31,7 +31,7 @@ public: // Action types enum ActionTypes { NoAction = 50, - Modify, + Modify, Remove, Rebuild }; diff --git a/uefitool.cpp b/uefitool.cpp index a73b931..7a48df3 100644 --- a/uefitool.cpp +++ b/uefitool.cpp @@ -18,11 +18,15 @@ UEFITool::UEFITool(QWidget *parent) : QMainWindow(parent), ui(new Ui::UEFITool) { + // Create UI ui->setupUi(this); - ffsEngine = NULL; - - //Connect + searchDialog = new SearchDialog(this); + ffsEngine = NULL; + + // Connect signals to slots connect(ui->actionOpenImageFile, SIGNAL(triggered()), this, SLOT(openImageFile())); + connect(ui->actionSaveImageFile, SIGNAL(triggered()), this, SLOT(saveImageFile())); + connect(ui->actionSearch, SIGNAL(triggered()), this, SLOT(search())); connect(ui->actionExtract, SIGNAL(triggered()), this, SLOT(extractAsIs())); connect(ui->actionExtractBody, SIGNAL(triggered()), this, SLOT(extractBody())); connect(ui->actionExtractUncompressed, SIGNAL(triggered()), this, SLOT(extractUncompressed())); @@ -32,120 +36,51 @@ UEFITool::UEFITool(QWidget *parent) : connect(ui->actionReplace, SIGNAL(triggered()), this, SLOT(replace())); connect(ui->actionRemove, SIGNAL(triggered()), this, SLOT(remove())); connect(ui->actionRebuild, SIGNAL(triggered()), this, SLOT(rebuild())); - connect(ui->actionSaveImageFile, SIGNAL(triggered()), this, SLOT(saveImageFile())); - connect(ui->actionChangeToNone, SIGNAL(triggered()), this, SLOT(changeToNone())); + connect(ui->actionChangeToNone, SIGNAL(triggered()), this, SLOT(changeToNone())); connect(ui->actionChangeToEfi11, SIGNAL(triggered()), this, SLOT(changeToEfi11())); connect(ui->actionChangeToTiano, SIGNAL(triggered()), this, SLOT(changeToTiano())); connect(ui->actionChangeToLzma, SIGNAL(triggered()), this, SLOT(changeToLzma())); - connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about())); + connect(ui->actionMessagesClear, SIGNAL(triggered()), this, SLOT(clearMessages())); + connect(ui->actionAbout, SIGNAL(triggered()), this, SLOT(about())); connect(ui->actionAboutQt, SIGNAL(triggered()), this, SLOT(aboutQt())); connect(ui->actionQuit, SIGNAL(triggered()), this, SLOT(exit())); - - // Enable Drag-and-Drop actions - this->setAcceptDrops(true); + connect(QCoreApplication::instance(), SIGNAL(aboutToQuit()), this, SLOT(writeSettings())); - // Create menus - createMenus(); + // Enable Drag-and-Drop actions + this->setAcceptDrops(true); // Initialize non-persistent data init(); -} - -void UEFITool::createMenus() -{ - // Capsule - capsuleMenu.clear(); - capsuleMenu.addAction(ui->actionExtract); - capsuleMenu.addAction(ui->actionExtractBody); - capsuleMenu.addSeparator(); - capsuleMenu.addAction(ui->actionRebuild); - - // Image - imageMenu.clear(); - imageMenu.addAction(ui->actionExtract); - imageMenu.addSeparator(); - imageMenu.addAction(ui->actionRebuild); - // Region - regionMenu.clear(); - regionMenu.addAction(ui->actionExtract); - regionMenu.addSeparator(); - regionMenu.addAction(ui->actionRebuild); - - // Padding - paddingMenu.clear(); - paddingMenu.addAction(ui->actionExtract); - - // Volume - volumeMenu.clear(); - volumeMenu.addAction(ui->actionExtract); - volumeMenu.addAction(ui->actionExtractBody); - volumeMenu.addSeparator(); - volumeMenu.addAction(ui->actionRebuild); - volumeMenu.addSeparator(); - volumeMenu.addAction(ui->actionInsertInto); - volumeMenu.addSeparator(); - volumeMenu.addAction(ui->actionRemove); - - // File - fileMenu.clear(); - fileMenu.addAction(ui->actionExtract); - fileMenu.addAction(ui->actionExtractBody); - //fileMenu.addAction(ui->actionExtractUncompressed); - fileMenu.addSeparator(); - fileMenu.addAction(ui->actionRebuild); - fileMenu.addSeparator(); - fileMenu.addAction(ui->actionInsertInto); - fileMenu.addAction(ui->actionInsertBefore); - fileMenu.addAction(ui->actionInsertAfter); - fileMenu.addSeparator(); - fileMenu.addAction(ui->actionRemove); - - // Section - sectionMenu.clear(); - sectionMenu.addAction(ui->actionExtract); - sectionMenu.addAction(ui->actionExtractBody); - //sectionMenu.addAction(ui->actionExtractUncompressed); - sectionMenu.addSeparator(); - sectionMenu.addAction(ui->actionRebuild); - sectionMenu.addSeparator(); - sectionMenu.addAction(ui->actionInsertInto); - sectionMenu.addAction(ui->actionInsertBefore); - sectionMenu.addAction(ui->actionInsertAfter); - sectionMenu.addSeparator(); - sectionMenu.addAction(ui->actionRemove); - sectionMenu.addSeparator(); - sectionMenu.addMenu(ui->menuChangeCompressionTo); + // Read stored settings + readSettings(); } UEFITool::~UEFITool() { delete ui; delete ffsEngine; + delete searchDialog; } void UEFITool::init() { - // Clear components + // Clear components ui->messageListWidget->clear(); ui->infoEdit->clear(); - // Disable actions and menus - ui->actionExtract->setDisabled(true); - ui->actionExtractBody->setDisabled(true); - ui->actionExtractUncompressed->setDisabled(true); - ui->actionReplace->setDisabled(true); - ui->actionRemove->setDisabled(true); - ui->actionRebuild->setDisabled(true); - ui->actionInsertInto->setDisabled(true); - ui->actionInsertBefore->setDisabled(true); - ui->actionInsertAfter->setDisabled(true); - ui->actionSaveImageFile->setDisabled(true); - ui->menuChangeCompressionTo->setDisabled(true); + // Disable menus + ui->menuCapsuleActions->setDisabled(true); + ui->menuImageActions->setDisabled(true); + ui->menuRegionActions->setDisabled(true); + ui->menuPaddingActions->setDisabled(true); + ui->menuVolumeActions->setDisabled(true); + ui->menuFileActions->setDisabled(true); + ui->menuSectionActions->setDisabled(true); // Make new ffsEngine - if (ffsEngine) - delete ffsEngine; + if (ffsEngine) + delete ffsEngine; ffsEngine = new FfsEngine(this); ui->structureTreeView->setModel(ffsEngine->model()); @@ -155,8 +90,6 @@ void UEFITool::init() connect(ui->structureTreeView->selectionModel(), SIGNAL(currentChanged(const QModelIndex &, const QModelIndex &)), this, SLOT(populateUi(const QModelIndex &))); connect(ui->messageListWidget, SIGNAL(itemDoubleClicked(QListWidgetItem*)), this, SLOT(scrollTreeView(QListWidgetItem*))); - - resizeTreeViewColums(); } void UEFITool::populateUi(const QModelIndex ¤t) @@ -168,8 +101,20 @@ void UEFITool::populateUi(const QModelIndex ¤t) UINT8 type = item->type(); UINT8 subtype = item->subtype(); UINT8 algorithm = item->compression(); - + + // Set info text ui->infoEdit->setPlainText(item->info()); + + // Enable menus + ui->menuCapsuleActions->setEnabled(type == TreeItem::Capsule); + ui->menuImageActions->setEnabled(type == TreeItem::Image); + ui->menuRegionActions->setEnabled(type == TreeItem::Region); + ui->menuPaddingActions->setEnabled(type == TreeItem::Padding); + ui->menuVolumeActions->setEnabled(type == TreeItem::Volume); + ui->menuFileActions->setEnabled(type == TreeItem::File); + ui->menuSectionActions->setEnabled(type == TreeItem::Section); + + // Enable actions ui->actionExtract->setDisabled(item->hasEmptyHeader() && item->hasEmptyBody() && item->hasEmptyTail()); ui->actionRebuild->setDisabled(item->hasEmptyHeader() && item->hasEmptyBody() && item->hasEmptyTail()); ui->actionExtractBody->setDisabled(item->hasEmptyHeader()); @@ -178,10 +123,33 @@ void UEFITool::populateUi(const QModelIndex ¤t) || (type == TreeItem::Section && (subtype == EFI_SECTION_COMPRESSION || subtype == EFI_SECTION_GUID_DEFINED || subtype == EFI_SECTION_DISPOSABLE))); ui->actionInsertBefore->setEnabled(type == TreeItem::File || type == TreeItem::Section); ui->actionInsertAfter->setEnabled(type == TreeItem::File || type == TreeItem::Section); - ui->menuChangeCompressionTo->setEnabled(type == TreeItem::Section && subtype == EFI_SECTION_COMPRESSION && + ui->menuChangeCompressionTo->setEnabled(type == TreeItem::Section && subtype == EFI_SECTION_COMPRESSION && (algorithm == COMPRESSION_ALGORITHM_NONE || COMPRESSION_ALGORITHM_EFI11 || algorithm == COMPRESSION_ALGORITHM_TIANO || algorithm == COMPRESSION_ALGORITHM_LZMA)); } +void UEFITool::search() +{ + if (searchDialog->exec() != QDialog::Accepted) + return; + + int index = searchDialog->ui->dataTypeComboBox->currentIndex(); + if (index == 0) { // Hex pattern + QByteArray pattern = QByteArray::fromHex(searchDialog->ui->searchEdit->text().toAscii()); + if (pattern.isEmpty()) + return; + ffsEngine->findHexPattern(pattern, searchDialog->ui->dataOnlyRadioButton->isChecked()); + showMessages(); + } + else if (index == 1) { // Text string + QString pattern = searchDialog->ui->searchEdit->text(); + if (pattern.isEmpty()) + return; + ffsEngine->findTextPattern(pattern, searchDialog->ui->unicodeCheckBox->isChecked(), + (Qt::CaseSensitivity) searchDialog->ui->caseSensitiveCheckBox->isChecked()); + showMessages(); + } +} + void UEFITool::rebuild() { QModelIndex index = ui->structureTreeView->selectionModel()->currentIndex(); @@ -214,7 +182,7 @@ void UEFITool::insert(const UINT8 mode) TreeItem* item = static_cast(index.internalPointer()); UINT8 type; - UINT8 objectType; + UINT8 objectType; if (mode == INSERT_MODE_BEFORE || mode == INSERT_MODE_AFTER) type = item->parent()->type(); @@ -225,12 +193,12 @@ void UEFITool::insert(const UINT8 mode) switch (type) { case TreeItem::Volume: path = QFileDialog::getOpenFileName(this, tr("Select FFS file to insert"),".","FFS files (*.ffs *.bin);;All files (*.*)"); - objectType = TreeItem::File; + objectType = TreeItem::File; break; case TreeItem::File: case TreeItem::Section: path = QFileDialog::getOpenFileName(this, tr("Select section file to insert"),".","Section files (*.sct *.bin);;All files (*.*)"); - objectType = TreeItem::Section; + objectType = TreeItem::Section; break; default: return; @@ -327,14 +295,14 @@ void UEFITool::changeToNone() void UEFITool::about() { - QMessageBox::about(this, tr("About UEFITool"), tr( - "Copyright (c) 2013, Nikolaj Schlej aka CodeRush.

" - "The program is dedicated to RevoGirl. Rest in peace, young genius.

" - "The program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License.
" - "The full text of the license may be found at OpenSource.org.

" - "THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS, " - "WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, " - "EITHER EXPRESS OR IMPLIED.")); + QMessageBox::about(this, tr("About UEFITool"), tr( + "Copyright (c) 2013, Nikolaj Schlej aka CodeRush.

" + "The program is dedicated to RevoGirl. Rest in peace, young genius.

" + "The program and the accompanying materials are licensed and made available under the terms and conditions of the BSD License.
" + "The full text of the license may be found at OpenSource.org.

" + "THE PROGRAM IS DISTRIBUTED UNDER THE BSD LICENSE ON AN \"AS IS\" BASIS, " + "WITHOUT WARRANTIES OR REPRESENTATIONS OF ANY KIND, " + "EITHER EXPRESS OR IMPLIED.")); } void UEFITool::aboutQt() @@ -344,7 +312,7 @@ void UEFITool::aboutQt() void UEFITool::exit() { - QCoreApplication::exit(0); + QCoreApplication::exit(0); } void UEFITool::saveImageFile() @@ -360,7 +328,7 @@ void UEFITool::saveImageFile() QByteArray reconstructed; UINT8 result = ffsEngine->reconstructImage(reconstructed); - showMessage(); + showMessages(); if (result) { ui->statusBar->showMessage(tr("Reconstruction failed (%1)").arg(result)); return; @@ -372,7 +340,7 @@ void UEFITool::saveImageFile() ui->statusBar->showMessage(tr("Reconstructed image written")); } -void UEFITool::resizeTreeViewColums() +void UEFITool::resizeTreeViewColumns() { int count = ffsEngine->model()->columnCount(); for(int i = 0; i < count; i++) @@ -406,13 +374,21 @@ void UEFITool::openImageFile(QString path) init(); UINT8 result = ffsEngine->parseInputFile(buffer); - showMessage(); - if (result) + showMessages(); + if (result) ui->statusBar->showMessage(tr("Opened file can't be parsed (%1)").arg(result)); else ui->statusBar->showMessage(tr("Opened: %1").arg(fileInfo.fileName())); - resizeTreeViewColums(); + // Enable search + ui->actionSearch->setEnabled(true); +} + +void UEFITool::clearMessages() +{ + ffsEngine->clearMessages(); + messageItems.clear(); + ui->messageListWidget->clear(); } void UEFITool::extract(const UINT8 mode) @@ -425,35 +401,35 @@ void UEFITool::extract(const UINT8 mode) UINT8 type = item->type(); QString path; - if(mode == EXTRACT_MODE_AS_IS) { - switch (type) { - case TreeItem::Capsule: - path = QFileDialog::getSaveFileName(this, tr("Save capsule to binary file"),".","Capsule files (*.cap *.bin);;All files (*.*)"); - break; - case TreeItem::Image: - path = QFileDialog::getSaveFileName(this, tr("Save image to binary file"),".","Image files (*.rom *.bin);;All files (*.*)"); - break; - case TreeItem::Region: - path = QFileDialog::getSaveFileName(this, tr("Save region to binary file"),".","Region files (*.rgn *.bin);;All files (*.*)"); - break; - case TreeItem::Padding: - path = QFileDialog::getSaveFileName(this, tr("Save padding to binary file"),".","Padding files (*.pad *.bin);;All files (*.*)"); - break; - case TreeItem::Volume: - path = QFileDialog::getSaveFileName(this, tr("Save volume to binary file"),".","Volume files (*.vol *.bin);;All files (*.*)"); - break; - case TreeItem::File: - path = QFileDialog::getSaveFileName(this, tr("Save FFS file to binary file"),".","FFS files (*.ffs *.bin);;All files (*.*)"); - break; - case TreeItem::Section: - path = QFileDialog::getSaveFileName(this, tr("Save section file to binary file"),".","Section files (*.sct *.bin);;All files (*.*)"); - break; - default: - return; - } - } - else - path = QFileDialog::getSaveFileName(this, tr("Save object to binary file"),".","Binary files (*.bin);;All files (*.*)"); + if(mode == EXTRACT_MODE_AS_IS) { + switch (type) { + case TreeItem::Capsule: + path = QFileDialog::getSaveFileName(this, tr("Save capsule to binary file"),".","Capsule files (*.cap *.bin);;All files (*.*)"); + break; + case TreeItem::Image: + path = QFileDialog::getSaveFileName(this, tr("Save image to binary file"),".","Image files (*.rom *.bin);;All files (*.*)"); + break; + case TreeItem::Region: + path = QFileDialog::getSaveFileName(this, tr("Save region to binary file"),".","Region files (*.rgn *.bin);;All files (*.*)"); + break; + case TreeItem::Padding: + path = QFileDialog::getSaveFileName(this, tr("Save padding to binary file"),".","Padding files (*.pad *.bin);;All files (*.*)"); + break; + case TreeItem::Volume: + path = QFileDialog::getSaveFileName(this, tr("Save volume to binary file"),".","Volume files (*.vol *.bin);;All files (*.*)"); + break; + case TreeItem::File: + path = QFileDialog::getSaveFileName(this, tr("Save FFS file to binary file"),".","FFS files (*.ffs *.bin);;All files (*.*)"); + break; + case TreeItem::Section: + path = QFileDialog::getSaveFileName(this, tr("Save section file to binary file"),".","Section files (*.sct *.bin);;All files (*.*)"); + break; + default: + return; + } + } + else + path = QFileDialog::getSaveFileName(this, tr("Save object to binary file"),".","Binary files (*.bin);;All files (*.*)"); QFile outputFile; outputFile.setFileName(path); @@ -500,13 +476,13 @@ void UEFITool::dropEvent(QDropEvent* event) openImageFile(path); } -void UEFITool::showMessage() +void UEFITool::showMessages() { ui->messageListWidget->clear(); - if (!ffsEngine) - return; + if (!ffsEngine) + return; - messageItems = ffsEngine->message(); + messageItems = ffsEngine->messages(); for (int i = 0; i < messageItems.count(); i++) { ui->messageListWidget->addItem(new MessageListItem(messageItems.at(i))); } @@ -516,46 +492,87 @@ void UEFITool::scrollTreeView(QListWidgetItem* item) { MessageListItem* messageItem = (MessageListItem*) item; QModelIndex index = messageItem->index(); - if (index.isValid()) { - ui->structureTreeView->scrollTo(index); + if (index.isValid()) { + ui->structureTreeView->scrollTo(index); ui->structureTreeView->selectionModel()->clearSelection(); ui->structureTreeView->selectionModel()->select(index, QItemSelectionModel::Select); } } -void UEFITool::contextMenuEvent (QContextMenuEvent* event) +void UEFITool::contextMenuEvent(QContextMenuEvent* event) { - if(!ui->structureTreeView->underMouse()) + if (ui->messageListWidget->underMouse()) { + ui->menuMessages->exec(event->globalPos()); return; - - QPoint pt = event->pos(); - QModelIndex index = ui->structureTreeView->indexAt(ui->structureTreeView->viewport()->mapFrom(this, pt)); - if(!index.isValid()) - return; - - TreeItem* item = static_cast(index.internalPointer()); - switch(item->type()) - { - case TreeItem::Capsule: - capsuleMenu.exec(event->globalPos()); - break; - case TreeItem::Image: - imageMenu.exec(event->globalPos()); - break; - case TreeItem::Region: - regionMenu.exec(event->globalPos()); - break; - case TreeItem::Padding: - paddingMenu.exec(event->globalPos()); - break; - case TreeItem::Volume: - volumeMenu.exec(event->globalPos()); - break; - case TreeItem::File: - fileMenu.exec(event->globalPos()); - break; - case TreeItem::Section: - sectionMenu.exec(event->globalPos()); - break; } + + if(!ui->structureTreeView->underMouse()) + return; + + QPoint pt = event->pos(); + QModelIndex index = ui->structureTreeView->indexAt(ui->structureTreeView->viewport()->mapFrom(this, pt)); + if(!index.isValid()) + return; + + TreeItem* item = static_cast(index.internalPointer()); + switch(item->type()) + { + case TreeItem::Capsule: + ui->menuCapsuleActions->exec(event->globalPos()); + break; + case TreeItem::Image: + ui->menuImageActions->exec(event->globalPos()); + break; + case TreeItem::Region: + ui->menuRegionActions->exec(event->globalPos()); + break; + case TreeItem::Padding: + ui->menuPaddingActions->exec(event->globalPos()); + break; + case TreeItem::Volume: + ui->menuVolumeActions->exec(event->globalPos()); + break; + case TreeItem::File: + ui->menuFileActions->exec(event->globalPos()); + break; + case TreeItem::Section: + ui->menuSectionActions->exec(event->globalPos()); + break; + } +} + +void UEFITool::readSettings() +{ + QSettings settings("UEFITool.ini", QSettings::IniFormat, this); + resize(settings.value("mainWindow/size", QSize(800, 600)).toSize()); + move(settings.value("mainWindow/position", QPoint(0, 0)).toPoint()); + QList horList, vertList; + horList.append(settings.value("mainWindow/treeWidth", 600).toInt()); + horList.append(settings.value("mainWindow/infoWidth", 180).toInt()); + vertList.append(settings.value("mainWindow/treeHeight", 400).toInt()); + vertList.append(settings.value("mainWindow/messageHeight", 180).toInt()); + ui->infoSplitter->setSizes(horList); + ui->messagesSplitter->setSizes(vertList); + resizeTreeViewColumns(); + ui->structureTreeView->setColumnWidth(0, settings.value("tree/columnWidth0", ui->structureTreeView->columnWidth(0)).toInt()); + ui->structureTreeView->setColumnWidth(1, settings.value("tree/columnWidth1", ui->structureTreeView->columnWidth(1)).toInt()); + ui->structureTreeView->setColumnWidth(2, settings.value("tree/columnWidth2", ui->structureTreeView->columnWidth(2)).toInt()); + ui->structureTreeView->setColumnWidth(3, settings.value("tree/columnWidth3", ui->structureTreeView->columnWidth(3)).toInt()); + //ui->structureTreeView->setColumnWidth(4, settings.value("tree/columnWidth4", 10).toInt()); +} + +void UEFITool::writeSettings() +{ + QSettings settings("UEFITool.ini", QSettings::IniFormat, this); + settings.setValue("mainWindow/size", size()); + settings.setValue("mainWindow/position", pos()); + settings.setValue("mainWindow/treeWidth", ui->structureGroupBox->width()); + settings.setValue("mainWindow/infoWidth", ui->infoGroupBox->width()); + settings.setValue("mainWindow/treeHeight", ui->structureGroupBox->height()); + settings.setValue("mainWindow/messageHeight", ui->messageGroupBox->height()); + settings.setValue("tree/columnWidth0", ui->structureTreeView->columnWidth(0)); + settings.setValue("tree/columnWidth1", ui->structureTreeView->columnWidth(1)); + settings.setValue("tree/columnWidth2", ui->structureTreeView->columnWidth(2)); + settings.setValue("tree/columnWidth3", ui->structureTreeView->columnWidth(3)); + //settings.setValue("tree/columnWidth4", ui->structureTreeView->columnWidth(4)); } \ No newline at end of file diff --git a/uefitool.h b/uefitool.h index a0e7119..522d648 100644 --- a/uefitool.h +++ b/uefitool.h @@ -21,18 +21,24 @@ #include #include #include +#include #include #include #include +#include +#include +#include #include +#include #include #include "basetypes.h" #include "ffs.h" #include "ffsengine.h" +#include "searchdialog.h" namespace Ui { -class UEFITool; + class UEFITool; } class UEFITool : public QMainWindow @@ -47,58 +53,55 @@ public: private slots: void init(); - void populateUi(const QModelIndex ¤t); - void openImageFile(); - void saveImageFile(); - - void resizeTreeViewColums(); + void populateUi(const QModelIndex ¤t); + void resizeTreeViewColumns(); void scrollTreeView(QListWidgetItem* item); - void extract(const UINT8 mode); + void openImageFile(); + void saveImageFile(); + void search(); + + void extract(const UINT8 mode); void extractAsIs(); void extractBody(); void extractUncompressed(); - void insert(const UINT8 mode); + void insert(const UINT8 mode); void insertInto(); void insertBefore(); void insertAfter(); - void replace(); + void replace(); - void remove(); + void remove(); - void rebuild(); - - void changeToNone(); + void rebuild(); + + void changeToNone(); void changeToEfi11(); void changeToTiano(); void changeToLzma(); - void about(); + void clearMessages(); + + void about(); void aboutQt(); void exit(); + void writeSettings(); private: - Ui::UEFITool * ui; + Ui::UEFITool* ui; FfsEngine* ffsEngine; - - QQueue messageItems; - void showMessage(); + SearchDialog* searchDialog; - QMenu capsuleMenu; - QMenu imageMenu; - QMenu regionMenu; - QMenu paddingMenu; - QMenu volumeMenu; - QMenu fileMenu; - QMenu sectionMenu; - void createMenus(); - + QQueue messageItems; + void showMessages(); + void dragEnterEvent(QDragEnterEvent* event); void dropEvent(QDropEvent* event); - void contextMenuEvent (QContextMenuEvent* event); + void contextMenuEvent(QContextMenuEvent* event); + void readSettings(); }; #endif diff --git a/uefitool.pro b/uefitool.pro index c0061d4..6225c5e 100644 --- a/uefitool.pro +++ b/uefitool.pro @@ -6,6 +6,7 @@ TEMPLATE = app SOURCES += main.cpp \ uefitool.cpp \ + searchdialog.cpp \ descriptor.cpp \ ffs.cpp \ ffsengine.cpp \ @@ -20,7 +21,9 @@ SOURCES += main.cpp \ Tiano/EfiTianoDecompress.c \ Tiano/EfiCompress.c \ Tiano/TianoCompress.c + HEADERS += uefitool.h \ + searchdialog.h \ basetypes.h \ descriptor.h \ gbe.h \ @@ -34,6 +37,10 @@ HEADERS += uefitool.h \ LZMA/LzmaDecompress.h \ Tiano/EfiTianoDecompress.h \ Tiano/EfiTianoCompress.h -FORMS += uefitool.ui + +FORMS += uefitool.ui \ + searchdialog.ui + RC_FILE = uefitool.rc + ICON = uefitool.icns diff --git a/uefitool.ui b/uefitool.ui index 9fbbc62..79a6eba 100644 --- a/uefitool.ui +++ b/uefitool.ui @@ -6,8 +6,8 @@ 0 0 - 800 - 600 + 834 + 499 @@ -20,7 +20,7 @@ true - UEFITool 0.10.0 + UEFITool 0.11.0 @@ -29,51 +29,106 @@ 0 - + - 5 + 0 - 8 + 0 - - - Structure + + + Qt::Vertical - - - 5 + + + Qt::Horizontal - - 8 + + + Structure + + + + 0 + + + 5 + + + + + + 0 + 0 + + + + 10 + + + false + + + true + + + 200 + + + true + + + + + + + + Information + + + + 0 + + + 5 + + + + + false + + + false + + + true + + + false + + + + + + + + + Messages - - - - - 0 - 0 - - - - 10 - - - false - - - true - - - 200 - - - true - - - - + + + 0 + + + 5 + + + + + + @@ -84,7 +139,7 @@ 0 0 - 800 + 834 21 @@ -95,40 +150,10 @@ + + - - - A&ction - - - - true - - - Change &compression to - - - - - - - - - - - - - - - - - - - - - - H&elp @@ -136,101 +161,115 @@ + + + &Action + + + + &Capsule + + + + + + + + + &Image + + + + + + + + &Region + + + + + + + + &Padding + + + + + + &Volume + + + + + + + + + + + + + &File + + + + + + + + + + + + + + + &Section + + + + Change compression to + + + + + + + + + + + + + + + + + + + + + + &Messages + + + + + + + + + + + + + - - - - 89 - 111 - - - - - 180 - 524287 - - - - QDockWidget::DockWidgetMovable - - - Qt::LeftDockWidgetArea|Qt::RightDockWidgetArea - - - Information - - - 2 - - - - - 5 - - - 8 - - - - - false - - - false - - - true - - - false - - - - - - - - - - 91 - 113 - - - - - 524287 - 113 - - - - QDockWidget::DockWidgetMovable - - - Qt::BottomDockWidgetArea|Qt::TopDockWidgetArea - - - Messages - - - 8 - - - - - 5 - - - 8 - - - - - - - false @@ -441,6 +480,25 @@ Ctrl+U + + + false + + + Sear&ch... + + + Ctrl+F + + + + + &Clear + + + Ctrl+Backspace + +