[7913] Fixed vmap_assambler sources. Updated binary. Author: VladimirMangos

* Fixed week ago added bugs into vmap code that break vmap_assambler sources work.
      Note: vmap_assambler binary not updated from nov 2008 until this commit and it has been correct working.
    * Add to vmap assambler process show output and add appropriate error messages output.
    * vmap_assambler binary updated.

--HG--
branch : trunk
This commit is contained in:
megamage
2009-05-31 15:09:00 -05:00
parent 507ae0a89d
commit 19e1230551
103 changed files with 3569 additions and 3623 deletions
+34 -32
View File
@@ -78,42 +78,44 @@ bool readConfigFile(char *pConffile, VMAP::TileAssembler* pTa)
//======================================================= //=======================================================
int main(int argc, char* argv[]) int main(int argc, char* argv[])
{ {
if(argc == 3 || argc == 4) if(argc != 3 && argc != 4)
{
bool ok = true;
char *src = argv[1];
char *dest = argv[2];
char *conffile = NULL;
if(argc >= 4) {
conffile = argv[3];
}
VMAP::TileAssembler* ta = new VMAP::TileAssembler(std::string(src), std::string(dest));
ta->setModelNameFilterMethod(modelNameFilter);
/*
All the names in the list are considered to be world maps or huge instances.
These maps will be spilt into tiles in the vmap assemble process
*/
if(conffile != NULL) {
ok = readConfigFile(conffile, ta);
if(!ok) {
printf("Can not open file config file: %s\n", conffile);
}
}
if(ok) { ok = ta->convertWorld(); }
if(ok) {
printf("Ok, all done\n");
} else {
printf("exit with errors\n");
return 1;
}
delete ta;
}
else
{ {
printf("\nusage: %s <raw data dir> <vmap dest dir> [config file name]\n", argv[0]); printf("\nusage: %s <raw data dir> <vmap dest dir> [config file name]\n", argv[0]);
return 1; return 1;
} }
char *src = argv[1];
char *dest = argv[2];
char *conffile = NULL;
if(argc >= 4)
conffile = argv[3];
VMAP::TileAssembler* ta = new VMAP::TileAssembler(std::string(src), std::string(dest));
ta->setModelNameFilterMethod(modelNameFilter);
/*
All the names in the list are considered to be world maps or huge instances.
These maps will be spilt into tiles in the vmap assemble process
*/
if(conffile != NULL)
{
if(!readConfigFile(conffile, ta))
{
printf("Can not open file config file: %s\n", conffile);
delete ta;
return 1;
}
}
if(!ta->convertWorld())
{
printf("exit with errors\n");
delete ta;
return 1;
}
delete ta;
printf("Ok, all done\n");
return 0; return 0;
} }
@@ -115,4 +115,3 @@ BOOL WINAPI SCOMP(Decompress)(char * pbOutBuffer, int * pdwOutLength, char * pbI
SetLastError(ERROR_CALL_NOT_IMPLEMENTED); SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
return FALSE; return FALSE;
} }
@@ -65,4 +65,3 @@ BOOL WINAPI SCOMP(Decompress)(char * pbOutBuffer, int * pdwOutLength, char * pb
#endif #endif
#endif // __STORM_H__ #endif // __STORM_H__
@@ -3,9 +3,9 @@
* Description: GfxDecode -- functions for reading Diablo's GFX files * Description: GfxDecode -- functions for reading Diablo's GFX files
* Author: Marko Friedemann <[email protected]> * Author: Marko Friedemann <[email protected]>
* Created at: Son Jan 27 15:20:43 CET 2002 * Created at: Son Jan 27 15:20:43 CET 2002
* Computer: hangloose.flachland-chemnitz.de * Computer: hangloose.flachland-chemnitz.de
* System: Linux 2.4.16 on i686 * System: Linux 2.4.16 on i686
* *
* Copyright (c) 2002 BMX-Chemnitz.DE All rights reserved. * Copyright (c) 2002 BMX-Chemnitz.DE All rights reserved.
* *
* --------------------------------------------------------------------- * ---------------------------------------------------------------------
@@ -60,12 +60,12 @@ static const uint16_t c_RampOffsetRight[17] = {
2, // __ before this, there are 2 Pixels 2, // __ before this, there are 2 Pixels
14, // + 12 --__ 4^2 - 2 14, // + 12 --__ 4^2 - 2
34, // + 20 --__ 6^2 - 2 34, // + 20 --__ 6^2 - 2
62, // + 28 this area --__ 8^2 - 2 62, // + 28 this area --__ 8^2 - 2
98, // + 36 is always --__ 10^2 - 2 pattern anyone? ;) 98, // + 36 is always --__ 10^2 - 2 pattern anyone? ;)
142, // + 44 colored --__ 142, // + 44 colored --__
194, // + 52 --__ 194, // + 52 --__
254, // + 60 lower ramp ends here --__ (-30 == 224) 254, // + 60 lower ramp ends here --__ (-30 == 224)
318, // + 64 upper ramp might be missing __-- 318, // + 64 upper ramp might be missing __--
374, // + 56 __-- | 374, // + 56 __-- |
422, // + 48 this area __-- | note that this 422, // + 48 this area __-- | note that this
462, // + 40 is always __-- | "drawing" 462, // + 40 is always __-- | "drawing"
@@ -133,7 +133,7 @@ class FrameBuf
cerr << "\n +++ at (" << uCols << "," << uRows << "), see for yourself *** \n\n"; cerr << "\n +++ at (" << uCols << "," << uRows << "), see for yourself *** \n\n";
uColorNum = TRANS_COL; // sane setting to avoid segfaults uColorNum = TRANS_COL; // sane setting to avoid segfaults
} }
memcpy(pCurrRow + 4*uCols, pPalette + 4*uColorNum, 4*sizeof(uint8_t)); memcpy(pCurrRow + 4*uCols, pPalette + 4*uColorNum, 4*sizeof(uint8_t));
if (++uCols == uXSize) if (++uCols == uXSize)
addLine(); addLine();
@@ -147,18 +147,18 @@ class FrameBuf
vector <uint8_t *>::reverse_iterator vri; vector <uint8_t *>::reverse_iterator vri;
// allocate a buffer to hold the actual image size // allocate a buffer to hold the actual image size
uint8_t *tmp = new uint8_t[4*uXSize*uRows]; uint8_t *tmp = new uint8_t[4*uXSize*uRows];
// the lines are upside down inside the vector, use reverse iterator // the lines are upside down inside the vector, use reverse iterator
for (i=0, vri=vecData.rbegin(); vri!=vecData.rend(); vri++, i++) for (i=0, vri=vecData.rbegin(); vri!=vecData.rend(); vri++, i++)
memcpy(tmp+4*uXSize*i, *vri, 4*uXSize*sizeof(uint8_t)); memcpy(tmp+4*uXSize*i, *vri, 4*uXSize*sizeof(uint8_t));
*upYSize = uRows; // set height *upYSize = uRows; // set height
if (uCols > 0) { if (uCols > 0) {
cerr << "\n*** there seemed to be an error (last line does not match boundary, " << uCols << " pixels left)"; cerr << "\n*** there seemed to be an error (last line does not match boundary, " << uCols << " pixels left)";
cerr << "\n +++ this is often caused by specifying an invalid width, see for yourself *** \n\n"; cerr << "\n +++ this is often caused by specifying an invalid width, see for yourself *** \n\n";
} }
return tmp; return tmp;
} }
}; };
@@ -183,17 +183,17 @@ uint8_t *celDecodeBlocks(uint8_t *pFileBuf, FrameBuf *pFrame, uint32_t *framesta
if (!pFrame->bHasBlocks) // sanity check if (!pFrame->bHasBlocks) // sanity check
return NULL; return NULL;
while (uFilePos < framestart[pFrame->uFrameNum+1]) { while (uFilePos < framestart[pFrame->uFrameNum+1]) {
cRead = pFileBuf[uFilePos++]; cRead = pFileBuf[uFilePos++];
if ((uFilePos == framestart[pFrame->uFrameNum]+1)) if ((uFilePos == framestart[pFrame->uFrameNum]+1))
// TODO: what is this 0x0A 0x00 stuff all about? // TODO: what is this 0x0A 0x00 stuff all about?
if ((cRead == 0x0A) && (pFileBuf[uFilePos] == 0x00)) { if ((cRead == 0x0A) && (pFileBuf[uFilePos] == 0x00)) {
uFilePos += 9; uFilePos += 9;
cRead = pFileBuf[uFilePos++]; cRead = pFileBuf[uFilePos++];
} }
if (cRead > 0x7F) if (cRead > 0x7F)
// transparent block (complement, 256-val) // transparent block (complement, 256-val)
for (i=0; i<256-cRead; i++) for (i=0; i<256-cRead; i++)
@@ -220,10 +220,10 @@ uint8_t *celDecodeRamps(uint8_t *pFileBuf, FrameBuf *pFrame, uint32_t *framestar
uint32_t uFilePos=0; uint32_t uFilePos=0;
uint16_t uBlockLen=0, i=0, j=0; uint16_t uBlockLen=0, i=0, j=0;
bool bFirstLonger=false; bool bFirstLonger=false;
if (!pFrame->bHasRamps) // sanity check if (!pFrame->bHasRamps) // sanity check
return NULL; return NULL;
if (pFrame->uXSize != 32) // only used in that case if (pFrame->uXSize != 32) // only used in that case
return NULL; return NULL;
@@ -265,7 +265,7 @@ uint8_t *celDecodeRamps(uint8_t *pFileBuf, FrameBuf *pFrame, uint32_t *framestar
pFrame->addPixel(pFileBuf[uFilePos++]); pFrame->addPixel(pFileBuf[uFilePos++]);
} }
} }
// now read the last 0x00 pair and fill up // now read the last 0x00 pair and fill up
uBlockLen = (uFrameLen == c_2RampSize ? 30 : 2); // one or two ramps? uBlockLen = (uFrameLen == c_2RampSize ? 30 : 2); // one or two ramps?
uFilePos = framestart[pFrame->uFrameNum] + (bLeft ? c_RampOffsetLeft[i] : c_RampOffsetRight[i]) + 2; uFilePos = framestart[pFrame->uFrameNum] + (bLeft ? c_RampOffsetLeft[i] : c_RampOffsetRight[i]) + 2;
@@ -276,16 +276,16 @@ uint8_t *celDecodeRamps(uint8_t *pFileBuf, FrameBuf *pFrame, uint32_t *framestar
for (j=0; j<pFrame->uXSize - uBlockLen; j++) for (j=0; j<pFrame->uXSize - uBlockLen; j++)
pFrame->addPixel(pFileBuf[uFilePos++]); pFrame->addPixel(pFileBuf[uFilePos++]);
} }
// now the rest of the file (plain) // now the rest of the file (plain)
while (uFilePos < framestart[pFrame->uFrameNum+1]) while (uFilePos < framestart[pFrame->uFrameNum+1])
pFrame->addPixel(pFileBuf[uFilePos++]); pFrame->addPixel(pFileBuf[uFilePos++]);
// the uppermost line is emtpy when 2 ramps are used // the uppermost line is emtpy when 2 ramps are used
if (uFrameLen == c_2RampSize) if (uFrameLen == c_2RampSize)
for (j=0; j<pFrame->uXSize; j++) for (j=0; j<pFrame->uXSize; j++)
pFrame->addPixel(TRANS_COL); pFrame->addPixel(TRANS_COL);
return pFrame->getData(); return pFrame->getData();
} }
@@ -308,17 +308,17 @@ uint8_t *celDecodeRamps(uint8_t *pFileBuf, FrameBuf *pFrame, uint32_t *framestar
* Comments: dirty hack, started from scratch @ 2000-10-11 * Comments: dirty hack, started from scratch @ 2000-10-11
* cleanly rewritten during incorporation into ladiks StormLib * cleanly rewritten during incorporation into ladiks StormLib
* status: structured hack ;) * status: structured hack ;)
* *
* It took me approx. 6 days to understand the format basics (hex viewer) * It took me approx. 6 days to understand the format basics (hex viewer)
* For this I had a little help from a dos tool ("ddecode", from * For this I had a little help from a dos tool ("ddecode", from
* www.cowlevel.com, binary only, no sources) which, however, gave * www.cowlevel.com, binary only, no sources) which, however, gave
* me the general idea what the pictures are actually supposed to look like. * me the general idea what the pictures are actually supposed to look like.
* *
* The fine adjustments, however, took quite some time and a little luck. * The fine adjustments, however, took quite some time and a little luck.
* After I had written to various people (mickyk and ladik), which could * After I had written to various people (mickyk and ladik), which could
* not help me, but wished best luck (thanks, btw, it helped ;)), I tried * not help me, but wished best luck (thanks, btw, it helped ;)), I tried
* some reverse engineering which was not succesful in the end. * some reverse engineering which was not succesful in the end.
* *
* I then had incidentally a new idea of what could be going on @ 2002-01-23. * I then had incidentally a new idea of what could be going on @ 2002-01-23.
* It just came to my mind that I could retry some actual painting in * It just came to my mind that I could retry some actual painting in
* reverse order (had done that before to no avail) and when looking closer * reverse order (had done that before to no avail) and when looking closer
@@ -334,48 +334,48 @@ uint8_t * WINAPI celGetFrameData(uint8_t *pFileBuf, uint8_t *palette, uint16_t u
uint32_t *framestart=NULL, frames=0, uFilePos=0; uint32_t *framestart=NULL, frames=0, uFilePos=0;
uint16_t i, tmpWord=0; uint16_t i, tmpWord=0;
uint8_t cRead=0, *data; uint8_t cRead=0, *data;
memcpy(&frames, pFileBuf, sizeof(uint32_t)); memcpy(&frames, pFileBuf, sizeof(uint32_t));
uFilePos += sizeof(uint32_t); uFilePos += sizeof(uint32_t);
if (pFileBuf == NULL) { if (pFileBuf == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (palette == NULL) { if (palette == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (uFrameNum > frames-1) { if (uFrameNum > frames-1) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (uYSize == NULL) { if (uYSize == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
// in case we want to know the rightmost pixels column (usable eg. for fonts) // in case we want to know the rightmost pixels column (usable eg. for fonts)
if (uMaxX != NULL) if (uMaxX != NULL)
*uMaxX = 0; *uMaxX = 0;
// get the frame offsets // get the frame offsets
framestart = new uint32_t[frames+1]; framestart = new uint32_t[frames+1];
for (i=0; i<frames+1; i++) { for (i=0; i<frames+1; i++) {
memcpy(&framestart[i], pFileBuf+uFilePos, sizeof(uint32_t)); memcpy(&framestart[i], pFileBuf+uFilePos, sizeof(uint32_t));
uFilePos += sizeof(uint32_t); uFilePos += sizeof(uint32_t);
} }
/****** block size ************************************************* /****** block size *************************************************
* depends on the image width * depends on the image width
******************************/ ******************************/
double erg = rint(sqrt(pow(2, rint(log((double)(framestart[uFrameNum+1] - framestart[uFrameNum])) / log(2.0))))); double erg = rint(sqrt(pow(2, rint(log((double)(framestart[uFrameNum+1] - framestart[uFrameNum])) / log(2.0)))));
pFrame = new FrameBuf(palette, uFrameNum, uXSize, uYSize, uMaxX, max((uint16_t)min((int)erg, 0x7F), uXSize)); pFrame = new FrameBuf(palette, uFrameNum, uXSize, uYSize, uMaxX, max((uint16_t)min((int)erg, 0x7F), uXSize));
/****** ramp detection -- AFAIK only needed for 32x32 tiles ******** /****** ramp detection -- AFAIK only needed for 32x32 tiles ********
* here I use hard coded constants because this is the only simple * here I use hard coded constants because this is the only simple
* way to get the detection done; plus this stuff is only to be * way to get the detection done; plus this stuff is only to be
@@ -385,7 +385,7 @@ uint8_t * WINAPI celGetFrameData(uint8_t *pFileBuf, uint8_t *palette, uint16_t u
uint32_t uFrameLen = framestart[uFrameNum+1] - framestart[uFrameNum]; uint32_t uFrameLen = framestart[uFrameNum+1] - framestart[uFrameNum];
if ((uXSize == 32) && ((uFrameLen == c_2RampSize) || (uFrameLen == c_1RampSize))) { if ((uXSize == 32) && ((uFrameLen == c_2RampSize) || (uFrameLen == c_1RampSize))) {
// use the static arrays for the check // use the static arrays for the check
for (i=0; i<(uFrameLen == c_2RampSize ? 16 : 8); i++) { for (i=0; i<(uFrameLen == c_2RampSize ? 16 : 8); i++) {
memcpy(&tmpWord, pFileBuf+framestart[uFrameNum]+c_RampOffsetLeft[i], sizeof(uint16_t)); memcpy(&tmpWord, pFileBuf+framestart[uFrameNum]+c_RampOffsetLeft[i], sizeof(uint16_t));
if (tmpWord != 0) if (tmpWord != 0)
@@ -400,7 +400,7 @@ uint8_t * WINAPI celGetFrameData(uint8_t *pFileBuf, uint8_t *palette, uint16_t u
} }
pFrame->bHasRamps = (i==(uFrameLen == c_2RampSize ? 16 : 8)); // bRampsLeft stays false in this case pFrame->bHasRamps = (i==(uFrameLen == c_2RampSize ? 16 : 8)); // bRampsLeft stays false in this case
} }
if (pFrame->bHasRamps) { // decode ramps and be off (if appropriate) if (pFrame->bHasRamps) { // decode ramps and be off (if appropriate)
data = celDecodeRamps(pFileBuf, pFrame, framestart, bRampsLeft); data = celDecodeRamps(pFileBuf, pFrame, framestart, bRampsLeft);
delete pFrame; delete pFrame;
@@ -408,25 +408,25 @@ uint8_t * WINAPI celGetFrameData(uint8_t *pFileBuf, uint8_t *palette, uint16_t u
return data; return data;
} }
} }
/*********** block detection *************************************** /*********** block detection ***************************************
* 0x0A as start byte seems to be sufficient (though I still dunno * 0x0A as start byte seems to be sufficient (though I still dunno
* what the trailing 10 bytes mean); in any other case we act as if * what the trailing 10 bytes mean); in any other case we act as if
* blocks were to be used and check afterwards if the image looks * blocks were to be used and check afterwards if the image looks
* OK (that is, the last line has no pixels in it) * OK (that is, the last line has no pixels in it)
******************************************************************/ ******************************************************************/
cRead = pFileBuf[framestart[uFrameNum]]; cRead = pFileBuf[framestart[uFrameNum]];
if (cRead == 0x0A) // sufficient if (cRead == 0x0A) // sufficient
pFrame->bHasBlocks = true; pFrame->bHasBlocks = true;
// if width == 32 && framelen == 32*32, assume plain // if width == 32 && framelen == 32*32, assume plain
else if ((uXSize != 32) || (uFrameLen != 32*32)) { // check needed else if ((uXSize != 32) || (uFrameLen != 32*32)) { // check needed
uFilePos=framestart[uFrameNum]; uFilePos=framestart[uFrameNum];
i=0; i=0;
// rush through the frame // rush through the frame
while (uFilePos < framestart[uFrameNum+1]) { while (uFilePos < framestart[uFrameNum+1]) {
cRead = pFileBuf[uFilePos++]; cRead = pFileBuf[uFilePos++];
// transparency blocks // transparency blocks
while (cRead > 0x7F) { while (cRead > 0x7F) {
i += 256-cRead; i += 256-cRead;
@@ -436,7 +436,7 @@ uint8_t * WINAPI celGetFrameData(uint8_t *pFileBuf, uint8_t *palette, uint16_t u
else else
cRead = 0; cRead = 0;
} }
// colored pixel block // colored pixel block
if (uFilePos < framestart[uFrameNum+1]) { if (uFilePos < framestart[uFrameNum+1]) {
if (cRead < pFrame->uMaxBlock + 1) { if (cRead < pFrame->uMaxBlock + 1) {
@@ -453,19 +453,19 @@ uint8_t * WINAPI celGetFrameData(uint8_t *pFileBuf, uint8_t *palette, uint16_t u
if (i%uXSize == 0) // looks as if we got it right if (i%uXSize == 0) // looks as if we got it right
pFrame->bHasBlocks=true; pFrame->bHasBlocks=true;
} }
if (pFrame->bHasBlocks) { // use block decoder if appropriate if (pFrame->bHasBlocks) { // use block decoder if appropriate
data = celDecodeBlocks(pFileBuf, pFrame, framestart); data = celDecodeBlocks(pFileBuf, pFrame, framestart);
delete pFrame; delete pFrame;
delete[] framestart; delete[] framestart;
return data; return data;
} }
// plain mode (#3), read each color index and write the pixel // plain mode (#3), read each color index and write the pixel
uFilePos=framestart[uFrameNum]; uFilePos=framestart[uFrameNum];
while (uFilePos < framestart[uFrameNum+1]) while (uFilePos < framestart[uFrameNum+1])
pFrame->addPixel(pFileBuf[uFilePos++]); pFrame->addPixel(pFileBuf[uFilePos++]);
// cleanup, return image data and height // cleanup, return image data and height
data = pFrame->getData(); data = pFrame->getData();
delete pFrame; delete pFrame;
@@ -496,7 +496,7 @@ uint16_t WINAPI cl2GetFrameCount(uint8_t *pFileBuf)
* *
* --------------------------------------------------------------- * ---------------------------------------------------------------
* Comments: dirty hack, started from scratch @ 2000-10-12 * Comments: dirty hack, started from scratch @ 2000-10-12
* *
* The format basics are similar to .cel, with the main difference * The format basics are similar to .cel, with the main difference
* that the values read have reverse interpretation. In .cel a value * that the values read have reverse interpretation. In .cel a value
* greater than 0x7F means transparency, while in .cl2 this means * greater than 0x7F means transparency, while in .cl2 this means
@@ -507,7 +507,7 @@ uint16_t WINAPI cl2GetFrameCount(uint8_t *pFileBuf)
* .cl2 only uses the block scheme, so there is no detection * .cl2 only uses the block scheme, so there is no detection
* necessary in order to get it right. The only thing still unknown * necessary in order to get it right. The only thing still unknown
* is that 0x0A 0x00 stuff... * is that 0x0A 0x00 stuff...
* *
* TODO: learn what 0x0A 0x00 means * TODO: learn what 0x0A 0x00 means
***********************************************************************/ ***********************************************************************/
BYTE ** WINAPI cl2GetDirData(BYTE *pFileBuf, BYTE *palette, WORD uXSize, WORD uDirNum, WORD *uYSize) BYTE ** WINAPI cl2GetDirData(BYTE *pFileBuf, BYTE *palette, WORD uXSize, WORD uDirNum, WORD *uYSize)
@@ -516,27 +516,27 @@ BYTE ** WINAPI cl2GetDirData(BYTE *pFileBuf, BYTE *palette, WORD uXSize, WORD uD
uint32_t frames=0, *framestart=NULL, uFilePos=0; uint32_t frames=0, *framestart=NULL, uFilePos=0;
uint16_t i, fc; uint16_t i, fc;
uint8_t cRead=0, **data=NULL; uint8_t cRead=0, **data=NULL;
if (pFileBuf == NULL) { if (pFileBuf == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (palette == NULL) { if (palette == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (uDirNum > 7) { if (uDirNum > 7) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (uYSize == NULL) { if (uYSize == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
// get direction offsets // get direction offsets
uint32_t dirstart[8]; uint32_t dirstart[8];
for (i=0; i<8; i++) { for (i=0; i<8; i++) {
@@ -545,23 +545,23 @@ BYTE ** WINAPI cl2GetDirData(BYTE *pFileBuf, BYTE *palette, WORD uXSize, WORD uD
} }
uFilePos = dirstart[uDirNum]; uFilePos = dirstart[uDirNum];
memcpy(&frames, pFileBuf+uFilePos, sizeof(uint32_t)); memcpy(&frames, pFileBuf+uFilePos, sizeof(uint32_t));
uFilePos += sizeof(uint32_t); uFilePos += sizeof(uint32_t);
data = new uint8_t*[frames]; data = new uint8_t*[frames];
// get frame offsets // get frame offsets
framestart = new uint32_t[frames+1]; framestart = new uint32_t[frames+1];
for (i=0; i<frames+1; i++) { for (i=0; i<frames+1; i++) {
memcpy(&framestart[i], pFileBuf+uFilePos, sizeof(uint32_t)); memcpy(&framestart[i], pFileBuf+uFilePos, sizeof(uint32_t));
uFilePos += sizeof(uint32_t); uFilePos += sizeof(uint32_t);
} }
// get frame data // get frame data
for (fc=0; fc<frames; fc++) { for (fc=0; fc<frames; fc++) {
pFrame = new FrameBuf(palette, 0, uXSize, uYSize, NULL, 0); pFrame = new FrameBuf(palette, 0, uXSize, uYSize, NULL, 0);
uFilePos = dirstart[uDirNum] + framestart[fc]; uFilePos = dirstart[uDirNum] + framestart[fc];
while (uFilePos < dirstart[uDirNum] + framestart[fc+1]) { while (uFilePos < dirstart[uDirNum] + framestart[fc+1]) {
@@ -583,12 +583,12 @@ BYTE ** WINAPI cl2GetDirData(BYTE *pFileBuf, BYTE *palette, WORD uXSize, WORD uD
for (i=0; i < 256-cRead; i++) for (i=0; i < 256-cRead; i++)
pFrame->addPixel(pFileBuf[uFilePos++]); pFrame->addPixel(pFileBuf[uFilePos++]);
} }
// got the frame data, save it // got the frame data, save it
data[fc] = pFrame->getData(); data[fc] = pFrame->getData();
delete pFrame; delete pFrame;
} }
delete[] framestart; delete[] framestart;
return data; return data;
} }
@@ -616,7 +616,7 @@ BYTE * WINAPI pcxGetData(BYTE *pFileBuf, DWORD uFileSize, BYTE uTransColor, WORD
uint16_t i=0; uint16_t i=0;
uint8_t *data, *palette; uint8_t *data, *palette;
uint8_t uColorNum=0, uCount=0; uint8_t uColorNum=0, uCount=0;
struct pcx_header_t { struct pcx_header_t {
uint8_t id; uint8_t id;
uint8_t version; uint8_t version;
@@ -635,17 +635,17 @@ BYTE * WINAPI pcxGetData(BYTE *pFileBuf, DWORD uFileSize, BYTE uTransColor, WORD
uint16_t colortype; uint16_t colortype;
uint8_t pad[58]; uint8_t pad[58];
} pcxHeader; } pcxHeader;
if (pFileBuf == NULL) { if (pFileBuf == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (uXSize == NULL) { if (uXSize == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
} }
if (uYSize == NULL) { if (uYSize == NULL) {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return NULL; return NULL;
@@ -655,12 +655,12 @@ BYTE * WINAPI pcxGetData(BYTE *pFileBuf, DWORD uFileSize, BYTE uTransColor, WORD
memcpy(&pcxHeader, pFileBuf, sizeof(struct pcx_header_t)); memcpy(&pcxHeader, pFileBuf, sizeof(struct pcx_header_t));
*uXSize = (pcxHeader.x1 - pcxHeader.x0 + 1); *uXSize = (pcxHeader.x1 - pcxHeader.x0 + 1);
*uYSize = (pcxHeader.y1 - pcxHeader.y0 + 1); *uYSize = (pcxHeader.y1 - pcxHeader.y0 + 1);
if ((pcxHeader.version != 2) && (pcxHeader.version != 5)) { if ((pcxHeader.version != 2) && (pcxHeader.version != 5)) {
cerr << "cannot handle pcx v" << pcxHeader.version << "\n"; cerr << "cannot handle pcx v" << pcxHeader.version << "\n";
return NULL; return NULL;
} }
// get palette // get palette
palette = new uint8_t[256*4]; palette = new uint8_t[256*4];
if (pFileBuf[uFileSize - 768 - 1] != 0x0C) { if (pFileBuf[uFileSize - 768 - 1] != 0x0C) {
@@ -672,7 +672,7 @@ BYTE * WINAPI pcxGetData(BYTE *pFileBuf, DWORD uFileSize, BYTE uTransColor, WORD
palette[i*4+3] = 0xFF; palette[i*4+3] = 0xFF;
} }
memset(palette+uTransColor*4, 0, 4*sizeof(uint8_t)); // transparent black memset(palette+uTransColor*4, 0, 4*sizeof(uint8_t)); // transparent black
// start right after the header // start right after the header
uFilePos = sizeof(struct pcx_header_t); uFilePos = sizeof(struct pcx_header_t);
data = new uint8_t[*uXSize * *uYSize * 4]; data = new uint8_t[*uXSize * *uYSize * 4];
@@ -684,15 +684,14 @@ BYTE * WINAPI pcxGetData(BYTE *pFileBuf, DWORD uFileSize, BYTE uTransColor, WORD
uColorNum = pFileBuf[uFilePos++]; uColorNum = pFileBuf[uFilePos++];
} else } else
uCount = 1; uCount = 1;
// draw count pixels with color val // draw count pixels with color val
for (i=0; i<uCount; i++) for (i=0; i<uCount; i++)
memcpy(data+(uDataRead++)*4, palette+uColorNum*4, 4*sizeof(uint8_t)); memcpy(data+(uDataRead++)*4, palette+uColorNum*4, 4*sizeof(uint8_t));
} }
// cleanup // cleanup
delete[] palette; delete[] palette;
return data; return data;
} }
+15 -16
View File
@@ -26,7 +26,7 @@ USHORT wPlatform = 0; // File platform
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Compression types // Compression types
// //
// Data compressions // Data compressions
// //
// Can be combination of MPQ_COMPRESSION_PKWARE, MPQ_COMPRESSION_BZIP2 // Can be combination of MPQ_COMPRESSION_PKWARE, MPQ_COMPRESSION_BZIP2
@@ -261,16 +261,16 @@ DWORD DetectFileSeed2(DWORD * pdwBlock, UINT nDwords, ...)
DWORD saveSeed1; DWORD saveSeed1;
DWORD dwTemp; DWORD dwTemp;
DWORD i, j; DWORD i, j;
// We need at least two DWORDS to detect the seed // We need at least two DWORDS to detect the seed
if(nDwords < 0x02 || nDwords > 0x10) if(nDwords < 0x02 || nDwords > 0x10)
return 0; return 0;
va_start(argList, nDwords); va_start(argList, nDwords);
for(i = 0; i < nDwords; i++) for(i = 0; i < nDwords; i++)
dwDecrypted[i] = va_arg(argList, DWORD); dwDecrypted[i] = va_arg(argList, DWORD);
va_end(argList); va_end(argList);
dwTemp = (*pdwBlock ^ dwDecrypted[0]) - 0xEEEEEEEE; dwTemp = (*pdwBlock ^ dwDecrypted[0]) - 0xEEEEEEEE;
for(i = 0; i < 0x100; i++) // Try all 255 possibilities for(i = 0; i < 0x100; i++) // Try all 255 possibilities
{ {
@@ -427,7 +427,7 @@ TMPQHash * GetHashEntry(TMPQArchive * ha, const char * szFileName)
// If filename is given by index, we have to search all hash entries for the right index. // If filename is given by index, we have to search all hash entries for the right index.
if(dwIndex <= ha->pHeader->dwBlockTableSize) if(dwIndex <= ha->pHeader->dwBlockTableSize)
{ {
// Pass all the hash entries and find the // Pass all the hash entries and find the
for(pHash = ha->pHashTable; pHash < pHashEnd; pHash++) for(pHash = ha->pHashTable; pHash < pHashEnd; pHash++)
{ {
if(pHash->dwBlockIndex == dwIndex) if(pHash->dwBlockIndex == dwIndex)
@@ -441,7 +441,7 @@ TMPQHash * GetHashEntry(TMPQArchive * ha, const char * szFileName)
dwName1 = DecryptName1(szFileName); dwName1 = DecryptName1(szFileName);
dwName2 = DecryptName2(szFileName); dwName2 = DecryptName2(szFileName);
pHash = pHash0 = ha->pHashTable + dwIndex; pHash = pHash0 = ha->pHashTable + dwIndex;
// Look for hash index // Look for hash index
while(pHash->dwBlockIndex != HASH_ENTRY_FREE) while(pHash->dwBlockIndex != HASH_ENTRY_FREE)
{ {
@@ -562,7 +562,7 @@ BOOL IsValidMpqHandle(TMPQArchive * ha)
return FALSE; return FALSE;
if(ha->pHeader == NULL || IsBadReadPtr(ha->pHeader, sizeof(TMPQHeader))) if(ha->pHeader == NULL || IsBadReadPtr(ha->pHeader, sizeof(TMPQHeader)))
return FALSE; return FALSE;
return (ha->pHeader->dwID == ID_MPQ); return (ha->pHeader->dwID == ID_MPQ);
} }
@@ -620,7 +620,7 @@ int AddFileToArchive(
{ {
if(nFileType == SFILE_TYPE_DATA) if(nFileType == SFILE_TYPE_DATA)
nCmpFirst = nCmpNext = nDataCmp; nCmpFirst = nCmpNext = nDataCmp;
if(nFileType == SFILE_TYPE_WAVE) if(nFileType == SFILE_TYPE_WAVE)
{ {
nCmpNext = uWaveCmpType[dwQuality]; nCmpNext = uWaveCmpType[dwQuality];
@@ -721,7 +721,7 @@ int AddFileToArchive(
// Get pointers to both block entries of the file // Get pointers to both block entries of the file
pBlockEx = ha->pExtBlockTable + pHash->dwBlockIndex; pBlockEx = ha->pExtBlockTable + pHash->dwBlockIndex;
pBlock = ha->pBlockTable + pHash->dwBlockIndex; pBlock = ha->pBlockTable + pHash->dwBlockIndex;
// Save the file size info // Save the file size info
pBlockEx->wFilePosHigh = (USHORT)RelativePos.HighPart; pBlockEx->wFilePosHigh = (USHORT)RelativePos.HighPart;
pBlock->dwFilePos = RelativePos.LowPart; pBlock->dwFilePos = RelativePos.LowPart;
@@ -735,7 +735,7 @@ int AddFileToArchive(
if(dwFlags & MPQ_FILE_ENCRYPTED) if(dwFlags & MPQ_FILE_ENCRYPTED)
{ {
dwSeed1 = DecryptFileSeed(szArchivedName); dwSeed1 = DecryptFileSeed(szArchivedName);
if(dwFlags & MPQ_FILE_FIXSEED) if(dwFlags & MPQ_FILE_FIXSEED)
dwSeed1 = (dwSeed1 + pBlock->dwFilePos) ^ pBlock->dwFSize; dwSeed1 = (dwSeed1 + pBlock->dwFilePos) ^ pBlock->dwFSize;
} }
@@ -785,7 +785,7 @@ int AddFileToArchive(
memset(pdwBlockPos, 0, dwBlockPosLen); memset(pdwBlockPos, 0, dwBlockPosLen);
pdwBlockPos[0] = dwBlockPosLen; pdwBlockPos[0] = dwBlockPosLen;
// Write the block positions // Write the block positions
BSWAP_ARRAY32_UNSIGNED((DWORD *)pdwBlockPos, nBlocks); BSWAP_ARRAY32_UNSIGNED((DWORD *)pdwBlockPos, nBlocks);
WriteFile(ha->hFile, pdwBlockPos, dwBlockPosLen, &dwTransferred, NULL); WriteFile(ha->hFile, pdwBlockPos, dwBlockPosLen, &dwTransferred, NULL);
@@ -852,7 +852,7 @@ int AddFileToArchive(
EncryptMPQBlock((DWORD *)pbToWrite, dwOutLength, dwSeed1 + nBlock); EncryptMPQBlock((DWORD *)pbToWrite, dwOutLength, dwSeed1 + nBlock);
BSWAP_ARRAY32_UNSIGNED((DWORD *)pbToWrite, dwOutLength / sizeof(DWORD)); BSWAP_ARRAY32_UNSIGNED((DWORD *)pbToWrite, dwOutLength / sizeof(DWORD));
} }
// Write the block // Write the block
WriteFile(ha->hFile, pbToWrite, dwOutLength, &dwTransferred, NULL); WriteFile(ha->hFile, pbToWrite, dwOutLength, &dwTransferred, NULL);
if(dwTransferred != dwOutLength) if(dwTransferred != dwOutLength)
@@ -876,10 +876,10 @@ int AddFileToArchive(
// If file is encrypted, block positions are also encrypted // If file is encrypted, block positions are also encrypted
if(dwFlags & MPQ_FILE_ENCRYPTED) if(dwFlags & MPQ_FILE_ENCRYPTED)
EncryptMPQBlock(pdwBlockPos, dwBlockPosLen, dwSeed1 - 1); EncryptMPQBlock(pdwBlockPos, dwBlockPosLen, dwSeed1 - 1);
// Set the position back to the block table // Set the position back to the block table
SetFilePointer(ha->hFile, FilePos.LowPart, &FilePos.HighPart, FILE_BEGIN); SetFilePointer(ha->hFile, FilePos.LowPart, &FilePos.HighPart, FILE_BEGIN);
// Write block positions to the archive // Write block positions to the archive
BSWAP_ARRAY32_UNSIGNED((DWORD *)pdwBlockPos, nBlocks); BSWAP_ARRAY32_UNSIGNED((DWORD *)pdwBlockPos, nBlocks);
WriteFile(ha->hFile, pdwBlockPos, dwBlockPosLen, &dwTransferred, NULL); WriteFile(ha->hFile, pdwBlockPos, dwBlockPosLen, &dwTransferred, NULL);
@@ -1015,7 +1015,7 @@ int SaveMPQTables(TMPQArchive * ha)
// Encrypt the block table and write it to the file // Encrypt the block table and write it to the file
EncryptBlockTable((DWORD *)pbBuffer, (BYTE *)"(block table)", dwBytes >> 2); EncryptBlockTable((DWORD *)pbBuffer, (BYTE *)"(block table)", dwBytes >> 2);
// Convert to little endian for file save // Convert to little endian for file save
BSWAP_ARRAY32_UNSIGNED((DWORD *)pbBuffer, dwBytes / sizeof(DWORD)); BSWAP_ARRAY32_UNSIGNED((DWORD *)pbBuffer, dwBytes / sizeof(DWORD));
WriteFile(ha->hFile, pbBuffer, dwBytes, &dwWritten, NULL); WriteFile(ha->hFile, pbBuffer, dwBytes, &dwWritten, NULL);
@@ -1072,4 +1072,3 @@ void FreeMPQArchive(TMPQArchive *& ha)
ha = NULL; ha = NULL;
} }
} }
@@ -86,4 +86,3 @@ int SListFileSaveToMpq(TMPQArchive * ha);
#endif // __SCOMMON_H__ #endif // __SCOMMON_H__
@@ -2,7 +2,7 @@
/* SCompression.cpp Copyright (c) Ladislav Zezula 2003 */ /* SCompression.cpp Copyright (c) Ladislav Zezula 2003 */
/*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
/* This module serves as a bridge between StormLib code and (de)compression */ /* This module serves as a bridge between StormLib code and (de)compression */
/* functions. All (de)compression calls go (and should only go) through this */ /* functions. All (de)compression calls go (and should only go) through this */
/* module. No system headers should be included in this module to prevent */ /* module. No system headers should be included in this module to prevent */
/* compile-time problems. */ /* compile-time problems. */
/*---------------------------------------------------------------------------*/ /*---------------------------------------------------------------------------*/
@@ -19,7 +19,7 @@
#include <string.h> #include <string.h>
// Include functions from Pkware Data Compression Library // Include functions from Pkware Data Compression Library
#include "pklib/pklib.h" #include "pklib/pklib.h"
// Include functions from zlib // Include functions from zlib
#ifndef __SYS_ZLIB #ifndef __SYS_ZLIB
@@ -29,10 +29,10 @@
#endif #endif
// Include functions from Huffmann compression // Include functions from Huffmann compression
#include "huffman/huff.h" #include "huffman/huff.h"
// Include functions from WAVe compression // Include functions from WAVe compression
#include "wave/wave.h" #include "wave/wave.h"
// Include functions from BZip2 compression library // Include functions from BZip2 compression library
#ifndef __SYS_BZLIB #ifndef __SYS_BZLIB
@@ -57,7 +57,7 @@ typedef struct
// Table of compression functions // Table of compression functions
typedef int (*COMPRESS)(char *, int *, char *, int, int *, int); typedef int (*COMPRESS)(char *, int *, char *, int, int *, int);
typedef struct typedef struct
{ {
unsigned long dwMask; // Compression mask unsigned long dwMask; // Compression mask
COMPRESS Compress; // Compression function COMPRESS Compress; // Compression function
@@ -81,7 +81,7 @@ typedef struct
// Function loads data from the input buffer. Used by Pklib's "implode" // Function loads data from the input buffer. Used by Pklib's "implode"
// and "explode" function as user-defined callback // and "explode" function as user-defined callback
// Returns number of bytes loaded // Returns number of bytes loaded
// //
// char * buf - Pointer to a buffer where to store loaded data // char * buf - Pointer to a buffer where to store loaded data
// unsigned int * size - Max. number of bytes to read // unsigned int * size - Max. number of bytes to read
// void * param - Custom pointer, parameter of implode/explode // void * param - Custom pointer, parameter of implode/explode
@@ -95,7 +95,7 @@ static unsigned int ReadInputData(char * buf, unsigned int * size, void * param)
// Check the case when not enough data available // Check the case when not enough data available
if(nToRead > nMaxAvail) if(nToRead > nMaxAvail)
nToRead = nMaxAvail; nToRead = nMaxAvail;
// Load data and increment offsets // Load data and increment offsets
memcpy(buf, pInfo->pInBuff + pInfo->nInPos, nToRead); memcpy(buf, pInfo->pInBuff + pInfo->nInPos, nToRead);
pInfo->nInPos += nToRead; pInfo->nInPos += nToRead;
@@ -105,7 +105,7 @@ static unsigned int ReadInputData(char * buf, unsigned int * size, void * param)
// Function for store output data. Used by Pklib's "implode" and "explode" // Function for store output data. Used by Pklib's "implode" and "explode"
// as user-defined callback // as user-defined callback
// //
// char * buf - Pointer to data to be written // char * buf - Pointer to data to be written
// unsigned int * size - Number of bytes to write // unsigned int * size - Number of bytes to write
// void * param - Custom pointer, parameter of implode/explode // void * param - Custom pointer, parameter of implode/explode
@@ -272,7 +272,7 @@ int Compress_zlib(char * pbOutBuffer, int * pdwOutLength, char * pbInBuffer, int
{ {
// Call zlib to compress the data // Call zlib to compress the data
nResult = deflate(&z, Z_FINISH); nResult = deflate(&z, Z_FINISH);
if(nResult == Z_OK || nResult == Z_STREAM_END) if(nResult == Z_OK || nResult == Z_STREAM_END)
*pdwOutLength = z.total_out; *pdwOutLength = z.total_out;
@@ -359,7 +359,7 @@ int Decompress_pklib(char * pbOutBuffer, int * pdwOutLength, char * pbInBuffer,
// Do the decompression // Do the decompression
explode(ReadInputData, WriteOutputData, work_buf, &Info); explode(ReadInputData, WriteOutputData, work_buf, &Info);
// Fix: If PKLIB is unable to decompress the data, they are uncompressed // Fix: If PKLIB is unable to decompress the data, they are uncompressed
if(Info.nOutPos == 0) if(Info.nOutPos == 0)
{ {
@@ -487,7 +487,7 @@ int WINAPI SCompCompress(char * pbCompressed, int * pdwOutLength, char * pbUncom
int dwInSize = dwInLength; int dwInSize = dwInLength;
int dwEntries = (sizeof(cmp_table) / sizeof(TCompressTable)); int dwEntries = (sizeof(cmp_table) / sizeof(TCompressTable));
int nResult = 1; int nResult = 1;
int i; int i;
// Check for valid parameters // Check for valid parameters
if(!pdwOutLength || *pdwOutLength < dwInLength || !pbCompressed || !pbUncompressed) if(!pdwOutLength || *pdwOutLength < dwInLength || !pbCompressed || !pbUncompressed)
@@ -523,7 +523,7 @@ int WINAPI SCompCompress(char * pbCompressed, int * pdwOutLength, char * pbUncom
{ {
if(uCompressions2 & cmp_table[i].dwMask) if(uCompressions2 & cmp_table[i].dwMask)
{ {
// Set the right output buffer // Set the right output buffer
dwCompressCount--; dwCompressCount--;
pbOutput = (dwCompressCount & 1) ? pbTempBuff : pbCompressed; pbOutput = (dwCompressCount & 1) ? pbTempBuff : pbCompressed;
@@ -611,7 +611,7 @@ int WINAPI SCompDecompress(char * pbOutBuffer, int * pdwOutLength, char * pbInBu
int dwCount = 0; // Counter for every use int dwCount = 0; // Counter for every use
int dwEntries = (sizeof(dcmp_table) / sizeof(TDecompressTable)); int dwEntries = (sizeof(dcmp_table) / sizeof(TDecompressTable));
int nResult = 1; int nResult = 1;
int i; int i;
// If the input length is the same as output, do nothing. // If the input length is the same as output, do nothing.
if(dwInLength == dwOutLength) if(dwInLength == dwOutLength)
@@ -623,11 +623,11 @@ int WINAPI SCompDecompress(char * pbOutBuffer, int * pdwOutLength, char * pbInBu
*pdwOutLength = dwInLength; *pdwOutLength = dwInLength;
return 1; return 1;
} }
// Get applied compression types and decrement data length // Get applied compression types and decrement data length
fDecompressions1 = fDecompressions2 = (unsigned char)*pbInBuffer++; fDecompressions1 = fDecompressions2 = (unsigned char)*pbInBuffer++;
dwInLength--; dwInLength--;
// Search decompression table type and get all types of compression // Search decompression table type and get all types of compression
for(i = 0; i < dwEntries; i++) for(i = 0; i < dwEntries; i++)
{ {
@@ -681,13 +681,13 @@ int WINAPI SCompDecompress(char * pbOutBuffer, int * pdwOutLength, char * pbInBu
{ {
if(pbWorkBuff != pbOutBuffer) if(pbWorkBuff != pbOutBuffer)
memcpy(pbOutBuffer, pbInBuffer, dwOutLength); memcpy(pbOutBuffer, pbInBuffer, dwOutLength);
} }
// Delete temporary buffer, if necessary // Delete temporary buffer, if necessary
if(pbTempBuff != NULL) if(pbTempBuff != NULL)
FREEMEM(pbTempBuff); FREEMEM(pbTempBuff);
*pdwOutLength = dwOutLength; *pdwOutLength = dwOutLength;
return nResult; return nResult;
} }
@@ -713,4 +713,3 @@ int WINAPI SCompSetDataCompression(int nDataCompression)
} }
@@ -143,7 +143,7 @@ static int CheckIfAllFilesKnown(TMPQArchive * ha, const char * szListFile, DWORD
SFileCloseFile(hFile); SFileCloseFile(hFile);
} }
// If the file is encrypted, we have to check // If the file is encrypted, we have to check
// If we can apply the file decryption seed // If we can apply the file decryption seed
if(dwFlags & MPQ_FILE_ENCRYPTED && dwSeed == 0) if(dwFlags & MPQ_FILE_ENCRYPTED && dwSeed == 0)
{ {
@@ -269,7 +269,7 @@ static int CopyMpqFileBlocks(
DecryptMPQBlock(pdwBlockPos, dwBytes, dwSeed1 - 1); DecryptMPQBlock(pdwBlockPos, dwBytes, dwSeed1 - 1);
if(pdwBlockPos[0] != dwBytes) if(pdwBlockPos[0] != dwBytes)
nError = ERROR_FILE_CORRUPT; nError = ERROR_FILE_CORRUPT;
memcpy(pdwBlockPos2, pdwBlockPos, dwBytes); memcpy(pdwBlockPos2, pdwBlockPos, dwBytes);
EncryptMPQBlock(pdwBlockPos2, dwBytes, dwSeed2 - 1); EncryptMPQBlock(pdwBlockPos2, dwBytes, dwSeed2 - 1);
} }
@@ -315,7 +315,7 @@ static int CopyMpqFileBlocks(
} }
// If necessary, re-encrypt the block // If necessary, re-encrypt the block
// Note: Recompression is not necessary here. Unlike encryption, // Note: Recompression is not necessary here. Unlike encryption,
// the compression does not depend on the position of the file in MPQ. // the compression does not depend on the position of the file in MPQ.
if((pBlock->dwFlags & MPQ_FILE_ENCRYPTED) && dwSeed1 != dwSeed2) if((pBlock->dwFlags & MPQ_FILE_ENCRYPTED) && dwSeed1 != dwSeed2)
{ {
@@ -583,7 +583,7 @@ BOOL WINAPI SFileCompactArchive(HANDLE hMPQ, const char * szListFile, BOOL /* bR
TempPos.LowPart = pBlock->dwFilePos; TempPos.LowPart = pBlock->dwFilePos;
if(TempPos.QuadPart < FirstFilePos.QuadPart) if(TempPos.QuadPart < FirstFilePos.QuadPart)
FirstFilePos = TempPos; FirstFilePos = TempPos;
pBlockEx++; pBlockEx++;
pBlock++; pBlock++;
} }
@@ -689,4 +689,3 @@ BOOL WINAPI SFileCompactArchive(HANDLE hMPQ, const char * szListFile, BOOL /* bR
CompactCB = NULL; CompactCB = NULL;
return (nError == ERROR_SUCCESS); return (nError == ERROR_SUCCESS);
} }
@@ -20,7 +20,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Local tables // Local tables
static DWORD PowersOfTwo[] = static DWORD PowersOfTwo[] =
{ {
0x0000002, 0x0000004, 0x0000008, 0x0000002, 0x0000004, 0x0000008,
0x0000010, 0x0000020, 0x0000040, 0x0000080, 0x0000010, 0x0000020, 0x0000040, 0x0000080,
@@ -52,7 +52,7 @@ static DWORD PowersOfTwo[] =
// //
// MPQ_CREATE_ARCHIVE_V1 - Creates MPQ archive version 1 // MPQ_CREATE_ARCHIVE_V1 - Creates MPQ archive version 1
// MPQ_CREATE_ARCHIVE_V2 - Creates MPQ archive version 2 // MPQ_CREATE_ARCHIVE_V2 - Creates MPQ archive version 2
// //
// dwHashTableSize - Size of the hash table (only if creating a new archive). // dwHashTableSize - Size of the hash table (only if creating a new archive).
// Must be between 2^4 (= 16) and 2^18 (= 262 144) // Must be between 2^4 (= 16) and 2^18 (= 262 144)
// //
@@ -118,7 +118,7 @@ BOOL WINAPI SFileCreateArchiveEx(const char * szMpqName, DWORD dwCreationDisposi
dwHashTableSize = HASH_TABLE_SIZE_MIN; dwHashTableSize = HASH_TABLE_SIZE_MIN;
if(dwHashTableSize > HASH_TABLE_SIZE_MAX) if(dwHashTableSize > HASH_TABLE_SIZE_MAX)
dwHashTableSize = HASH_TABLE_SIZE_MAX; dwHashTableSize = HASH_TABLE_SIZE_MAX;
// Round the hash table size up to the nearest power of two // Round the hash table size up to the nearest power of two
for(nIndex = 0; PowersOfTwo[nIndex] != 0; nIndex++) for(nIndex = 0; PowersOfTwo[nIndex] != 0; nIndex++)
{ {
@@ -249,7 +249,7 @@ BOOL WINAPI SFileCreateArchiveEx(const char * szMpqName, DWORD dwCreationDisposi
BSWAP_TMPQHEADER(ha->pHeader); BSWAP_TMPQHEADER(ha->pHeader);
WriteFile(ha->hFile, ha->pHeader, dwHeaderSize, &dwTransferred, NULL); WriteFile(ha->hFile, ha->pHeader, dwHeaderSize, &dwTransferred, NULL);
BSWAP_TMPQHEADER(ha->pHeader); BSWAP_TMPQHEADER(ha->pHeader);
if(dwTransferred != ha->pHeader->dwHeaderSize) if(dwTransferred != ha->pHeader->dwHeaderSize)
nError = ERROR_DISK_FULL; nError = ERROR_DISK_FULL;
@@ -273,7 +273,7 @@ BOOL WINAPI SFileCreateArchiveEx(const char * szMpqName, DWORD dwCreationDisposi
CloseHandle(hFile); CloseHandle(hFile);
SetLastError(nError); SetLastError(nError);
} }
// Return the values // Return the values
*phMPQ = (HANDLE)ha; *phMPQ = (HANDLE)ha;
return (nError == ERROR_SUCCESS); return (nError == ERROR_SUCCESS);
@@ -355,7 +355,7 @@ BOOL WINAPI SFileAddFileEx(HANDLE hMPQ, const char * szFileName, const char * sz
SetLastError(nError); SetLastError(nError);
return (nError == ERROR_SUCCESS); return (nError == ERROR_SUCCESS);
} }
// Adds a data file into the archive // Adds a data file into the archive
// TODO: Test for archives > 4GB // TODO: Test for archives > 4GB
BOOL WINAPI SFileAddFile(HANDLE hMPQ, const char * szFileName, const char * szArchivedName, DWORD dwFlags) BOOL WINAPI SFileAddFile(HANDLE hMPQ, const char * szFileName, const char * szArchivedName, DWORD dwFlags)
@@ -375,7 +375,7 @@ BOOL WINAPI SFileAddWave(HANDLE hMPQ, const char * szFileName, const char * szAr
// //
// This function removes a file from the archive. The file content // This function removes a file from the archive. The file content
// remains there, only the entries in the hash table and in the block // remains there, only the entries in the hash table and in the block
// table are updated. // table are updated.
// TODO: Test for archives > 4GB // TODO: Test for archives > 4GB
BOOL WINAPI SFileRemoveFile(HANDLE hMPQ, const char * szFileName, DWORD dwSearchScope) BOOL WINAPI SFileRemoveFile(HANDLE hMPQ, const char * szFileName, DWORD dwSearchScope)
@@ -528,4 +528,3 @@ BOOL WINAPI SFileRenameFile(HANDLE hMPQ, const char * szFileName, const char * s
return (nError == ERROR_SUCCESS); return (nError == ERROR_SUCCESS);
} }
@@ -61,4 +61,3 @@ BOOL WINAPI SFileExtractFile(HANDLE hMpq, const char * szToExtract, const char *
SetLastError(nError); SetLastError(nError);
return (BOOL)(nError == ERROR_SUCCESS); return (BOOL)(nError == ERROR_SUCCESS);
} }
@@ -67,7 +67,7 @@ BOOL CheckWildCard(const char * szString, const char * szWildCard)
// The next N characters must not agree // The next N characters must not agree
nMustNotMatch |= 0x70000000; nMustNotMatch |= 0x70000000;
break; break;
case '?': // Means "One or no character" case '?': // Means "One or no character"
while(*szWildCard == '?') while(*szWildCard == '?')
{ {
@@ -111,7 +111,7 @@ BOOL CheckWildCard(const char * szString, const char * szWildCard)
{ {
if((nResult = _strnicmp(szString, szWildCard, nMustMatch)) == 0) if((nResult = _strnicmp(szString, szWildCard, nMustMatch)) == 0)
break; break;
szString++; szString++;
nMustNotMatch--; nMustNotMatch--;
} }
@@ -207,7 +207,7 @@ HANDLE WINAPI SFileFindFirstFile(HANDLE hMPQ, const char * szMask, SFILE_FIND_DA
{ {
if(!IsValidMpqHandle(ha)) if(!IsValidMpqHandle(ha))
nError = ERROR_INVALID_PARAMETER; nError = ERROR_INVALID_PARAMETER;
if(szMask == NULL || lpFindFileData == NULL) if(szMask == NULL || lpFindFileData == NULL)
nError = ERROR_INVALID_PARAMETER; nError = ERROR_INVALID_PARAMETER;
@@ -245,7 +245,7 @@ HANDLE WINAPI SFileFindFirstFile(HANDLE hMPQ, const char * szMask, SFILE_FIND_DA
FreeMPQSearch(hs); FreeMPQSearch(hs);
SetLastError(nError); SetLastError(nError);
} }
// Return the result value // Return the result value
return (HANDLE)hs; return (HANDLE)hs;
} }
@@ -289,4 +289,3 @@ BOOL WINAPI SFileFindClose(HANDLE hFind)
FreeMPQSearch(hs); FreeMPQSearch(hs);
return TRUE; return TRUE;
} }
@@ -74,7 +74,7 @@ static int RelocateMpqTablePositions(TMPQArchive * ha)
TempSize.QuadPart = ha->ExtBlockTablePos.QuadPart + (pHeader->dwBlockTableSize * sizeof(TMPQBlockEx)); TempSize.QuadPart = ha->ExtBlockTablePos.QuadPart + (pHeader->dwBlockTableSize * sizeof(TMPQBlockEx));
if(TempSize.QuadPart > ha->MpqSize.QuadPart) if(TempSize.QuadPart > ha->MpqSize.QuadPart)
ha->MpqSize = TempSize; ha->MpqSize = TempSize;
// MPQ size does not include the bytes before MPQ header // MPQ size does not include the bytes before MPQ header
ha->MpqSize.QuadPart -= ha->MpqPos.QuadPart; ha->MpqSize.QuadPart -= ha->MpqPos.QuadPart;
return ERROR_SUCCESS; return ERROR_SUCCESS;
@@ -122,7 +122,7 @@ BOOL SFileOpenArchiveEx(
DWORD dwBlockTableSize = 0; // Block table size. DWORD dwBlockTableSize = 0; // Block table size.
DWORD dwTransferred; // Number of bytes read DWORD dwTransferred; // Number of bytes read
DWORD dwBytes = 0; // Number of bytes to read DWORD dwBytes = 0; // Number of bytes to read
int nError = ERROR_SUCCESS; int nError = ERROR_SUCCESS;
// Check the right parameters // Check the right parameters
if(nError == ERROR_SUCCESS) if(nError == ERROR_SUCCESS)
@@ -142,7 +142,7 @@ BOOL SFileOpenArchiveEx(
if(hFile == INVALID_HANDLE_VALUE) if(hFile == INVALID_HANDLE_VALUE)
nError = GetLastError(); nError = GetLastError();
} }
// Allocate the MPQhandle // Allocate the MPQhandle
if(nError == ERROR_SUCCESS) if(nError == ERROR_SUCCESS)
{ {
@@ -241,7 +241,7 @@ BOOL SFileOpenArchiveEx(
break; break;
} }
// If a MPQ shunt already has been found, // If a MPQ shunt already has been found,
// and no MPQ header was at potision pointed by the shunt, // and no MPQ header was at potision pointed by the shunt,
// then the archive is corrupt // then the archive is corrupt
if(ha->pShunt != NULL) if(ha->pShunt != NULL)
@@ -327,7 +327,7 @@ BOOL SFileOpenArchiveEx(
nError = ERROR_BAD_FORMAT; nError = ERROR_BAD_FORMAT;
break; break;
} }
// Remember the highest block table entry // Remember the highest block table entry
if(pHash->dwBlockIndex > dwMaxBlockIndex) if(pHash->dwBlockIndex > dwMaxBlockIndex)
dwMaxBlockIndex = pHash->dwBlockIndex; dwMaxBlockIndex = pHash->dwBlockIndex;
@@ -437,7 +437,7 @@ BOOL SFileOpenArchiveEx(
} }
} }
// If the user didn't specified otherwise, // If the user didn't specified otherwise,
// include the internal listfile to the TMPQArchive structure // include the internal listfile to the TMPQArchive structure
if((dwFlags & MPQ_OPEN_NO_LISTFILE) == 0) if((dwFlags & MPQ_OPEN_NO_LISTFILE) == 0)
{ {
@@ -479,7 +479,7 @@ BOOL WINAPI SFileOpenArchive(const char * szMpqName, DWORD dwPriority, DWORD dwF
BOOL WINAPI SFileCloseArchive(HANDLE hMPQ) BOOL WINAPI SFileCloseArchive(HANDLE hMPQ)
{ {
TMPQArchive * ha = (TMPQArchive *)hMPQ; TMPQArchive * ha = (TMPQArchive *)hMPQ;
if(!IsValidMpqHandle(ha)) if(!IsValidMpqHandle(ha))
{ {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
@@ -495,4 +495,3 @@ BOOL WINAPI SFileCloseArchive(HANDLE hMPQ)
return TRUE; return TRUE;
} }
@@ -25,7 +25,7 @@ static BOOL OpenLocalFile(const char * szFileName, HANDLE * phFile)
if(hFile != INVALID_HANDLE_VALUE) if(hFile != INVALID_HANDLE_VALUE)
{ {
// Allocate and initialize file handle // Allocate and initialize file handle
size_t nHandleSize = sizeof(TMPQFile) + strlen(szFileName); size_t nHandleSize = sizeof(TMPQFile) + strlen(szFileName);
if((hf = (TMPQFile *)ALLOCMEM(char, nHandleSize)) != NULL) if((hf = (TMPQFile *)ALLOCMEM(char, nHandleSize)) != NULL)
{ {
memset(hf, 0, nHandleSize); memset(hf, 0, nHandleSize);
@@ -62,7 +62,7 @@ static void FreeMPQFile(TMPQFile *& hf)
/*****************************************************************************/ /*****************************************************************************/
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// SFileEnumLocales enums all locale versions within MPQ. // SFileEnumLocales enums all locale versions within MPQ.
// Functions fills all available language identifiers on a file into the buffer // Functions fills all available language identifiers on a file into the buffer
// pointed by plcLocales. There must be enough entries to copy the localed, // pointed by plcLocales. There must be enough entries to copy the localed,
// otherwise the function returns ERROR_INSUFFICIENT_BUFFER. // otherwise the function returns ERROR_INSUFFICIENT_BUFFER.
@@ -220,7 +220,7 @@ BOOL WINAPI SFileOpenFileEx(HANDLE hMPQ, const char * szFileName, DWORD dwSearch
size_t nHandleSize = 0; // Memory space necessary to allocate TMPQHandle size_t nHandleSize = 0; // Memory space necessary to allocate TMPQHandle
int nError = ERROR_SUCCESS; int nError = ERROR_SUCCESS;
#ifdef _DEBUG #ifdef _DEBUG
// Due to increasing numbers of files in MPQs, I had to change the behavior // Due to increasing numbers of files in MPQs, I had to change the behavior
// of opening by file index. Now, the SFILE_OPEN_BY_INDEX value of dwSearchScope // of opening by file index. Now, the SFILE_OPEN_BY_INDEX value of dwSearchScope
// must be entered. This check will allow to find code places that are incompatible // must be entered. This check will allow to find code places that are incompatible
@@ -321,13 +321,13 @@ BOOL WINAPI SFileOpenFileEx(HANDLE hMPQ, const char * szFileName, DWORD dwSearch
hf->pBlock = pBlock; hf->pBlock = pBlock;
hf->nBlocks = (hf->pBlock->dwFSize + ha->dwBlockSize - 1) / ha->dwBlockSize; hf->nBlocks = (hf->pBlock->dwFSize + ha->dwBlockSize - 1) / ha->dwBlockSize;
hf->pHash = pHash; hf->pHash = pHash;
hf->MpqFilePos.HighPart = pBlockEx->wFilePosHigh; hf->MpqFilePos.HighPart = pBlockEx->wFilePosHigh;
hf->MpqFilePos.LowPart = pBlock->dwFilePos; hf->MpqFilePos.LowPart = pBlock->dwFilePos;
hf->MpqFilePos.QuadPart += ha->MpqPos.QuadPart; hf->MpqFilePos.QuadPart += ha->MpqPos.QuadPart;
hf->dwHashIndex = dwHashIndex; hf->dwHashIndex = dwHashIndex;
hf->dwFileIndex = dwBlockIndex; hf->dwFileIndex = dwBlockIndex;
// Allocate buffers for decompression. // Allocate buffers for decompression.
if(hf->pBlock->dwFlags & MPQ_FILE_COMPRESSED) if(hf->pBlock->dwFlags & MPQ_FILE_COMPRESSED)
@@ -337,11 +337,11 @@ BOOL WINAPI SFileOpenFileEx(HANDLE hMPQ, const char * szFileName, DWORD dwSearch
// As for newer MPQs, there may be one additional entry in the block table // As for newer MPQs, there may be one additional entry in the block table
// (if the MPQ_FILE_HAS_EXTRA flag is set). // (if the MPQ_FILE_HAS_EXTRA flag is set).
// Allocate the buffer to include this DWORD as well // Allocate the buffer to include this DWORD as well
if((hf->pdwBlockPos = ALLOCMEM(DWORD, hf->nBlocks + 2)) == NULL) if((hf->pdwBlockPos = ALLOCMEM(DWORD, hf->nBlocks + 2)) == NULL)
nError = ERROR_NOT_ENOUGH_MEMORY; nError = ERROR_NOT_ENOUGH_MEMORY;
} }
// Decrypt file seed. Cannot be used if the file is given by index // Decrypt file seed. Cannot be used if the file is given by index
if(dwSearchScope != SFILE_OPEN_BY_INDEX) if(dwSearchScope != SFILE_OPEN_BY_INDEX)
{ {
@@ -386,7 +386,7 @@ BOOL WINAPI SFileOpenFileEx(HANDLE hMPQ, const char * szFileName, DWORD dwSearch
BOOL WINAPI SFileCloseFile(HANDLE hFile) BOOL WINAPI SFileCloseFile(HANDLE hFile)
{ {
TMPQFile * hf = (TMPQFile *)hFile; TMPQFile * hf = (TMPQFile *)hFile;
if(!IsValidFileHandle(hf)) if(!IsValidFileHandle(hf))
{ {
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
@@ -401,4 +401,3 @@ BOOL WINAPI SFileCloseFile(HANDLE hFile)
FreeMPQFile(hf); FreeMPQFile(hf);
return TRUE; return TRUE;
} }
@@ -154,8 +154,8 @@ static DWORD WINAPI ReadMPQBlocks(TMPQFile * hf, DWORD dwBlockPos, BYTE * buffer
} }
} }
// Set file pointer, if necessary // Set file pointer, if necessary
if(ha->FilePointer.QuadPart != FilePos.QuadPart) if(ha->FilePointer.QuadPart != FilePos.QuadPart)
{ {
SetFilePointer(ha->hFile, FilePos.LowPart, &FilePos.HighPart, FILE_BEGIN); SetFilePointer(ha->hFile, FilePos.LowPart, &FilePos.HighPart, FILE_BEGIN);
} }
@@ -245,7 +245,7 @@ static DWORD WINAPI ReadMPQBlocks(TMPQFile * hf, DWORD dwBlockPos, BYTE * buffer
// TODO: Test for archives > 4GB // TODO: Test for archives > 4GB
static DWORD WINAPI ReadMPQFileSingleUnit(TMPQFile * hf, DWORD dwFilePos, BYTE * pbBuffer, DWORD dwToRead) static DWORD WINAPI ReadMPQFileSingleUnit(TMPQFile * hf, DWORD dwFilePos, BYTE * pbBuffer, DWORD dwToRead)
{ {
TMPQArchive * ha = hf->ha; TMPQArchive * ha = hf->ha;
DWORD dwBytesRead = 0; DWORD dwBytesRead = 0;
if(ha->FilePointer.QuadPart != hf->MpqFilePos.QuadPart) if(ha->FilePointer.QuadPart != hf->MpqFilePos.QuadPart)
@@ -311,7 +311,7 @@ static DWORD WINAPI ReadMPQFileSingleUnit(TMPQFile * hf, DWORD dwFilePos, BYTE *
// TODO: Test for archives > 4GB // TODO: Test for archives > 4GB
static DWORD WINAPI ReadMPQFile(TMPQFile * hf, DWORD dwFilePos, BYTE * pbBuffer, DWORD dwToRead) static DWORD WINAPI ReadMPQFile(TMPQFile * hf, DWORD dwFilePos, BYTE * pbBuffer, DWORD dwToRead)
{ {
TMPQArchive * ha = hf->ha; TMPQArchive * ha = hf->ha;
TMPQBlock * pBlock = hf->pBlock; // Pointer to file block TMPQBlock * pBlock = hf->pBlock; // Pointer to file block
DWORD dwBytesRead = 0; // Number of bytes read from the file DWORD dwBytesRead = 0; // Number of bytes read from the file
DWORD dwBlockPos; // Position in the file aligned to the whole blocks DWORD dwBlockPos; // Position in the file aligned to the whole blocks
@@ -359,7 +359,7 @@ static DWORD WINAPI ReadMPQFile(TMPQFile * hf, DWORD dwFilePos, BYTE * pbBuffer,
// Copy data from block buffer into target buffer // Copy data from block buffer into target buffer
memcpy(pbBuffer, ha->pbBlockBuffer + ha->dwBuffPos, dwToCopy); memcpy(pbBuffer, ha->pbBlockBuffer + ha->dwBuffPos, dwToCopy);
// Update pointers // Update pointers
dwToRead -= dwToCopy; dwToRead -= dwToCopy;
dwBytesRead += dwToCopy; dwBytesRead += dwToCopy;
@@ -374,7 +374,7 @@ static DWORD WINAPI ReadMPQFile(TMPQFile * hf, DWORD dwFilePos, BYTE * pbBuffer,
// Load the whole ("middle") blocks only if there are more or equal one block // Load the whole ("middle") blocks only if there are more or equal one block
if(dwToRead > ha->dwBlockSize) if(dwToRead > ha->dwBlockSize)
{ {
DWORD dwBlockBytes = dwToRead & ~(ha->dwBlockSize - 1); DWORD dwBlockBytes = dwToRead & ~(ha->dwBlockSize - 1);
dwLoaded = ReadMPQBlocks(hf, dwBlockPos, pbBuffer, dwBlockBytes); dwLoaded = ReadMPQBlocks(hf, dwBlockPos, pbBuffer, dwBlockBytes);
@@ -419,7 +419,7 @@ static DWORD WINAPI ReadMPQFile(TMPQFile * hf, DWORD dwFilePos, BYTE * pbBuffer,
dwBytesRead += dwToCopy; dwBytesRead += dwToCopy;
ha->dwBuffPos = dwToCopy; ha->dwBuffPos = dwToCopy;
} }
// Return what we've read // Return what we've read
return dwBytesRead; return dwBytesRead;
} }
@@ -456,7 +456,7 @@ BOOL WINAPI SFileReadFile(HANDLE hFile, VOID * lpBuffer, DWORD dwToRead, DWORD *
SetLastError(ERROR_HANDLE_EOF); SetLastError(ERROR_HANDLE_EOF);
return FALSE; return FALSE;
} }
if(pdwRead != NULL) if(pdwRead != NULL)
*pdwRead = dwTransferred; *pdwRead = dwTransferred;
return TRUE; return TRUE;
@@ -498,7 +498,7 @@ BOOL WINAPI SFileReadFile(HANDLE hFile, VOID * lpBuffer, DWORD dwToRead, DWORD *
DWORD WINAPI SFileGetFilePos(HANDLE hFile, DWORD * pdwFilePosHigh) DWORD WINAPI SFileGetFilePos(HANDLE hFile, DWORD * pdwFilePosHigh)
{ {
TMPQFile * hf = (TMPQFile *)hFile; TMPQFile * hf = (TMPQFile *)hFile;
if(pdwFilePosHigh != NULL) if(pdwFilePosHigh != NULL)
*pdwFilePosHigh = 0; *pdwFilePosHigh = 0;
@@ -525,7 +525,7 @@ DWORD WINAPI SFileGetFilePos(HANDLE hFile, DWORD * pdwFilePosHigh)
DWORD WINAPI SFileGetFileSize(HANDLE hFile, DWORD * pdwFileSizeHigh) DWORD WINAPI SFileGetFileSize(HANDLE hFile, DWORD * pdwFileSizeHigh)
{ {
TMPQFile * hf = (TMPQFile *)hFile; TMPQFile * hf = (TMPQFile *)hFile;
if(pdwFileSizeHigh != NULL) if(pdwFileSizeHigh != NULL)
*pdwFileSizeHigh = 0; *pdwFileSizeHigh = 0;
@@ -604,7 +604,7 @@ DWORD WINAPI SFileSetFilePointer(HANDLE hFile, LONG lFilePos, LONG * pdwFilePosH
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Tries to retrieve the file name // Tries to retrieve the file name
static TID2Ext id2ext[] = static TID2Ext id2ext[] =
{ {
{0x1A51504D, "mpq"}, // MPQ archive header ID ('MPQ\x1A') {0x1A51504D, "mpq"}, // MPQ archive header ID ('MPQ\x1A')
{0x46464952, "wav"}, // WAVE header 'RIFF' {0x46464952, "wav"}, // WAVE header 'RIFF'
@@ -623,7 +623,7 @@ static TID2Ext id2ext[] =
{0x3032444D, "m2"}, // WoW ??? .m2 {0x3032444D, "m2"}, // WoW ??? .m2
{0x43424457, "dbc"}, // ??? .dbc {0x43424457, "dbc"}, // ??? .dbc
{0x47585053, "bls"}, // WoW pixel shaders {0x47585053, "bls"}, // WoW pixel shaders
{0, NULL} // Terminator {0, NULL} // Terminator
}; };
// TODO: Test for archives > 4GB // TODO: Test for archives > 4GB
@@ -646,7 +646,7 @@ BOOL WINAPI SFileGetFileName(HANDLE hFile, char * szFileName)
if(hf == NULL || szFileName == NULL) if(hf == NULL || szFileName == NULL)
nError = ERROR_INVALID_PARAMETER; nError = ERROR_INVALID_PARAMETER;
} }
// If the file name is already filled, return it. // If the file name is already filled, return it.
if(nError == ERROR_SUCCESS && *hf->szFileName != 0) if(nError == ERROR_SUCCESS && *hf->szFileName != 0)
{ {
@@ -665,7 +665,7 @@ BOOL WINAPI SFileGetFileName(HANDLE hFile, char * szFileName)
if(nError == ERROR_SUCCESS) if(nError == ERROR_SUCCESS)
{ {
dwFirstBytes[0] = dwFirstBytes[1] = 0; dwFirstBytes[0] = dwFirstBytes[1] = 0;
dwFilePos = SFileSetFilePointer(hf, 0, NULL, FILE_CURRENT); dwFilePos = SFileSetFilePointer(hf, 0, NULL, FILE_CURRENT);
if(!SFileReadFile(hFile, &dwFirstBytes, sizeof(dwFirstBytes), NULL)) if(!SFileReadFile(hFile, &dwFirstBytes, sizeof(dwFirstBytes), NULL))
nError = GetLastError(); nError = GetLastError();
BSWAP_ARRAY32_UNSIGNED(dwFirstBytes, sizeof(dwFirstBytes) / sizeof(DWORD)); BSWAP_ARRAY32_UNSIGNED(dwFirstBytes, sizeof(dwFirstBytes) / sizeof(DWORD));
@@ -824,4 +824,3 @@ DWORD_PTR WINAPI SFileGetFileInfo(HANDLE hMpqOrFile, DWORD dwInfoType)
SetLastError(ERROR_INVALID_PARAMETER); SetLastError(ERROR_INVALID_PARAMETER);
return 0xFFFFFFFF; return 0xFFFFFFFF;
} }
@@ -71,7 +71,7 @@ static size_t ReadLine(TListFileCache * pCache, char * szLine, int nMaxChars)
{ {
char * szLineBegin = szLine; char * szLineBegin = szLine;
char * szLineEnd = szLine + nMaxChars - 1; char * szLineEnd = szLine + nMaxChars - 1;
__BeginLoading: __BeginLoading:
// Skip newlines, spaces, tabs and another non-printable stuff // Skip newlines, spaces, tabs and another non-printable stuff
@@ -156,7 +156,7 @@ int SListFileAddNode(TMPQArchive * ha, const char * szFileName)
dwName2 = pHash->dwName2; dwName2 = pHash->dwName2;
if((DWORD_PTR)ha->pListFile[dwHashIndex] <= LISTFILE_ENTRY_DELETED) if((DWORD_PTR)ha->pListFile[dwHashIndex] <= LISTFILE_ENTRY_DELETED)
return ERROR_SUCCESS; return ERROR_SUCCESS;
// Create the listfile node and insert it into the listfile table // Create the listfile node and insert it into the listfile table
nLength = strlen(szFileName); nLength = strlen(szFileName);
pNode = (TFileNode *)ALLOCMEM(char, sizeof(TFileNode) + nLength); pNode = (TFileNode *)ALLOCMEM(char, sizeof(TFileNode) + nLength);
@@ -310,8 +310,8 @@ int SListFileSaveToMpq(TMPQArchive * ha)
szBuffer[nLength + 0] = 0x0D; szBuffer[nLength + 0] = 0x0D;
szBuffer[nLength + 1] = 0x0A; szBuffer[nLength + 1] = 0x0A;
WriteFile(hFile, szBuffer, (DWORD)(nLength + 2), &dwTransferred, NULL); WriteFile(hFile, szBuffer, (DWORD)(nLength + 2), &dwTransferred, NULL);
} }
// Add the listfile into the archive. // Add the listfile into the archive.
SFileSetLocale(LANG_NEUTRAL); SFileSetLocale(LANG_NEUTRAL);
nError = AddFileToArchive(ha, hFile, LISTFILE_NAME, MPQ_FILE_COMPRESS_PKWARE | MPQ_FILE_ENCRYPTED | MPQ_FILE_REPLACEEXISTING, 0, SFILE_TYPE_DATA, NULL); nError = AddFileToArchive(ha, hFile, LISTFILE_NAME, MPQ_FILE_COMPRESS_PKWARE | MPQ_FILE_ENCRYPTED | MPQ_FILE_REPLACEEXISTING, 0, SFILE_TYPE_DATA, NULL);
@@ -329,7 +329,7 @@ int SListFileSaveToMpq(TMPQArchive * ha)
// File functions // File functions
// Adds a listfile into the MPQ archive. // Adds a listfile into the MPQ archive.
// Note that the function does not remove the // Note that the function does not remove the
// TODO: Test for archives > 4GB // TODO: Test for archives > 4GB
int WINAPI SFileAddListFile(HANDLE hMpq, const char * szListFile) int WINAPI SFileAddListFile(HANDLE hMpq, const char * szListFile)
{ {
@@ -359,7 +359,7 @@ int WINAPI SFileAddListFile(HANDLE hMpq, const char * szListFile)
if(nError == ERROR_SUCCESS) if(nError == ERROR_SUCCESS)
{ {
dwCacheSize = dwCacheSize =
dwFileSize = SFileGetFileSize(hListFile, NULL); dwFileSize = SFileGetFileSize(hListFile, NULL);
// Try to allocate memory for the complete file. If it fails, // Try to allocate memory for the complete file. If it fails,
@@ -443,7 +443,7 @@ HANDLE SListFileFindFirstFile(HANDLE hMpq, const char * szListFile, const char *
if(nError == ERROR_SUCCESS) if(nError == ERROR_SUCCESS)
{ {
dwCacheSize = dwCacheSize =
dwFileSize = SFileGetFileSize(hListFile, NULL); dwFileSize = SFileGetFileSize(hListFile, NULL);
// Try to allocate memory for the complete file. If it fails, // Try to allocate memory for the complete file. If it fails,
@@ -493,7 +493,7 @@ HANDLE SListFileFindFirstFile(HANDLE hMpq, const char * szListFile, const char *
// If some mask entered, check it // If some mask entered, check it
if(CheckWildCard(lpFindFileData->cFileName, pCache->szMask)) if(CheckWildCard(lpFindFileData->cFileName, pCache->szMask))
break; break;
} }
} }
@@ -559,4 +559,3 @@ BOOL SListFileFindClose(HANDLE hFind)
return FALSE; return FALSE;
} }
@@ -65,4 +65,3 @@ BOOL WINAPI SCOMP(Decompress)(char * pbOutBuffer, int * pdwOutLength, char * pb
#endif #endif
#endif // __STORM_H__ #endif // __STORM_H__
+23 -24
View File
@@ -55,7 +55,7 @@
// //
// The library type is encoded in the library name as the following // The library type is encoded in the library name as the following
// StormLibXYZ.lib // StormLibXYZ.lib
// //
// X - D for Debug version, R for Release version // X - D for Debug version, R for Release version
// Y - A for ANSI version, U for Unicode version (Unicode version does not exist yet) // Y - A for ANSI version, U for Unicode version (Unicode version does not exist yet)
// Z - S for static C library, D for multithreaded DLL C-library // Z - S for static C library, D for multithreaded DLL C-library
@@ -63,15 +63,15 @@
#if defined(_MSC_VER) && !defined (__STORMLIB_SELF__) #if defined(_MSC_VER) && !defined (__STORMLIB_SELF__)
#ifdef _DEBUG // DEBUG VERSIONS #ifdef _DEBUG // DEBUG VERSIONS
#ifdef _DLL #ifdef _DLL
#pragma comment(lib, "StormLibDAD.lib") // Debug Ansi Dynamic version #pragma comment(lib, "StormLibDAD.lib") // Debug Ansi Dynamic version
#else #else
#pragma comment(lib, "StormLibDAS.lib") // Debug Ansi Static version #pragma comment(lib, "StormLibDAS.lib") // Debug Ansi Static version
#endif #endif
#else // RELEASE VERSIONS #else // RELEASE VERSIONS
#ifdef _DLL #ifdef _DLL
#pragma comment(lib, "StormLibRAD.lib") // Release Ansi Dynamic version #pragma comment(lib, "StormLibRAD.lib") // Release Ansi Dynamic version
#else #else
#pragma comment(lib, "StormLibRAS.lib") // Release Ansi Static version #pragma comment(lib, "StormLibRAS.lib") // Release Ansi Static version
#endif #endif
#endif #endif
@@ -109,7 +109,7 @@
#define MPQ_FILE_COMPRESS_PKWARE 0x00000100 // Compression made by PKWARE Data Compression Library #define MPQ_FILE_COMPRESS_PKWARE 0x00000100 // Compression made by PKWARE Data Compression Library
#define MPQ_FILE_COMPRESS_MULTI 0x00000200 // Multiple compressions #define MPQ_FILE_COMPRESS_MULTI 0x00000200 // Multiple compressions
#define MPQ_FILE_COMPRESSED 0x0000FF00 // File is compressed #define MPQ_FILE_COMPRESSED 0x0000FF00 // File is compressed
#define MPQ_FILE_ENCRYPTED 0x00010000 // Indicates whether file is encrypted #define MPQ_FILE_ENCRYPTED 0x00010000 // Indicates whether file is encrypted
#define MPQ_FILE_FIXSEED 0x00020000 // File decrypt seed has to be fixed #define MPQ_FILE_FIXSEED 0x00020000 // File decrypt seed has to be fixed
#define MPQ_FILE_SINGLE_UNIT 0x01000000 // File is stored as a single unit, rather than split into sectors (Thx, Quantam) #define MPQ_FILE_SINGLE_UNIT 0x01000000 // File is stored as a single unit, rather than split into sectors (Thx, Quantam)
#define MPQ_FILE_DUMMY_FILE 0x02000000 // The file is only 1 byte long and its name is a hash #define MPQ_FILE_DUMMY_FILE 0x02000000 // The file is only 1 byte long and its name is a hash
@@ -132,8 +132,8 @@
#define MPQ_COMPRESSION_ZLIB 0x02 // ZLIB compression #define MPQ_COMPRESSION_ZLIB 0x02 // ZLIB compression
#define MPQ_COMPRESSION_PKWARE 0x08 // PKWARE DCL compression #define MPQ_COMPRESSION_PKWARE 0x08 // PKWARE DCL compression
#define MPQ_COMPRESSION_BZIP2 0x10 // BZIP2 compression #define MPQ_COMPRESSION_BZIP2 0x10 // BZIP2 compression
#define MPQ_COMPRESSION_WAVE_MONO 0x40 // #define MPQ_COMPRESSION_WAVE_MONO 0x40 //
#define MPQ_COMPRESSION_WAVE_STEREO 0x80 // #define MPQ_COMPRESSION_WAVE_STEREO 0x80 //
// Constants for SFileAddWave // Constants for SFileAddWave
@@ -168,7 +168,7 @@
#define CCB_COPYING_NON_MPQ_DATA 3 // Copying non-MPQ data: No params used #define CCB_COPYING_NON_MPQ_DATA 3 // Copying non-MPQ data: No params used
#define CCB_COMPACTING_FILES 4 // Compacting archive (dwParam1 = current, dwParam2 = total) #define CCB_COMPACTING_FILES 4 // Compacting archive (dwParam1 = current, dwParam2 = total)
#define CCB_CLOSING_ARCHIVE 5 // Closing archive: No params used #define CCB_CLOSING_ARCHIVE 5 // Closing archive: No params used
#define LISTFILE_NAME "(listfile)" // Name of internal listfile #define LISTFILE_NAME "(listfile)" // Name of internal listfile
#define SIGNATURE_NAME "(signature)" // Name of internal signature #define SIGNATURE_NAME "(signature)" // Name of internal signature
#define ATTRIBUTES_NAME "(attributes)" // Name of internal attributes file #define ATTRIBUTES_NAME "(attributes)" // Name of internal attributes file
@@ -213,10 +213,10 @@ struct TMPQShunt
struct TMPQHeader struct TMPQHeader
{ {
// The ID_MPQ ('MPQ\x1A') signature // The ID_MPQ ('MPQ\x1A') signature
DWORD dwID; DWORD dwID;
// Size of the archive header // Size of the archive header
DWORD dwHeaderSize; DWORD dwHeaderSize;
// Size of MPQ archive // Size of MPQ archive
// This field is deprecated in the Burning Crusade MoPaQ format, and the size of the archive // This field is deprecated in the Burning Crusade MoPaQ format, and the size of the archive
@@ -235,14 +235,14 @@ struct TMPQHeader
// Offset to the beginning of the hash table, relative to the beginning of the archive. // Offset to the beginning of the hash table, relative to the beginning of the archive.
DWORD dwHashTablePos; DWORD dwHashTablePos;
// Offset to the beginning of the block table, relative to the beginning of the archive. // Offset to the beginning of the block table, relative to the beginning of the archive.
DWORD dwBlockTablePos; DWORD dwBlockTablePos;
// Number of entries in the hash table. Must be a power of two, and must be less than 2^16 for // Number of entries in the hash table. Must be a power of two, and must be less than 2^16 for
// the original MoPaQ format, or less than 2^20 for the Burning Crusade format. // the original MoPaQ format, or less than 2^20 for the Burning Crusade format.
DWORD dwHashTableSize; DWORD dwHashTableSize;
// Number of entries in the block table // Number of entries in the block table
DWORD dwBlockTableSize; DWORD dwBlockTableSize;
}; };
@@ -267,7 +267,7 @@ struct TMPQHash
{ {
// The hash of the file path, using method A. // The hash of the file path, using method A.
DWORD dwName1; DWORD dwName1;
// The hash of the file path, using method B. // The hash of the file path, using method B.
DWORD dwName2; DWORD dwName2;
@@ -303,16 +303,16 @@ struct TMPQBlock
{ {
// Offset of the beginning of the block, relative to the beginning of the archive. // Offset of the beginning of the block, relative to the beginning of the archive.
DWORD dwFilePos; DWORD dwFilePos;
// Compressed file size // Compressed file size
DWORD dwCSize; DWORD dwCSize;
// Only valid if the block is a file; otherwise meaningless, and should be 0. // Only valid if the block is a file; otherwise meaningless, and should be 0.
// If the file is compressed, this is the size of the uncompressed file data. // If the file is compressed, this is the size of the uncompressed file data.
DWORD dwFSize; DWORD dwFSize;
// Flags for the file. See MPQ_FILE_XXXX constants // Flags for the file. See MPQ_FILE_XXXX constants
DWORD dwFlags; DWORD dwFlags;
}; };
@@ -333,7 +333,7 @@ struct TFileNode
// There can be more files that have the same name. // There can be more files that have the same name.
// (e.g. multiple language files). We don't want to // (e.g. multiple language files). We don't want to
// have an entry for each of them, so the entries will be referenced. // have an entry for each of them, so the entries will be referenced.
// When a number of node references reaches zero, // When a number of node references reaches zero,
// the node will be deleted // the node will be deleted
size_t nLength; // File name length size_t nLength; // File name length
@@ -372,7 +372,7 @@ struct TMPQArchive
TMPQHash * pHashTable; // Hash table TMPQHash * pHashTable; // Hash table
TMPQBlock * pBlockTable; // Block table TMPQBlock * pBlockTable; // Block table
TMPQBlockEx * pExtBlockTable; // Extended block table TMPQBlockEx * pExtBlockTable; // Extended block table
TMPQShunt Shunt; // MPQ shunt. Valid only when ID_MPQ_SHUNT has been found TMPQShunt Shunt; // MPQ shunt. Valid only when ID_MPQ_SHUNT has been found
TMPQHeader2 Header; // MPQ header TMPQHeader2 Header; // MPQ header
@@ -520,8 +520,8 @@ int WINAPI SFileAddListFile(HANDLE hMpq, const char * szListFile);
// Archive creating and editing // Archive creating and editing
BOOL WINAPI SFileCreateArchiveEx(const char * szMpqName, DWORD dwCreationDisposition, DWORD dwHashTableSize, HANDLE * phMPQ); BOOL WINAPI SFileCreateArchiveEx(const char * szMpqName, DWORD dwCreationDisposition, DWORD dwHashTableSize, HANDLE * phMPQ);
BOOL WINAPI SFileAddFile(HANDLE hMPQ, const char * szFileName, const char * szArchivedName, DWORD dwFlags); BOOL WINAPI SFileAddFile(HANDLE hMPQ, const char * szFileName, const char * szArchivedName, DWORD dwFlags);
BOOL WINAPI SFileAddWave(HANDLE hMPQ, const char * szFileName, const char * szArchivedName, DWORD dwFlags, DWORD dwQuality); BOOL WINAPI SFileAddWave(HANDLE hMPQ, const char * szFileName, const char * szArchivedName, DWORD dwFlags, DWORD dwQuality);
BOOL WINAPI SFileRemoveFile(HANDLE hMPQ, const char * szFileName, DWORD dwSearchScope = SFILE_OPEN_BY_INDEX); BOOL WINAPI SFileRemoveFile(HANDLE hMPQ, const char * szFileName, DWORD dwSearchScope = SFILE_OPEN_BY_INDEX);
BOOL WINAPI SFileRenameFile(HANDLE hMPQ, const char * szOldFileName, const char * szNewFileName); BOOL WINAPI SFileRenameFile(HANDLE hMPQ, const char * szOldFileName, const char * szNewFileName);
BOOL WINAPI SFileSetFileLocale(HANDLE hFile, LCID lcNewLocale); BOOL WINAPI SFileSetFileLocale(HANDLE hFile, LCID lcNewLocale);
@@ -577,4 +577,3 @@ BYTE ** WINAPI cl2GetDirData(BYTE *fileBuf, BYTE *palette, USHORT xsize, USHORT
BYTE * WINAPI pcxGetData(BYTE *filebuf, DWORD filesize, BYTE transcol, USHORT *xsize, USHORT *ysize); BYTE * WINAPI pcxGetData(BYTE *filebuf, DWORD filesize, BYTE transcol, USHORT *xsize, USHORT *ysize);
#endif // __STORMLIB_H_ #endif // __STORMLIB_H_
+24 -25
View File
@@ -20,7 +20,7 @@
/* 12.11.03 1.02 Dan Macintosh compatibility */ /* 12.11.03 1.02 Dan Macintosh compatibility */
/* 24.07.04 1.03 Sam Mac OS X compatibility */ /* 24.07.04 1.03 Sam Mac OS X compatibility */
/* 22.11.06 1.04 Sam Mac OS X compatibility (for StormLib 6.0) */ /* 22.11.06 1.04 Sam Mac OS X compatibility (for StormLib 6.0) */
/* 31.12.06 1.05 XPinguin Full GNU/Linux compatibility */ /* 31.12.06 1.05 XPinguin Full GNU/Linux compatibility */
/*****************************************************************************/ /*****************************************************************************/
#ifndef __STORMPORT_H__ #ifndef __STORMPORT_H__
@@ -35,9 +35,9 @@
#define _CRT_NON_CONFORMING_SWPRINTFS #define _CRT_NON_CONFORMING_SWPRINTFS
#endif #endif
#include <assert.h> #include <assert.h>
#include <stdio.h> #include <stdio.h>
#include <windows.h> #include <windows.h>
#define PLATFORM_LITTLE_ENDIAN 1 #define PLATFORM_LITTLE_ENDIAN 1
#ifdef WIN64 #ifdef WIN64
@@ -50,20 +50,20 @@
#endif #endif
// Defines for Mac Carbon // Defines for Mac Carbon
#if !defined(PLATFORM_DEFINED) && defined(__APPLE__) // Mac Carbon API #if !defined(PLATFORM_DEFINED) && defined(__APPLE__) // Mac Carbon API
// Macintosh using Carbon // Macintosh using Carbon
#include <Carbon/Carbon.h> // Mac OS X #include <Carbon/Carbon.h> // Mac OS X
#define _stricmp strcasecmp // Case insensitive strcmp has a different name on this platform. #define _stricmp strcasecmp // Case insensitive strcmp has a different name on this platform.
#define _strnicmp strncasecmp #define _strnicmp strncasecmp
typedef void * LPCSTR; typedef void * LPCSTR;
typedef unsigned long * LPDWORD; typedef unsigned long * LPDWORD;
typedef long * PLONG; typedef long * PLONG;
typedef void * LPVOID; typedef void * LPVOID;
typedef unsigned int UINT; typedef unsigned int UINT;
#define PKEXPORT #define PKEXPORT
#define __SYS_ZLIB #define __SYS_ZLIB
#define __SYS_BZLIB #define __SYS_BZLIB
@@ -120,17 +120,17 @@
typedef void * LPOVERLAPPED; // Unsupported on Linux typedef void * LPOVERLAPPED; // Unsupported on Linux
typedef char TCHAR; typedef char TCHAR;
typedef unsigned long LCID; typedef unsigned long LCID;
typedef void * LPCSTR; typedef void * LPCSTR;
typedef unsigned long * LPDWORD; typedef unsigned long * LPDWORD;
typedef long * PLONG; typedef long * PLONG;
typedef void * LPVOID; typedef void * LPVOID;
typedef unsigned int UINT; typedef unsigned int UINT;
typedef struct _FILETIME typedef struct _FILETIME
{ {
DWORD dwLowDateTime; DWORD dwLowDateTime;
DWORD dwHighDateTime; DWORD dwHighDateTime;
} }
FILETIME, *PFILETIME; FILETIME, *PFILETIME;
@@ -152,7 +152,7 @@
LONGLONG QuadPart; LONGLONG QuadPart;
} }
LARGE_INTEGER, *PLARGE_INTEGER; LARGE_INTEGER, *PLARGE_INTEGER;
// Some Windows-specific defines // Some Windows-specific defines
#ifndef MAX_PATH #ifndef MAX_PATH
#define MAX_PATH 1024 #define MAX_PATH 1024
@@ -167,24 +167,24 @@
#endif #endif
#define VOID void #define VOID void
#define WINAPI #define WINAPI
#define FILE_BEGIN SEEK_SET #define FILE_BEGIN SEEK_SET
#define FILE_CURRENT SEEK_CUR #define FILE_CURRENT SEEK_CUR
#define FILE_END SEEK_END #define FILE_END SEEK_END
#define CREATE_NEW 1 #define CREATE_NEW 1
#define CREATE_ALWAYS 2 #define CREATE_ALWAYS 2
#define OPEN_EXISTING 3 #define OPEN_EXISTING 3
#define OPEN_ALWAYS 4 #define OPEN_ALWAYS 4
#define FILE_SHARE_READ 0x00000001L #define FILE_SHARE_READ 0x00000001L
#define GENERIC_WRITE 0x40000000 #define GENERIC_WRITE 0x40000000
#define GENERIC_READ 0x80000000 #define GENERIC_READ 0x80000000
#define FILE_FLAG_DELETE_ON_CLOSE 1 // Sam: Added these two defines so it would compile. #define FILE_FLAG_DELETE_ON_CLOSE 1 // Sam: Added these two defines so it would compile.
#define FILE_FLAG_SEQUENTIAL_SCAN 2 #define FILE_FLAG_SEQUENTIAL_SCAN 2
#define ERROR_SUCCESS 0 #define ERROR_SUCCESS 0
#define ERROR_INVALID_FUNCTION 1 #define ERROR_INVALID_FUNCTION 1
#define ERROR_FILE_NOT_FOUND 2 #define ERROR_FILE_NOT_FOUND 2
@@ -204,22 +204,22 @@
#define ERROR_PARAMETER_QUOTA_EXCEEDED 1283 #define ERROR_PARAMETER_QUOTA_EXCEEDED 1283
#define ERROR_FILE_CORRUPT 1392 #define ERROR_FILE_CORRUPT 1392
#define ERROR_INSUFFICIENT_BUFFER 4999 #define ERROR_INSUFFICIENT_BUFFER 4999
#define INVALID_HANDLE_VALUE ((HANDLE) -1) #define INVALID_HANDLE_VALUE ((HANDLE) -1)
#ifndef min #ifndef min
#define min(a, b) ((a < b) ? a : b) #define min(a, b) ((a < b) ? a : b)
#endif #endif
#ifndef max #ifndef max
#define max(a, b) ((a > b) ? a : b) #define max(a, b) ((a > b) ? a : b)
#endif #endif
#define _stricmp strcasecmp #define _stricmp strcasecmp
#define _strnicmp strncasecmp #define _strnicmp strncasecmp
extern int globalerr; extern int globalerr;
void SetLastError(int err); void SetLastError(int err);
int GetLastError(); int GetLastError();
char *ErrString(int err); char *ErrString(int err);
@@ -276,4 +276,3 @@
#endif #endif
#endif // __STORMPORT_H__ #endif // __STORMPORT_H__
@@ -2,7 +2,7 @@
* *
* Description: implementation for StormLib - linux port * Description: implementation for StormLib - linux port
* intended to be used in GLdiablo * intended to be used in GLdiablo
* *
* ----> StormLib was originally developed for Windows by * ----> StormLib was originally developed for Windows by
* Ladislav Zezula (www.zezula.net), and he did * Ladislav Zezula (www.zezula.net), and he did
* a _great_ job! Thanks Ladislav! * a _great_ job! Thanks Ladislav!
@@ -17,9 +17,9 @@
* *
* Author: Marko Friedemann <[email protected]> * Author: Marko Friedemann <[email protected]>
* Created at: Mon Jan 29 19:01:37 CEST 2001 * Created at: Mon Jan 29 19:01:37 CEST 2001
* Computer: whiplash.flachland-chemnitz.de * Computer: whiplash.flachland-chemnitz.de
* System: Linux 2.4.0 on i686 * System: Linux 2.4.0 on i686
* *
* Copyright (c) 2001 BMX-Chemnitz.DE All rights reserved. * Copyright (c) 2001 BMX-Chemnitz.DE All rights reserved.
* *
********************************************************************/ ********************************************************************/
@@ -97,7 +97,7 @@ DWORD GetFileSize(HANDLE hFile, DWORD *ulOffSetHigh)
struct stat fileinfo; struct stat fileinfo;
fstat((int)hFile, &fileinfo); fstat((int)hFile, &fileinfo);
return fileinfo.st_size; return fileinfo.st_size;
} }
@@ -163,7 +163,6 @@ BOOL DeleteFile(const char *lpFileName)
BOOL MoveFile(const char *lpExistingFileName, const char *lpNewFileName) BOOL MoveFile(const char *lpExistingFileName, const char *lpNewFileName)
{ {
return rename(lpExistingFileName, lpNewFileName); return rename(lpExistingFileName, lpNewFileName);
} }
#endif #endif
@@ -1,7 +1,7 @@
/******************************************************************** /********************************************************************
* *
* Description: implementation for StormLib - Macintosh port * Description: implementation for StormLib - Macintosh port
* *
* these are function wraps to execute Windows API calls * these are function wraps to execute Windows API calls
* as native Macintosh file calls (open/close/read/write/...) * as native Macintosh file calls (open/close/read/write/...)
* requires Mac OS X * requires Mac OS X
@@ -15,7 +15,7 @@
* *
********************************************************************/ ********************************************************************/
#ifndef _WIN32 || _WIN64 #ifndef _WIN32
#include "StormPort.h" #include "StormPort.h"
#include "StormLib.h" #include "StormLib.h"
@@ -45,14 +45,14 @@ static OSErr FSGetFullPath(const FSRef *ref, UInt8 *fullPath, UInt32 fullPathLen
OSErr result; OSErr result;
result = FSRefMakePath(ref, fullPath, fullPathLength); result = FSRefMakePath(ref, fullPath, fullPathLength);
return result; return result;
} }
static OSErr FSLocationFromFullPath(const void *fullPath, FSRef *ref) static OSErr FSLocationFromFullPath(const void *fullPath, FSRef *ref)
{ {
OSErr result; OSErr result;
result = FSPathMakeRef((UInt8 *)fullPath, ref, NULL); // Create an FSRef from the path result = FSPathMakeRef((UInt8 *)fullPath, ref, NULL); // Create an FSRef from the path
return result; return result;
} }
@@ -61,7 +61,7 @@ static OSErr FSLocationFromFullPath(const void *fullPath, FSRef *ref)
/*****************************************************************************/ /*****************************************************************************/
static OSErr FSCreateCompat(const FSRef *parentRef, OSType creator, OSType fileType, const UniChar *fileName, static OSErr FSCreateCompat(const FSRef *parentRef, OSType creator, OSType fileType, const UniChar *fileName,
UniCharCount nameLength, FSRef *ref) UniCharCount nameLength, FSRef *ref)
{ {
FSCatalogInfo theCatInfo; FSCatalogInfo theCatInfo;
@@ -71,7 +71,7 @@ static OSErr FSCreateCompat(const FSRef *parentRef, OSType creator, OSType fileT
((FileInfo *)&theCatInfo.finderInfo)->finderFlags = 0; ((FileInfo *)&theCatInfo.finderInfo)->finderFlags = 0;
SetPt(&((FileInfo *)&theCatInfo.finderInfo)->location, 0, 0); SetPt(&((FileInfo *)&theCatInfo.finderInfo)->location, 0, 0);
((FileInfo *)&theCatInfo.finderInfo)->reservedField = 0; ((FileInfo *)&theCatInfo.finderInfo)->reservedField = 0;
theErr = FSCreateFileUnicode(parentRef, nameLength, fileName, kFSCatInfoFinderInfo, &theCatInfo, ref, NULL); theErr = FSCreateFileUnicode(parentRef, nameLength, fileName, kFSCatInfoFinderInfo, &theCatInfo, ref, NULL);
return theErr; return theErr;
} }
@@ -84,11 +84,11 @@ static OSErr FSOpenDFCompat(FSRef *ref, char permission, short *refNum)
HFSUniStr255 forkName; HFSUniStr255 forkName;
OSErr theErr; OSErr theErr;
Boolean isFolder, wasChanged; Boolean isFolder, wasChanged;
theErr = FSResolveAliasFile(ref, TRUE, &isFolder, &wasChanged); theErr = FSResolveAliasFile(ref, TRUE, &isFolder, &wasChanged);
if (theErr != noErr) if (theErr != noErr)
return theErr; return theErr;
FSGetDataForkName(&forkName); FSGetDataForkName(&forkName);
theErr = FSOpenFork(ref, forkName.length, forkName.unicode, permission, refNum); theErr = FSOpenFork(ref, forkName.length, forkName.unicode, permission, refNum);
return theErr; return theErr;
@@ -209,7 +209,7 @@ void ConvertTMPQShunt(void *shunt)
void ConvertTMPQHeader(void *header) void ConvertTMPQHeader(void *header)
{ {
TMPQHeader2 * theHeader = (TMPQHeader2 *)header; TMPQHeader2 * theHeader = (TMPQHeader2 *)header;
theHeader->dwID = SwapULong(theHeader->dwID); theHeader->dwID = SwapULong(theHeader->dwID);
theHeader->dwHeaderSize = SwapULong(theHeader->dwHeaderSize); theHeader->dwHeaderSize = SwapULong(theHeader->dwHeaderSize);
theHeader->dwArchiveSize = SwapULong(theHeader->dwArchiveSize); theHeader->dwArchiveSize = SwapULong(theHeader->dwArchiveSize);
@@ -271,7 +271,7 @@ int GetLastError()
********************************************************************/ ********************************************************************/
char *ErrString(int err) char *ErrString(int err)
{ {
switch (err) switch (err)
{ {
case ERROR_INVALID_FUNCTION: case ERROR_INVALID_FUNCTION:
return "function not implemented"; return "function not implemented";
@@ -324,7 +324,7 @@ void GetTempPath(DWORD szTempLength, char * szTemp) // I think I'll change this
else else
szTemp[0] = '\0'; szTemp[0] = '\0';
strcat(szTemp, "/"); strcat(szTemp, "/");
SetLastError(theErr); SetLastError(theErr);
} }
@@ -347,7 +347,7 @@ void GetTempFileName(const char * lpTempFolderPath, const char * lpFileName, DWO
strcpy(szLFName, lpTempFolderPath); strcpy(szLFName, lpTempFolderPath);
strcat(szLFName, lpFileName); strcat(szLFName, lpFileName);
strcat(szLFName, tmp); strcat(szLFName, tmp);
if ((fHandle = CreateFile(szLFName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE) if ((fHandle = CreateFile(szLFName, GENERIC_READ, 0, NULL, OPEN_EXISTING, 0, 0)) == INVALID_HANDLE_VALUE)
// OK we found it! // OK we found it!
break; break;
@@ -364,16 +364,16 @@ BOOL DeleteFile(const char * lpFileName)
{ {
OSErr theErr; OSErr theErr;
FSRef theFileRef; FSRef theFileRef;
theErr = FSLocationFromFullPath(lpFileName, &theFileRef); theErr = FSLocationFromFullPath(lpFileName, &theFileRef);
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
return FALSE; return FALSE;
} }
theErr = FSDeleteObject(&theFileRef); theErr = FSDeleteObject(&theFileRef);
SetLastError(theErr); SetLastError(theErr);
return theErr == noErr; return theErr == noErr;
@@ -390,7 +390,7 @@ BOOL MoveFile(const char * lpFromFileName, const char * lpToFileName)
FSRef fromFileRef; FSRef fromFileRef;
FSRef toFileRef; FSRef toFileRef;
FSRef parentFolderRef; FSRef parentFolderRef;
// Get the path to the old file // Get the path to the old file
theErr = FSLocationFromFullPath(lpFromFileName, &fromFileRef); theErr = FSLocationFromFullPath(lpFromFileName, &fromFileRef);
if (theErr != noErr) if (theErr != noErr)
@@ -398,7 +398,7 @@ BOOL MoveFile(const char * lpFromFileName, const char * lpToFileName)
SetLastError(theErr); SetLastError(theErr);
return false; return false;
} }
// Get the path to the new folder for the file // Get the path to the new folder for the file
char folderName[strlen(lpToFileName)]; char folderName[strlen(lpToFileName)];
CFStringRef folderPathCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8); CFStringRef folderPathCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8);
@@ -409,7 +409,7 @@ BOOL MoveFile(const char * lpFromFileName, const char * lpToFileName)
CFRelease(fileURL); CFRelease(fileURL);
CFRelease(folderURL); CFRelease(folderURL);
CFRelease(folderPathCFString); CFRelease(folderPathCFString);
// Move the old file // Move the old file
theErr = FSMoveObject(&fromFileRef, &parentFolderRef, &toFileRef); theErr = FSMoveObject(&fromFileRef, &parentFolderRef, &toFileRef);
if (theErr != noErr) if (theErr != noErr)
@@ -417,19 +417,19 @@ BOOL MoveFile(const char * lpFromFileName, const char * lpToFileName)
SetLastError(theErr); SetLastError(theErr);
return false; return false;
} }
// Get a CFString for the new file name // Get a CFString for the new file name
CFStringRef newFileNameCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8); CFStringRef newFileNameCFString = CFStringCreateWithCString(NULL, lpToFileName, kCFStringEncodingUTF8);
fileURL = CFURLCreateWithFileSystemPath(NULL, newFileNameCFString, kCFURLPOSIXPathStyle, FALSE); fileURL = CFURLCreateWithFileSystemPath(NULL, newFileNameCFString, kCFURLPOSIXPathStyle, FALSE);
CFRelease(newFileNameCFString); CFRelease(newFileNameCFString);
newFileNameCFString = CFURLCopyLastPathComponent(fileURL); newFileNameCFString = CFURLCopyLastPathComponent(fileURL);
CFRelease(fileURL); CFRelease(fileURL);
// Convert CFString to Unicode and rename the file // Convert CFString to Unicode and rename the file
UniChar unicodeFileName[256]; UniChar unicodeFileName[256];
CFStringGetCharacters(newFileNameCFString, CFRangeMake(0, CFStringGetLength(newFileNameCFString)), CFStringGetCharacters(newFileNameCFString, CFRangeMake(0, CFStringGetLength(newFileNameCFString)),
unicodeFileName); unicodeFileName);
theErr = FSRenameUnicode(&toFileRef, CFStringGetLength(newFileNameCFString), unicodeFileName, theErr = FSRenameUnicode(&toFileRef, CFStringGetLength(newFileNameCFString), unicodeFileName,
kTextEncodingUnknown, NULL); kTextEncodingUnknown, NULL);
if (theErr != noErr) if (theErr != noErr)
{ {
@@ -437,9 +437,9 @@ BOOL MoveFile(const char * lpFromFileName, const char * lpToFileName)
CFRelease(newFileNameCFString); CFRelease(newFileNameCFString);
return false; return false;
} }
CFRelease(newFileNameCFString); CFRelease(newFileNameCFString);
SetLastError(theErr); SetLastError(theErr);
return true; return true;
} }
@@ -470,7 +470,7 @@ HANDLE CreateFile( const char *sFileName, /* file name */
char permission; char permission;
static OSType gCreator; static OSType gCreator;
static OSType gType; static OSType gType;
theErr = FSLocationFromFullPath(sFileName, &theFileRef); theErr = FSLocationFromFullPath(sFileName, &theFileRef);
if (theErr == fnfErr) if (theErr == fnfErr)
{ // Create the FSRef for the parent directory. { // Create the FSRef for the parent directory.
@@ -484,23 +484,23 @@ HANDLE CreateFile( const char *sFileName, /* file name */
CFRelease(fileURL); CFRelease(fileURL);
CFRelease(folderURL); CFRelease(folderURL);
CFRelease(folderPathCFString); CFRelease(folderPathCFString);
} }
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
if (ulCreation == OPEN_EXISTING || theErr != fnfErr) if (ulCreation == OPEN_EXISTING || theErr != fnfErr)
return INVALID_HANDLE_VALUE; return INVALID_HANDLE_VALUE;
} }
if (ulCreation != OPEN_EXISTING) if (ulCreation != OPEN_EXISTING)
{ /* We create the file */ { /* We create the file */
UniChar unicodeFileName[256]; UniChar unicodeFileName[256];
CFStringRef filePathCFString = CFStringCreateWithCString(NULL, sFileName, kCFStringEncodingUTF8); CFStringRef filePathCFString = CFStringCreateWithCString(NULL, sFileName, kCFStringEncodingUTF8);
CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, filePathCFString, kCFURLPOSIXPathStyle, FALSE); CFURLRef fileURL = CFURLCreateWithFileSystemPath(NULL, filePathCFString, kCFURLPOSIXPathStyle, FALSE);
CFStringRef fileNameCFString = CFURLCopyLastPathComponent(fileURL); CFStringRef fileNameCFString = CFURLCopyLastPathComponent(fileURL);
CFStringGetCharacters(fileNameCFString, CFRangeMake(0, CFStringGetLength(fileNameCFString)), CFStringGetCharacters(fileNameCFString, CFRangeMake(0, CFStringGetLength(fileNameCFString)),
unicodeFileName); unicodeFileName);
theErr = FSCreateCompat(&theParentRef, gCreator, gType, unicodeFileName, theErr = FSCreateCompat(&theParentRef, gCreator, gType, unicodeFileName,
CFStringGetLength(fileNameCFString), &theFileRef); CFStringGetLength(fileNameCFString), &theFileRef);
CFRelease(fileNameCFString); CFRelease(fileNameCFString);
CFRelease(filePathCFString); CFRelease(filePathCFString);
@@ -522,7 +522,7 @@ HANDLE CreateFile( const char *sFileName, /* file name */
permission = fsRdWrPerm; permission = fsRdWrPerm;
} }
theErr = FSOpenDFCompat(&theFileRef, permission, &fileRef); theErr = FSOpenDFCompat(&theFileRef, permission, &fileRef);
SetLastError(theErr); SetLastError(theErr);
if (theErr == noErr) if (theErr == noErr)
@@ -537,14 +537,14 @@ HANDLE CreateFile( const char *sFileName, /* file name */
BOOL CloseHandle( HANDLE hFile ) /* handle to object */ BOOL CloseHandle( HANDLE hFile ) /* handle to object */
{ {
OSErr theErr; OSErr theErr;
if ((hFile == NULL) || (hFile == INVALID_HANDLE_VALUE)) if ((hFile == NULL) || (hFile == INVALID_HANDLE_VALUE))
return FALSE; return FALSE;
theErr = FSCloseFork((short)(int)hFile); theErr = FSCloseFork((short)(int)hFile);
SetLastError(theErr); SetLastError(theErr);
return theErr != noErr; return theErr != noErr;
} }
@@ -562,19 +562,19 @@ DWORD GetFileSize( HANDLE hFile, /* handle to file */
SetLastError(theErr); SetLastError(theErr);
return -1u; return -1u;
} }
theErr = FSGetForkSize((short)(int)hFile, &fileLength); theErr = FSGetForkSize((short)(int)hFile, &fileLength);
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
return -1u; return -1u;
} }
if (ulOffSetHigh != NULL) if (ulOffSetHigh != NULL)
*ulOffSetHigh = fileLength >> 32; *ulOffSetHigh = fileLength >> 32;
SetLastError(theErr); SetLastError(theErr);
return fileLength; return fileLength;
} }
@@ -593,81 +593,81 @@ DWORD SetFilePointer( HANDLE hFile, /* handle to file */
if (ulMethod == FILE_CURRENT) if (ulMethod == FILE_CURRENT)
{ {
SInt64 bytesToMove; SInt64 bytesToMove;
if (pOffSetHigh != NULL) if (pOffSetHigh != NULL)
bytesToMove = ((SInt64)*pOffSetHigh << 32) + lOffSetLow; bytesToMove = ((SInt64)*pOffSetHigh << 32) + lOffSetLow;
else else
bytesToMove = lOffSetLow; bytesToMove = lOffSetLow;
SInt64 newPos; SInt64 newPos;
theErr = FSSetForkPosition((short)(int)hFile, fsFromMark, bytesToMove); theErr = FSSetForkPosition((short)(int)hFile, fsFromMark, bytesToMove);
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
return -1u; return -1u;
} }
theErr = FSGetForkPosition((short)(int)hFile, &newPos); theErr = FSGetForkPosition((short)(int)hFile, &newPos);
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
return -1u; return -1u;
} }
if (pOffSetHigh != NULL) if (pOffSetHigh != NULL)
*pOffSetHigh = newPos >> 32; *pOffSetHigh = newPos >> 32;
SetLastError(theErr); SetLastError(theErr);
return newPos; return newPos;
} }
else if (ulMethod == FILE_BEGIN) else if (ulMethod == FILE_BEGIN)
{ {
SInt64 bytesToMove; SInt64 bytesToMove;
if (pOffSetHigh != NULL) if (pOffSetHigh != NULL)
bytesToMove = ((SInt64)*pOffSetHigh << 32) + lOffSetLow; bytesToMove = ((SInt64)*pOffSetHigh << 32) + lOffSetLow;
else else
bytesToMove = lOffSetLow; bytesToMove = lOffSetLow;
theErr = FSSetForkPosition((short)(int)hFile, fsFromStart, bytesToMove); theErr = FSSetForkPosition((short)(int)hFile, fsFromStart, bytesToMove);
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
return -1u; return -1u;
} }
SetLastError(theErr); SetLastError(theErr);
return lOffSetLow; return lOffSetLow;
} }
else else
{ {
SInt64 bytesToMove; SInt64 bytesToMove;
if (pOffSetHigh != NULL) if (pOffSetHigh != NULL)
bytesToMove = ((SInt64)*pOffSetHigh << 32) + lOffSetLow; bytesToMove = ((SInt64)*pOffSetHigh << 32) + lOffSetLow;
else else
bytesToMove = lOffSetLow; bytesToMove = lOffSetLow;
SInt64 newPos; SInt64 newPos;
theErr = FSSetForkPosition((short)(int)hFile, fsFromLEOF, bytesToMove); theErr = FSSetForkPosition((short)(int)hFile, fsFromLEOF, bytesToMove);
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
return -1u; return -1u;
} }
theErr = FSGetForkPosition((short)(int)hFile, &newPos); theErr = FSGetForkPosition((short)(int)hFile, &newPos);
if (theErr != noErr) if (theErr != noErr)
{ {
SetLastError(theErr); SetLastError(theErr);
return -1u; return -1u;
} }
if (pOffSetHigh != NULL) if (pOffSetHigh != NULL)
*pOffSetHigh = newPos >> 32; *pOffSetHigh = newPos >> 32;
SetLastError(theErr); SetLastError(theErr);
return newPos; return newPos;
} }
@@ -679,11 +679,11 @@ DWORD SetFilePointer( HANDLE hFile, /* handle to file */
BOOL SetEndOfFile( HANDLE hFile ) /* handle to file */ BOOL SetEndOfFile( HANDLE hFile ) /* handle to file */
{ {
OSErr theErr; OSErr theErr;
theErr = FSSetForkSize((short)(int)hFile, fsAtMark, 0); theErr = FSSetForkSize((short)(int)hFile, fsAtMark, 0);
SetLastError(theErr); SetLastError(theErr);
return theErr == noErr; return theErr == noErr;
} }
@@ -701,13 +701,13 @@ BOOL ReadFile( HANDLE hFile, /* handle to file */
ByteCount nbCharsRead; ByteCount nbCharsRead;
OSErr theErr; OSErr theErr;
nbCharsRead = ulLen; nbCharsRead = ulLen;
theErr = FSReadFork((short)(int)hFile, fsAtMark, 0, nbCharsRead, pBuffer, &nbCharsRead); theErr = FSReadFork((short)(int)hFile, fsAtMark, 0, nbCharsRead, pBuffer, &nbCharsRead);
*ulRead = nbCharsRead; *ulRead = nbCharsRead;
SetLastError(theErr); SetLastError(theErr);
return theErr == noErr; return theErr == noErr;
} }
@@ -725,13 +725,13 @@ BOOL WriteFile( HANDLE hFile, /* handle to file */
ByteCount nbCharsToWrite; ByteCount nbCharsToWrite;
OSErr theErr; OSErr theErr;
nbCharsToWrite = ulLen; nbCharsToWrite = ulLen;
theErr = FSWriteFork((short)(int)hFile, fsAtMark, 0, nbCharsToWrite, pBuffer, &nbCharsToWrite); theErr = FSWriteFork((short)(int)hFile, fsAtMark, 0, nbCharsToWrite, pBuffer, &nbCharsToWrite);
*ulWritten = nbCharsToWrite; *ulWritten = nbCharsToWrite;
SetLastError(theErr); SetLastError(theErr);
return theErr == noErr; return theErr == noErr;
} }
@@ -744,15 +744,15 @@ BOOL IsBadReadPtr(const void * ptr, int size)
return FALSE; return FALSE;
} }
// Returns attributes of a file. Actually, it doesn't, it just checks if // Returns attributes of a file. Actually, it doesn't, it just checks if
// the file exists, since that's all StormLib uses it for // the file exists, since that's all StormLib uses it for
DWORD GetFileAttributes(const char * szFileName) DWORD GetFileAttributes(const char * szFileName)
{ {
FSRef theRef; FSRef theRef;
OSErr theErr; OSErr theErr;
theErr = FSLocationFromFullPath(szFileName, &theRef); theErr = FSLocationFromFullPath(szFileName, &theRef);
if (theErr != noErr) if (theErr != noErr)
return -1u; return -1u;
else else
@@ -760,4 +760,3 @@ DWORD GetFileAttributes(const char * szFileName)
} }
#endif #endif
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -57,8 +57,8 @@
For more information on these sources, see the manual. For more information on these sources, see the manual.
To get some idea how the block sorting algorithms in this file To get some idea how the block sorting algorithms in this file
work, read my paper work, read my paper
On the Performance of BWT Sorting Algorithms On the Performance of BWT Sorting Algorithms
in Proceedings of the IEEE Data Compression Conference 2000, in Proceedings of the IEEE Data Compression Conference 2000,
Snowbird, Utah, USA, 27-30 March 2000. The main sort in this Snowbird, Utah, USA, 27-30 March 2000. The main sort in this
@@ -74,11 +74,11 @@
/*---------------------------------------------*/ /*---------------------------------------------*/
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
__inline__ __inline__
void fallbackSimpleSort ( UInt32* fmap, void fallbackSimpleSort ( UInt32* fmap,
UInt32* eclass, UInt32* eclass,
Int32 lo, Int32 lo,
Int32 hi ) Int32 hi )
{ {
Int32 i, j, tmp; Int32 i, j, tmp;
@@ -137,9 +137,9 @@ void fallbackSimpleSort ( UInt32* fmap,
static static
void fallbackQSort3 ( UInt32* fmap, void fallbackQSort3 ( UInt32* fmap,
UInt32* eclass, UInt32* eclass,
Int32 loSt, Int32 loSt,
Int32 hiSt ) Int32 hiSt )
{ {
Int32 unLo, unHi, ltLo, gtHi, n, m; Int32 unLo, unHi, ltLo, gtHi, n, m;
@@ -164,9 +164,9 @@ void fallbackQSort3 ( UInt32* fmap,
} }
/* Random partitioning. Median of 3 sometimes fails to /* Random partitioning. Median of 3 sometimes fails to
avoid bad cases. Median of 9 seems to help but avoid bad cases. Median of 9 seems to help but
looks rather expensive. This too seems to work but looks rather expensive. This too seems to work but
is cheaper. Guidance for the magic constants is cheaper. Guidance for the magic constants
7621 and 32768 is taken from Sedgewick's algorithms 7621 and 32768 is taken from Sedgewick's algorithms
book, chapter 35. book, chapter 35.
*/ */
@@ -183,10 +183,10 @@ void fallbackQSort3 ( UInt32* fmap,
while (1) { while (1) {
if (unLo > unHi) break; if (unLo > unHi) break;
n = (Int32)eclass[fmap[unLo]] - (Int32)med; n = (Int32)eclass[fmap[unLo]] - (Int32)med;
if (n == 0) { if (n == 0) {
fswap(fmap[unLo], fmap[ltLo]); fswap(fmap[unLo], fmap[ltLo]);
ltLo++; unLo++; ltLo++; unLo++;
continue; continue;
}; };
if (n > 0) break; if (n > 0) break;
unLo++; unLo++;
@@ -194,10 +194,10 @@ void fallbackQSort3 ( UInt32* fmap,
while (1) { while (1) {
if (unLo > unHi) break; if (unLo > unHi) break;
n = (Int32)eclass[fmap[unHi]] - (Int32)med; n = (Int32)eclass[fmap[unHi]] - (Int32)med;
if (n == 0) { if (n == 0) {
fswap(fmap[unHi], fmap[gtHi]); fswap(fmap[unHi], fmap[gtHi]);
gtHi--; unHi--; gtHi--; unHi--;
continue; continue;
}; };
if (n < 0) break; if (n < 0) break;
unHi--; unHi--;
@@ -256,8 +256,8 @@ void fallbackQSort3 ( UInt32* fmap,
#define UNALIGNED_BH(zz) ((zz) & 0x01f) #define UNALIGNED_BH(zz) ((zz) & 0x01f)
static static
void fallbackSort ( UInt32* fmap, void fallbackSort ( UInt32* fmap,
UInt32* eclass, UInt32* eclass,
UInt32* bhtab, UInt32* bhtab,
Int32 nblock, Int32 nblock,
Int32 verb ) Int32 verb )
@@ -298,7 +298,7 @@ void fallbackSort ( UInt32* fmap,
--*/ --*/
/*-- set sentinel bits for block-end detection --*/ /*-- set sentinel bits for block-end detection --*/
for (i = 0; i < 32; i++) { for (i = 0; i < 32; i++) {
SET_BH(nblock + 2*i); SET_BH(nblock + 2*i);
CLEAR_BH(nblock + 2*i + 1); CLEAR_BH(nblock + 2*i + 1);
} }
@@ -307,7 +307,7 @@ void fallbackSort ( UInt32* fmap,
H = 1; H = 1;
while (1) { while (1) {
if (verb >= 4) if (verb >= 4)
VPrintf1 ( " depth %6d has ", H ); VPrintf1 ( " depth %6d has ", H );
j = 0; j = 0;
@@ -321,7 +321,7 @@ void fallbackSort ( UInt32* fmap,
r = -1; r = -1;
while (1) { while (1) {
/*-- find the next non-singleton bucket --*/ /*-- find the next non-singleton bucket --*/
k = r + 1; k = r + 1;
while (ISSET_BH(k) && UNALIGNED_BH(k)) k++; while (ISSET_BH(k) && UNALIGNED_BH(k)) k++;
if (ISSET_BH(k)) { if (ISSET_BH(k)) {
@@ -352,14 +352,14 @@ void fallbackSort ( UInt32* fmap,
} }
} }
if (verb >= 4) if (verb >= 4)
VPrintf1 ( "%6d unresolved strings\n", nNotDone ); VPrintf1 ( "%6d unresolved strings\n", nNotDone );
H *= 2; H *= 2;
if (H > nblock || nNotDone == 0) break; if (H > nblock || nNotDone == 0) break;
} }
/*-- /*--
Reconstruct the original block in Reconstruct the original block in
eclass8 [0 .. nblock-1], since the eclass8 [0 .. nblock-1], since the
previous phase destroyed it. previous phase destroyed it.
@@ -391,9 +391,9 @@ void fallbackSort ( UInt32* fmap,
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
__inline__ __inline__
Bool mainGtU ( UInt32 i1, Bool mainGtU ( UInt32 i1,
UInt32 i2, UInt32 i2,
UChar* block, UChar* block,
UInt16* quadrant, UInt16* quadrant,
UInt32 nblock, UInt32 nblock,
Int32* budget ) Int32* budget )
@@ -533,8 +533,8 @@ void mainSimpleSort ( UInt32* ptr,
UChar* block, UChar* block,
UInt16* quadrant, UInt16* quadrant,
Int32 nblock, Int32 nblock,
Int32 lo, Int32 lo,
Int32 hi, Int32 hi,
Int32 d, Int32 d,
Int32* budget ) Int32* budget )
{ {
@@ -558,8 +558,8 @@ void mainSimpleSort ( UInt32* ptr,
if (i > hi) break; if (i > hi) break;
v = ptr[i]; v = ptr[i];
j = i; j = i;
while ( mainGtU ( while ( mainGtU (
ptr[j-h]+d, v+d, block, quadrant, nblock, budget ptr[j-h]+d, v+d, block, quadrant, nblock, budget
) ) { ) ) {
ptr[j] = ptr[j-h]; ptr[j] = ptr[j-h];
j = j - h; j = j - h;
@@ -572,8 +572,8 @@ void mainSimpleSort ( UInt32* ptr,
if (i > hi) break; if (i > hi) break;
v = ptr[i]; v = ptr[i];
j = i; j = i;
while ( mainGtU ( while ( mainGtU (
ptr[j-h]+d, v+d, block, quadrant, nblock, budget ptr[j-h]+d, v+d, block, quadrant, nblock, budget
) ) { ) ) {
ptr[j] = ptr[j-h]; ptr[j] = ptr[j-h];
j = j - h; j = j - h;
@@ -586,8 +586,8 @@ void mainSimpleSort ( UInt32* ptr,
if (i > hi) break; if (i > hi) break;
v = ptr[i]; v = ptr[i];
j = i; j = i;
while ( mainGtU ( while ( mainGtU (
ptr[j-h]+d, v+d, block, quadrant, nblock, budget ptr[j-h]+d, v+d, block, quadrant, nblock, budget
) ) { ) ) {
ptr[j] = ptr[j-h]; ptr[j] = ptr[j-h];
j = j - h; j = j - h;
@@ -625,13 +625,13 @@ void mainSimpleSort ( UInt32* ptr,
} \ } \
} }
static static
__inline__ __inline__
UChar mmed3 ( UChar a, UChar b, UChar c ) UChar mmed3 ( UChar a, UChar b, UChar c )
{ {
UChar t; UChar t;
if (a > b) { t = a; a = b; b = t; }; if (a > b) { t = a; a = b; b = t; };
if (b > c) { if (b > c) {
b = c; b = c;
if (a > b) b = a; if (a > b) b = a;
} }
@@ -669,8 +669,8 @@ void mainQSort3 ( UInt32* ptr,
UChar* block, UChar* block,
UInt16* quadrant, UInt16* quadrant,
Int32 nblock, Int32 nblock,
Int32 loSt, Int32 loSt,
Int32 hiSt, Int32 hiSt,
Int32 dSt, Int32 dSt,
Int32* budget ) Int32* budget )
{ {
@@ -693,14 +693,14 @@ void mainQSort3 ( UInt32* ptr,
AssertH ( sp < MAIN_QSORT_STACK_SIZE, 1001 ); AssertH ( sp < MAIN_QSORT_STACK_SIZE, 1001 );
mpop ( lo, hi, d ); mpop ( lo, hi, d );
if (hi - lo < MAIN_QSORT_SMALL_THRESH || if (hi - lo < MAIN_QSORT_SMALL_THRESH ||
d > MAIN_QSORT_DEPTH_THRESH) { d > MAIN_QSORT_DEPTH_THRESH) {
mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget ); mainSimpleSort ( ptr, block, quadrant, nblock, lo, hi, d, budget );
if (*budget < 0) return; if (*budget < 0) return;
continue; continue;
} }
med = (Int32) med = (Int32)
mmed3 ( block[ptr[ lo ]+d], mmed3 ( block[ptr[ lo ]+d],
block[ptr[ hi ]+d], block[ptr[ hi ]+d],
block[ptr[ (lo+hi)>>1 ]+d] ); block[ptr[ (lo+hi)>>1 ]+d] );
@@ -712,9 +712,9 @@ void mainQSort3 ( UInt32* ptr,
while (True) { while (True) {
if (unLo > unHi) break; if (unLo > unHi) break;
n = ((Int32)block[ptr[unLo]+d]) - med; n = ((Int32)block[ptr[unLo]+d]) - med;
if (n == 0) { if (n == 0) {
mswap(ptr[unLo], ptr[ltLo]); mswap(ptr[unLo], ptr[ltLo]);
ltLo++; unLo++; continue; ltLo++; unLo++; continue;
}; };
if (n > 0) break; if (n > 0) break;
unLo++; unLo++;
@@ -722,9 +722,9 @@ void mainQSort3 ( UInt32* ptr,
while (True) { while (True) {
if (unLo > unHi) break; if (unLo > unHi) break;
n = ((Int32)block[ptr[unHi]+d]) - med; n = ((Int32)block[ptr[unHi]+d]) - med;
if (n == 0) { if (n == 0) {
mswap(ptr[unHi], ptr[gtHi]); mswap(ptr[unHi], ptr[gtHi]);
gtHi--; unHi--; continue; gtHi--; unHi--; continue;
}; };
if (n < 0) break; if (n < 0) break;
unHi--; unHi--;
@@ -795,9 +795,9 @@ void mainQSort3 ( UInt32* ptr,
#define CLEARMASK (~(SETMASK)) #define CLEARMASK (~(SETMASK))
static static
void mainSort ( UInt32* ptr, void mainSort ( UInt32* ptr,
UChar* block, UChar* block,
UInt16* quadrant, UInt16* quadrant,
UInt32* ftab, UInt32* ftab,
Int32 nblock, Int32 nblock,
Int32 verb, Int32 verb,
@@ -925,7 +925,7 @@ void mainSort ( UInt32* ptr,
/*-- /*--
Step 1: Step 1:
Complete the big bucket [ss] by quicksorting Complete the big bucket [ss] by quicksorting
any unsorted small buckets [ss, j], for j != ss. any unsorted small buckets [ss, j], for j != ss.
Hopefully previous pointer-scanning phases have already Hopefully previous pointer-scanning phases have already
completed many of the small buckets [ss, j], so completed many of the small buckets [ss, j], so
we don't have to sort them at all. we don't have to sort them at all.
@@ -941,10 +941,10 @@ void mainSort ( UInt32* ptr,
VPrintf4 ( " qsort [0x%x, 0x%x] " VPrintf4 ( " qsort [0x%x, 0x%x] "
"done %d this %d\n", "done %d this %d\n",
ss, j, numQSorted, hi - lo + 1 ); ss, j, numQSorted, hi - lo + 1 );
mainQSort3 ( mainQSort3 (
ptr, block, quadrant, nblock, ptr, block, quadrant, nblock,
lo, hi, BZ_N_RADIX, budget lo, hi, BZ_N_RADIX, budget
); );
numQSorted += (hi - lo + 1); numQSorted += (hi - lo + 1);
if (*budget < 0) return; if (*budget < 0) return;
} }
@@ -976,16 +976,16 @@ void mainSort ( UInt32* ptr,
for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) { for (j = (ftab[(ss+1) << 8] & CLEARMASK) - 1; j > copyEnd[ss]; j--) {
k = ptr[j]-1; if (k < 0) k += nblock; k = ptr[j]-1; if (k < 0) k += nblock;
c1 = block[k]; c1 = block[k];
if (!bigDone[c1]) if (!bigDone[c1])
ptr[ copyEnd[c1]-- ] = k; ptr[ copyEnd[c1]-- ] = k;
} }
} }
AssertH ( (copyStart[ss]-1 == copyEnd[ss]) AssertH ( (copyStart[ss]-1 == copyEnd[ss])
|| ||
/* Extremely rare case missing in bzip2-1.0.0 and 1.0.1. /* Extremely rare case missing in bzip2-1.0.0 and 1.0.1.
Necessity for this case is demonstrated by compressing Necessity for this case is demonstrated by compressing
a sequence of approximately 48.5 million of character a sequence of approximately 48.5 million of character
251; 1.0.0/1.0.1 will then die here. */ 251; 1.0.0/1.0.1 will then die here. */
(copyStart[ss] == 0 && copyEnd[ss] == nblock-1), (copyStart[ss] == 0 && copyEnd[ss] == nblock-1),
1007 ) 1007 )
@@ -1002,7 +1002,7 @@ void mainSort ( UInt32* ptr,
updating for the last bucket is pointless. updating for the last bucket is pointless.
The quadrant array provides a way to incrementally The quadrant array provides a way to incrementally
cache sort orderings, as they appear, so as to cache sort orderings, as they appear, so as to
make subsequent comparisons in fullGtU() complete make subsequent comparisons in fullGtU() complete
faster. For repetitive blocks this makes a big faster. For repetitive blocks this makes a big
difference (but not big enough to be able to avoid difference (but not big enough to be able to avoid
@@ -1012,9 +1012,9 @@ void mainSort ( UInt32* ptr,
for 0 <= i < nblock and 0 <= j <= nblock for 0 <= i < nblock and 0 <= j <= nblock
if block[i] != block[j], if block[i] != block[j],
then the relative values of quadrant[i] and then the relative values of quadrant[i] and
quadrant[j] are meaningless. quadrant[j] are meaningless.
else { else {
@@ -1077,7 +1077,7 @@ void mainSort ( UInt32* ptr,
*/ */
void BZ2_blockSort ( EState* s ) void BZ2_blockSort ( EState* s )
{ {
UInt32* ptr = s->ptr; UInt32* ptr = s->ptr;
UChar* block = s->block; UChar* block = s->block;
UInt32* ftab = s->ftab; UInt32* ftab = s->ftab;
Int32 nblock = s->nblock; Int32 nblock = s->nblock;
@@ -1101,8 +1101,8 @@ void BZ2_blockSort ( EState* s )
quadrant = (UInt16*)(&(block[i])); quadrant = (UInt16*)(&(block[i]));
/* (wfact-1) / 3 puts the default-factor-30 /* (wfact-1) / 3 puts the default-factor-30
transition point at very roughly the same place as transition point at very roughly the same place as
with v0.1 and v0.9.0. with v0.1 and v0.9.0.
Not that it particularly matters any more, since the Not that it particularly matters any more, since the
resulting compressed stream is now the same regardless resulting compressed stream is now the same regardless
of whether or not we use the main sort or fallback sort. of whether or not we use the main sort or fallback sort.
@@ -1113,14 +1113,14 @@ void BZ2_blockSort ( EState* s )
budget = budgetInit; budget = budgetInit;
mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget ); mainSort ( ptr, block, quadrant, ftab, nblock, verb, &budget );
if (verb >= 3) if (verb >= 3)
VPrintf3 ( " %d work, %d block, ratio %5.2f\n", VPrintf3 ( " %d work, %d block, ratio %5.2f\n",
budgetInit - budget, budgetInit - budget,
nblock, nblock,
(float)(budgetInit - budget) / (float)(budgetInit - budget) /
(float)(nblock==0 ? 1 : nblock) ); (float)(nblock==0 ? 1 : nblock) );
if (budget < 0) { if (budget < 0) {
if (verb >= 2) if (verb >= 2)
VPrintf0 ( " too repetitive; using fallback" VPrintf0 ( " too repetitive; using fallback"
" sorting algorithm\n" ); " sorting algorithm\n" );
fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb ); fallbackSort ( s->arr1, s->arr2, ftab, nblock, verb );
+153 -153
View File
@@ -16,16 +16,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -64,12 +64,12 @@
/*-- /*--
WARNING: WARNING:
This program and library (attempts to) compress data by This program and library (attempts to) compress data by
performing several non-trivial transformations on it. performing several non-trivial transformations on it.
Unless you are 100% familiar with *all* the algorithms Unless you are 100% familiar with *all* the algorithms
contained herein, and with the consequences of modifying them, contained herein, and with the consequences of modifying them,
you should NOT meddle with the compression or decompression you should NOT meddle with the compression or decompression
machinery. Incorrect changes can and very likely *will* machinery. Incorrect changes can and very likely *will*
lead to disasterous loss of data. lead to disasterous loss of data.
DISCLAIMER: DISCLAIMER:
@@ -84,8 +84,8 @@
of various special cases in the code which occur with very low of various special cases in the code which occur with very low
but non-zero probability make it impossible to rule out the but non-zero probability make it impossible to rule out the
possibility of bugs remaining in the program. DO NOT COMPRESS possibility of bugs remaining in the program. DO NOT COMPRESS
ANY DATA WITH THIS PROGRAM AND/OR LIBRARY UNLESS YOU ARE PREPARED ANY DATA WITH THIS PROGRAM AND/OR LIBRARY UNLESS YOU ARE PREPARED
TO ACCEPT THE POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL TO ACCEPT THE POSSIBILITY, HOWEVER SMALL, THAT THE DATA WILL
NOT BE RECOVERABLE. NOT BE RECOVERABLE.
That is not to say this program is inherently unreliable. That is not to say this program is inherently unreliable.
@@ -93,9 +93,9 @@
has been carefully constructed and extensively tested. has been carefully constructed and extensively tested.
PATENTS: PATENTS:
To the best of my knowledge, bzip2/libbzip2 does not use any To the best of my knowledge, bzip2/libbzip2 does not use any
patented algorithms. However, I do not have the resources patented algorithms. However, I do not have the resources
available to carry out a full patent search. Therefore I cannot available to carry out a full patent search. Therefore I cannot
give any guarantee of the above statement. give any guarantee of the above statement.
--*/ --*/
@@ -257,7 +257,7 @@ typedef int Int32;
typedef unsigned int UInt32; typedef unsigned int UInt32;
typedef short Int16; typedef short Int16;
typedef unsigned short UInt16; typedef unsigned short UInt16;
#define True ((Bool)1) #define True ((Bool)1)
#define False ((Bool)0) #define False ((Bool)0)
@@ -321,7 +321,7 @@ static void* myMalloc ( Int32 );
/*---------------------------------------------------*/ /*---------------------------------------------------*/
typedef typedef
struct { UChar b[8]; } struct { UChar b[8]; }
UInt64; UInt64;
@@ -364,7 +364,7 @@ Bool uInt64_isZero ( UInt64* n )
/* Divide *n by 10, and return the remainder. */ /* Divide *n by 10, and return the remainder. */
static static
Int32 uInt64_qrm10 ( UInt64* n ) Int32 uInt64_qrm10 ( UInt64* n )
{ {
UInt32 rem, tmp; UInt32 rem, tmp;
@@ -395,7 +395,7 @@ void uInt64_toAscii ( char* outbuf, UInt64* n )
nBuf++; nBuf++;
} while (!uInt64_isZero(&n_copy)); } while (!uInt64_isZero(&n_copy));
outbuf[nBuf] = 0; outbuf[nBuf] = 0;
for (i = 0; i < nBuf; i++) for (i = 0; i < nBuf; i++)
outbuf[i] = buf[nBuf-i-1]; outbuf[i] = buf[nBuf-i-1];
} }
@@ -405,7 +405,7 @@ void uInt64_toAscii ( char* outbuf, UInt64* n )
/*---------------------------------------------------*/ /*---------------------------------------------------*/
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
Bool myfeof ( FILE* f ) Bool myfeof ( FILE* f )
{ {
Int32 c = fgetc ( f ); Int32 c = fgetc ( f );
@@ -416,7 +416,7 @@ Bool myfeof ( FILE* f )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void compressStream ( FILE *stream, FILE *zStream ) void compressStream ( FILE *stream, FILE *zStream )
{ {
BZFILE* bzf = NULL; BZFILE* bzf = NULL;
@@ -432,8 +432,8 @@ void compressStream ( FILE *stream, FILE *zStream )
if (ferror(stream)) goto errhandler_io; if (ferror(stream)) goto errhandler_io;
if (ferror(zStream)) goto errhandler_io; if (ferror(zStream)) goto errhandler_io;
bzf = BZ2_bzWriteOpen ( &bzerr, zStream, bzf = BZ2_bzWriteOpen ( &bzerr, zStream,
blockSize100k, verbosity, workFactor ); blockSize100k, verbosity, workFactor );
if (bzerr != BZ_OK) goto errhandler; if (bzerr != BZ_OK) goto errhandler;
if (verbosity >= 2) fprintf ( stderr, "\n" ); if (verbosity >= 2) fprintf ( stderr, "\n" );
@@ -448,7 +448,7 @@ void compressStream ( FILE *stream, FILE *zStream )
} }
BZ2_bzWriteClose64 ( &bzerr, bzf, 0, BZ2_bzWriteClose64 ( &bzerr, bzf, 0,
&nbytes_in_lo32, &nbytes_in_hi32, &nbytes_in_lo32, &nbytes_in_hi32,
&nbytes_out_lo32, &nbytes_out_hi32 ); &nbytes_out_lo32, &nbytes_out_hi32 );
if (bzerr != BZ_OK) goto errhandler; if (bzerr != BZ_OK) goto errhandler;
@@ -468,34 +468,34 @@ void compressStream ( FILE *stream, FILE *zStream )
if (verbosity >= 1) { if (verbosity >= 1) {
if (nbytes_in_lo32 == 0 && nbytes_in_hi32 == 0) { if (nbytes_in_lo32 == 0 && nbytes_in_hi32 == 0) {
fprintf ( stderr, " no data compressed.\n"); fprintf ( stderr, " no data compressed.\n");
} else { } else {
Char buf_nin[32], buf_nout[32]; Char buf_nin[32], buf_nout[32];
UInt64 nbytes_in, nbytes_out; UInt64 nbytes_in, nbytes_out;
double nbytes_in_d, nbytes_out_d; double nbytes_in_d, nbytes_out_d;
uInt64_from_UInt32s ( &nbytes_in, uInt64_from_UInt32s ( &nbytes_in,
nbytes_in_lo32, nbytes_in_hi32 ); nbytes_in_lo32, nbytes_in_hi32 );
uInt64_from_UInt32s ( &nbytes_out, uInt64_from_UInt32s ( &nbytes_out,
nbytes_out_lo32, nbytes_out_hi32 ); nbytes_out_lo32, nbytes_out_hi32 );
nbytes_in_d = uInt64_to_double ( &nbytes_in ); nbytes_in_d = uInt64_to_double ( &nbytes_in );
nbytes_out_d = uInt64_to_double ( &nbytes_out ); nbytes_out_d = uInt64_to_double ( &nbytes_out );
uInt64_toAscii ( buf_nin, &nbytes_in ); uInt64_toAscii ( buf_nin, &nbytes_in );
uInt64_toAscii ( buf_nout, &nbytes_out ); uInt64_toAscii ( buf_nout, &nbytes_out );
fprintf ( stderr, "%6.3f:1, %6.3f bits/byte, " fprintf ( stderr, "%6.3f:1, %6.3f bits/byte, "
"%5.2f%% saved, %s in, %s out.\n", "%5.2f%% saved, %s in, %s out.\n",
nbytes_in_d / nbytes_out_d, nbytes_in_d / nbytes_out_d,
(8.0 * nbytes_out_d) / nbytes_in_d, (8.0 * nbytes_out_d) / nbytes_in_d,
100.0 * (1.0 - nbytes_out_d / nbytes_in_d), 100.0 * (1.0 - nbytes_out_d / nbytes_in_d),
buf_nin, buf_nin,
buf_nout buf_nout
); );
} }
} }
return; return;
errhandler: errhandler:
BZ2_bzWriteClose64 ( &bzerr_dummy, bzf, 1, BZ2_bzWriteClose64 ( &bzerr_dummy, bzf, 1,
&nbytes_in_lo32, &nbytes_in_hi32, &nbytes_in_lo32, &nbytes_in_hi32,
&nbytes_out_lo32, &nbytes_out_hi32 ); &nbytes_out_lo32, &nbytes_out_hi32 );
switch (bzerr) { switch (bzerr) {
@@ -517,7 +517,7 @@ void compressStream ( FILE *stream, FILE *zStream )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
Bool uncompressStream ( FILE *zStream, FILE *stream ) Bool uncompressStream ( FILE *zStream, FILE *stream )
{ {
BZFILE* bzf = NULL; BZFILE* bzf = NULL;
@@ -539,8 +539,8 @@ Bool uncompressStream ( FILE *zStream, FILE *stream )
while (True) { while (True) {
bzf = BZ2_bzReadOpen ( bzf = BZ2_bzReadOpen (
&bzerr, zStream, verbosity, &bzerr, zStream, verbosity,
(int)smallMode, unused, nUnused (int)smallMode, unused, nUnused
); );
if (bzf == NULL || bzerr != BZ_OK) goto errhandler; if (bzf == NULL || bzerr != BZ_OK) goto errhandler;
@@ -584,19 +584,19 @@ Bool uncompressStream ( FILE *zStream, FILE *stream )
if (verbosity >= 2) fprintf ( stderr, "\n " ); if (verbosity >= 2) fprintf ( stderr, "\n " );
return True; return True;
trycat: trycat:
if (forceOverwrite) { if (forceOverwrite) {
rewind(zStream); rewind(zStream);
while (True) { while (True) {
if (myfeof(zStream)) break; if (myfeof(zStream)) break;
nread = fread ( obuf, sizeof(UChar), 5000, zStream ); nread = fread ( obuf, sizeof(UChar), 5000, zStream );
if (ferror(zStream)) goto errhandler_io; if (ferror(zStream)) goto errhandler_io;
if (nread > 0) fwrite ( obuf, sizeof(UChar), nread, stream ); if (nread > 0) fwrite ( obuf, sizeof(UChar), nread, stream );
if (ferror(stream)) goto errhandler_io; if (ferror(stream)) goto errhandler_io;
} }
goto closeok; goto closeok;
} }
errhandler: errhandler:
BZ2_bzReadClose ( &bzerr_dummy, bzf ); BZ2_bzReadClose ( &bzerr_dummy, bzf );
switch (bzerr) { switch (bzerr) {
@@ -618,10 +618,10 @@ Bool uncompressStream ( FILE *zStream, FILE *stream )
return False; return False;
} else { } else {
if (noisy) if (noisy)
fprintf ( stderr, fprintf ( stderr,
"\n%s: %s: trailing garbage after EOF ignored\n", "\n%s: %s: trailing garbage after EOF ignored\n",
progName, inName ); progName, inName );
return True; return True;
} }
default: default:
panic ( "decompress:unexpected error" ); panic ( "decompress:unexpected error" );
@@ -633,7 +633,7 @@ Bool uncompressStream ( FILE *zStream, FILE *stream )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
Bool testStream ( FILE *zStream ) Bool testStream ( FILE *zStream )
{ {
BZFILE* bzf = NULL; BZFILE* bzf = NULL;
@@ -652,8 +652,8 @@ Bool testStream ( FILE *zStream )
while (True) { while (True) {
bzf = BZ2_bzReadOpen ( bzf = BZ2_bzReadOpen (
&bzerr, zStream, verbosity, &bzerr, zStream, verbosity,
(int)smallMode, unused, nUnused (int)smallMode, unused, nUnused
); );
if (bzf == NULL || bzerr != BZ_OK) goto errhandler; if (bzf == NULL || bzerr != BZ_OK) goto errhandler;
@@ -686,7 +686,7 @@ Bool testStream ( FILE *zStream )
errhandler: errhandler:
BZ2_bzReadClose ( &bzerr_dummy, bzf ); BZ2_bzReadClose ( &bzerr_dummy, bzf );
if (verbosity == 0) if (verbosity == 0)
fprintf ( stderr, "%s: %s: ", progName, inName ); fprintf ( stderr, "%s: %s: ", progName, inName );
switch (bzerr) { switch (bzerr) {
case BZ_CONFIG_ERROR: case BZ_CONFIG_ERROR:
@@ -707,14 +707,14 @@ Bool testStream ( FILE *zStream )
case BZ_DATA_ERROR_MAGIC: case BZ_DATA_ERROR_MAGIC:
if (zStream != stdin) fclose(zStream); if (zStream != stdin) fclose(zStream);
if (streamNo == 1) { if (streamNo == 1) {
fprintf ( stderr, fprintf ( stderr,
"bad magic number (file not created by bzip2)\n" ); "bad magic number (file not created by bzip2)\n" );
return False; return False;
} else { } else {
if (noisy) if (noisy)
fprintf ( stderr, fprintf ( stderr,
"trailing garbage after EOF ignored\n" ); "trailing garbage after EOF ignored\n" );
return True; return True;
} }
default: default:
panic ( "test:unexpected error" ); panic ( "test:unexpected error" );
@@ -738,7 +738,7 @@ void setExit ( Int32 v )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void cadvise ( void ) void cadvise ( void )
{ {
if (noisy) if (noisy)
@@ -753,26 +753,26 @@ void cadvise ( void )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void showFileNames ( void ) void showFileNames ( void )
{ {
if (noisy) if (noisy)
fprintf ( fprintf (
stderr, stderr,
"\tInput file = %s, output file = %s\n", "\tInput file = %s, output file = %s\n",
inName, outName inName, outName
); );
} }
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void cleanUpAndFail ( Int32 ec ) void cleanUpAndFail ( Int32 ec )
{ {
IntNative retVal; IntNative retVal;
struct MY_STAT statBuf; struct MY_STAT statBuf;
if ( srcMode == SM_F2F if ( srcMode == SM_F2F
&& opMode != OM_TEST && opMode != OM_TEST
&& deleteOutputOnInterrupt ) { && deleteOutputOnInterrupt ) {
@@ -784,7 +784,7 @@ void cleanUpAndFail ( Int32 ec )
retVal = MY_STAT ( inName, &statBuf ); retVal = MY_STAT ( inName, &statBuf );
if (retVal == 0) { if (retVal == 0) {
if (noisy) if (noisy)
fprintf ( stderr, fprintf ( stderr,
"%s: Deleting output file %s, if it exists.\n", "%s: Deleting output file %s, if it exists.\n",
progName, outName ); progName, outName );
if (outputHandleJustInCase != NULL) if (outputHandleJustInCase != NULL)
@@ -805,7 +805,7 @@ void cleanUpAndFail ( Int32 ec )
fprintf ( stderr, fprintf ( stderr,
"%s: `%s' may be incomplete.\n", "%s: `%s' may be incomplete.\n",
progName, outName ); progName, outName );
fprintf ( stderr, fprintf ( stderr,
"%s: I suggest doing an integrity test (bzip2 -tv)" "%s: I suggest doing an integrity test (bzip2 -tv)"
" of it.\n", " of it.\n",
progName ); progName );
@@ -813,7 +813,7 @@ void cleanUpAndFail ( Int32 ec )
} }
if (noisy && numFileNames > 0 && numFilesProcessed < numFileNames) { if (noisy && numFileNames > 0 && numFilesProcessed < numFileNames) {
fprintf ( stderr, fprintf ( stderr,
"%s: WARNING: some files have not been processed:\n" "%s: WARNING: some files have not been processed:\n"
"%s: %d specified on command line, %d not processed yet.\n\n", "%s: %d specified on command line, %d not processed yet.\n\n",
progName, progName, progName, progName,
@@ -825,7 +825,7 @@ void cleanUpAndFail ( Int32 ec )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void panic ( Char* s ) void panic ( Char* s )
{ {
fprintf ( stderr, fprintf ( stderr,
@@ -840,7 +840,7 @@ void panic ( Char* s )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void crcError ( void ) void crcError ( void )
{ {
fprintf ( stderr, fprintf ( stderr,
@@ -853,14 +853,14 @@ void crcError ( void )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void compressedStreamEOF ( void ) void compressedStreamEOF ( void )
{ {
if (noisy) { if (noisy) {
fprintf ( stderr, fprintf ( stderr,
"\n%s: Compressed file ends unexpectedly;\n\t" "\n%s: Compressed file ends unexpectedly;\n\t"
"perhaps it is corrupted? *Possible* reason follows.\n", "perhaps it is corrupted? *Possible* reason follows.\n",
progName ); progName );
perror ( progName ); perror ( progName );
showFileNames(); showFileNames();
cadvise(); cadvise();
@@ -870,7 +870,7 @@ void compressedStreamEOF ( void )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void ioError ( void ) void ioError ( void )
{ {
fprintf ( stderr, fprintf ( stderr,
@@ -884,7 +884,7 @@ void ioError ( void )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void mySignalCatcher ( IntNative n ) void mySignalCatcher ( IntNative n )
{ {
fprintf ( stderr, fprintf ( stderr,
@@ -895,11 +895,11 @@ void mySignalCatcher ( IntNative n )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void mySIGSEGVorSIGBUScatcher ( IntNative n ) void mySIGSEGVorSIGBUScatcher ( IntNative n )
{ {
if (opMode == OM_Z) if (opMode == OM_Z)
fprintf ( fprintf (
stderr, stderr,
"\n%s: Caught a SIGSEGV or SIGBUS whilst compressing.\n" "\n%s: Caught a SIGSEGV or SIGBUS whilst compressing.\n"
"\n" "\n"
@@ -920,7 +920,7 @@ void mySIGSEGVorSIGBUScatcher ( IntNative n )
"\n", "\n",
progName ); progName );
else else
fprintf ( fprintf (
stderr, stderr,
"\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing.\n" "\n%s: Caught a SIGSEGV or SIGBUS whilst decompressing.\n"
"\n" "\n"
@@ -951,7 +951,7 @@ void mySIGSEGVorSIGBUScatcher ( IntNative n )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void outOfMemory ( void ) void outOfMemory ( void )
{ {
fprintf ( stderr, fprintf ( stderr,
@@ -963,7 +963,7 @@ void outOfMemory ( void )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void configError ( void ) void configError ( void )
{ {
fprintf ( stderr, fprintf ( stderr,
@@ -983,11 +983,11 @@ void configError ( void )
/* All rather crufty. The main problem is that input files /* All rather crufty. The main problem is that input files
are stat()d multiple times before use. This should be are stat()d multiple times before use. This should be
cleaned up. cleaned up.
*/ */
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void pad ( Char *s ) void pad ( Char *s )
{ {
Int32 i; Int32 i;
@@ -998,8 +998,8 @@ void pad ( Char *s )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void copyFileName ( Char* to, Char* from ) void copyFileName ( Char* to, Char* from )
{ {
if ( strlen(from) > FILE_NAME_LEN-10 ) { if ( strlen(from) > FILE_NAME_LEN-10 ) {
fprintf ( fprintf (
@@ -1019,7 +1019,7 @@ void copyFileName ( Char* to, Char* from )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
Bool fileExists ( Char* name ) Bool fileExists ( Char* name )
{ {
FILE *tmp = fopen ( name, "rb" ); FILE *tmp = fopen ( name, "rb" );
@@ -1059,7 +1059,7 @@ FILE* fopen_output_safely ( Char* name, const char* mode )
/*-- /*--
if in doubt, return True if in doubt, return True
--*/ --*/
static static
Bool notAStandardFile ( Char* name ) Bool notAStandardFile ( Char* name )
{ {
IntNative i; IntNative i;
@@ -1076,9 +1076,9 @@ Bool notAStandardFile ( Char* name )
/*-- /*--
rac 11/21/98 see if file has hard links to it rac 11/21/98 see if file has hard links to it
--*/ --*/
static static
Int32 countHardLinks ( Char* name ) Int32 countHardLinks ( Char* name )
{ {
IntNative i; IntNative i;
struct MY_STAT statBuf; struct MY_STAT statBuf;
@@ -1109,14 +1109,14 @@ Int32 countHardLinks ( Char* name )
It sounds pretty fragile to me. Whether this carries across It sounds pretty fragile to me. Whether this carries across
robustly to arbitrary Unix-like platforms (or even works robustly robustly to arbitrary Unix-like platforms (or even works robustly
on this one, RedHat 7.2) is unknown to me. Nevertheless ... on this one, RedHat 7.2) is unknown to me. Nevertheless ...
*/ */
#if BZ_UNIX #if BZ_UNIX
static static
struct MY_STAT fileMetaInfo; struct MY_STAT fileMetaInfo;
#endif #endif
static static
void saveInputFileMetaInfo ( Char *srcName ) void saveInputFileMetaInfo ( Char *srcName )
{ {
# if BZ_UNIX # if BZ_UNIX
@@ -1128,7 +1128,7 @@ void saveInputFileMetaInfo ( Char *srcName )
} }
static static
void applySavedMetaInfoToOutputFile ( Char *dstName ) void applySavedMetaInfoToOutputFile ( Char *dstName )
{ {
# if BZ_UNIX # if BZ_UNIX
@@ -1153,7 +1153,7 @@ void applySavedMetaInfoToOutputFile ( Char *dstName )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
Bool containsDubiousChars ( Char* name ) Bool containsDubiousChars ( Char* name )
{ {
# if BZ_UNIX # if BZ_UNIX
@@ -1162,7 +1162,7 @@ Bool containsDubiousChars ( Char* name )
*/ */
return False; return False;
# else /* ! BZ_UNIX */ # else /* ! BZ_UNIX */
/* On non-unix (Win* platforms), wildcard characters are not allowed in /* On non-unix (Win* platforms), wildcard characters are not allowed in
* filenames. * filenames.
*/ */
for (; *name != '\0'; name++) for (; *name != '\0'; name++)
@@ -1175,12 +1175,12 @@ Bool containsDubiousChars ( Char* name )
/*---------------------------------------------*/ /*---------------------------------------------*/
#define BZ_N_SUFFIX_PAIRS 4 #define BZ_N_SUFFIX_PAIRS 4
Char* zSuffix[BZ_N_SUFFIX_PAIRS] Char* zSuffix[BZ_N_SUFFIX_PAIRS]
= { ".bz2", ".bz", ".tbz2", ".tbz" }; = { ".bz2", ".bz", ".tbz2", ".tbz" };
Char* unzSuffix[BZ_N_SUFFIX_PAIRS] Char* unzSuffix[BZ_N_SUFFIX_PAIRS]
= { "", "", ".tar", ".tar" }; = { "", "", ".tar", ".tar" };
static static
Bool hasSuffix ( Char* s, Char* suffix ) Bool hasSuffix ( Char* s, Char* suffix )
{ {
Int32 ns = strlen(s); Int32 ns = strlen(s);
@@ -1190,8 +1190,8 @@ Bool hasSuffix ( Char* s, Char* suffix )
return False; return False;
} }
static static
Bool mapSuffix ( Char* name, Bool mapSuffix ( Char* name,
Char* oldSuffix, Char* newSuffix ) Char* oldSuffix, Char* newSuffix )
{ {
if (!hasSuffix(name,oldSuffix)) return False; if (!hasSuffix(name,oldSuffix)) return False;
@@ -1202,7 +1202,7 @@ Bool mapSuffix ( Char* name,
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void compress ( Char *name ) void compress ( Char *name )
{ {
FILE *inStr; FILE *inStr;
@@ -1216,18 +1216,18 @@ void compress ( Char *name )
panic ( "compress: bad modes\n" ); panic ( "compress: bad modes\n" );
switch (srcMode) { switch (srcMode) {
case SM_I2O: case SM_I2O:
copyFileName ( inName, "(stdin)" ); copyFileName ( inName, "(stdin)" );
copyFileName ( outName, "(stdout)" ); copyFileName ( outName, "(stdout)" );
break; break;
case SM_F2F: case SM_F2F:
copyFileName ( inName, name ); copyFileName ( inName, name );
copyFileName ( outName, name ); copyFileName ( outName, name );
strcat ( outName, ".bz2" ); strcat ( outName, ".bz2" );
break; break;
case SM_F2O: case SM_F2O:
copyFileName ( inName, name ); copyFileName ( inName, name );
copyFileName ( outName, "(stdout)" ); copyFileName ( outName, "(stdout)" );
break; break;
} }
@@ -1247,7 +1247,7 @@ void compress ( Char *name )
for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) { for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) {
if (hasSuffix(inName, zSuffix[i])) { if (hasSuffix(inName, zSuffix[i])) {
if (noisy) if (noisy)
fprintf ( stderr, fprintf ( stderr,
"%s: Input file %s already has %s suffix.\n", "%s: Input file %s already has %s suffix.\n",
progName, inName, zSuffix[i] ); progName, inName, zSuffix[i] );
setExit(1); setExit(1);
@@ -1273,12 +1273,12 @@ void compress ( Char *name )
} }
if ( srcMode == SM_F2F && fileExists ( outName ) ) { if ( srcMode == SM_F2F && fileExists ( outName ) ) {
if (forceOverwrite) { if (forceOverwrite) {
remove(outName); remove(outName);
} else { } else {
fprintf ( stderr, "%s: Output file %s already exists.\n", fprintf ( stderr, "%s: Output file %s already exists.\n",
progName, outName ); progName, outName );
setExit(1); setExit(1);
return; return;
} }
} }
if ( srcMode == SM_F2F && !forceOverwrite && if ( srcMode == SM_F2F && !forceOverwrite &&
@@ -1383,7 +1383,7 @@ void compress ( Char *name )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void uncompress ( Char *name ) void uncompress ( Char *name )
{ {
FILE *inStr; FILE *inStr;
@@ -1400,22 +1400,22 @@ void uncompress ( Char *name )
cantGuess = False; cantGuess = False;
switch (srcMode) { switch (srcMode) {
case SM_I2O: case SM_I2O:
copyFileName ( inName, "(stdin)" ); copyFileName ( inName, "(stdin)" );
copyFileName ( outName, "(stdout)" ); copyFileName ( outName, "(stdout)" );
break; break;
case SM_F2F: case SM_F2F:
copyFileName ( inName, name ); copyFileName ( inName, name );
copyFileName ( outName, name ); copyFileName ( outName, name );
for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++) for (i = 0; i < BZ_N_SUFFIX_PAIRS; i++)
if (mapSuffix(outName,zSuffix[i],unzSuffix[i])) if (mapSuffix(outName,zSuffix[i],unzSuffix[i]))
goto zzz; goto zzz;
cantGuess = True; cantGuess = True;
strcat ( outName, ".out" ); strcat ( outName, ".out" );
break; break;
case SM_F2O: case SM_F2O:
copyFileName ( inName, name ); copyFileName ( inName, name );
copyFileName ( outName, "(stdout)" ); copyFileName ( outName, "(stdout)" );
break; break;
} }
@@ -1452,14 +1452,14 @@ void uncompress ( Char *name )
} }
if ( /* srcMode == SM_F2F implied && */ cantGuess ) { if ( /* srcMode == SM_F2F implied && */ cantGuess ) {
if (noisy) if (noisy)
fprintf ( stderr, fprintf ( stderr,
"%s: Can't guess original name for %s -- using %s\n", "%s: Can't guess original name for %s -- using %s\n",
progName, inName, outName ); progName, inName, outName );
/* just a warning, no return */ /* just a warning, no return */
} }
if ( srcMode == SM_F2F && fileExists ( outName ) ) { if ( srcMode == SM_F2F && fileExists ( outName ) ) {
if (forceOverwrite) { if (forceOverwrite) {
remove(outName); remove(outName);
} else { } else {
fprintf ( stderr, "%s: Output file %s already exists.\n", fprintf ( stderr, "%s: Output file %s already exists.\n",
progName, outName ); progName, outName );
@@ -1581,7 +1581,7 @@ void uncompress ( Char *name )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void testf ( Char *name ) void testf ( Char *name )
{ {
FILE *inStr; FILE *inStr;
@@ -1670,7 +1670,7 @@ void testf ( Char *name )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void license ( void ) void license ( void )
{ {
fprintf ( stderr, fprintf ( stderr,
@@ -1695,7 +1695,7 @@ void license ( void )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void usage ( Char *fullProgName ) void usage ( Char *fullProgName )
{ {
fprintf ( fprintf (
@@ -1739,11 +1739,11 @@ void usage ( Char *fullProgName )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void redundant ( Char* flag ) void redundant ( Char* flag )
{ {
fprintf ( fprintf (
stderr, stderr,
"%s: %s is redundant in versions 0.9.5 and above\n", "%s: %s is redundant in versions 0.9.5 and above\n",
progName, flag ); progName, flag );
} }
@@ -1755,8 +1755,8 @@ void redundant ( Char* flag )
implement a linked list of command-line arguments, implement a linked list of command-line arguments,
into which main() copies argv[1 .. argc-1]. into which main() copies argv[1 .. argc-1].
The purpose of this exercise is to facilitate The purpose of this exercise is to facilitate
the expansion of wildcard characters * and ? in the expansion of wildcard characters * and ? in
filenames for OSs which don't know how to do it filenames for OSs which don't know how to do it
themselves, like MSDOS, Windows 95 and NT. themselves, like MSDOS, Windows 95 and NT.
@@ -1773,7 +1773,7 @@ typedef
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void *myMalloc ( Int32 n ) void *myMalloc ( Int32 n )
{ {
void* p; void* p;
@@ -1785,7 +1785,7 @@ void *myMalloc ( Int32 n )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
Cell *mkCell ( void ) Cell *mkCell ( void )
{ {
Cell *c; Cell *c;
@@ -1798,7 +1798,7 @@ Cell *mkCell ( void )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
Cell *snocString ( Cell *root, Char *name ) Cell *snocString ( Cell *root, Char *name )
{ {
if (root == NULL) { if (root == NULL) {
@@ -1816,8 +1816,8 @@ Cell *snocString ( Cell *root, Char *name )
/*---------------------------------------------*/ /*---------------------------------------------*/
static static
void addFlagsFromEnvVar ( Cell** argList, Char* varName ) void addFlagsFromEnvVar ( Cell** argList, Char* varName )
{ {
Int32 i, j, k; Int32 i, j, k;
Char *envbase, *p; Char *envbase, *p;
@@ -1894,7 +1894,7 @@ IntNative main ( IntNative argc, Char *argv[] )
if (*tmp == PATH_SEP) progName = tmp + 1; if (*tmp == PATH_SEP) progName = tmp + 1;
/*-- Copy flags from env var BZIP2, and /*-- Copy flags from env var BZIP2, and
expand filename wildcards in arg list. expand filename wildcards in arg list.
--*/ --*/
argList = NULL; argList = NULL;
@@ -1977,7 +1977,7 @@ IntNative main ( IntNative argc, Char *argv[] )
} }
} }
} }
/*-- And again ... --*/ /*-- And again ... --*/
for (aa = argList; aa != NULL; aa = aa->link) { for (aa = argList; aa != NULL; aa = aa->link) {
if (ISFLAG("--")) break; if (ISFLAG("--")) break;
@@ -1991,7 +1991,7 @@ IntNative main ( IntNative argc, Char *argv[] )
if (ISFLAG("--quiet")) noisy = False; else if (ISFLAG("--quiet")) noisy = False; else
if (ISFLAG("--version")) license(); else if (ISFLAG("--version")) license(); else
if (ISFLAG("--license")) license(); else if (ISFLAG("--license")) license(); else
if (ISFLAG("--exponential")) workFactor = 1; else if (ISFLAG("--exponential")) workFactor = 1; else
if (ISFLAG("--repetitive-best")) redundant(aa->name); else if (ISFLAG("--repetitive-best")) redundant(aa->name); else
if (ISFLAG("--repetitive-fast")) redundant(aa->name); else if (ISFLAG("--repetitive-fast")) redundant(aa->name); else
if (ISFLAG("--fast")) blockSize100k = 1; else if (ISFLAG("--fast")) blockSize100k = 1; else
@@ -2007,7 +2007,7 @@ IntNative main ( IntNative argc, Char *argv[] )
} }
if (verbosity > 4) verbosity = 4; if (verbosity > 4) verbosity = 4;
if (opMode == OM_Z && smallMode && blockSize100k > 2) if (opMode == OM_Z && smallMode && blockSize100k > 2)
blockSize100k = 2; blockSize100k = 2;
if (opMode == OM_TEST && srcMode == SM_F2O) { if (opMode == OM_TEST && srcMode == SM_F2O) {
@@ -2041,7 +2041,7 @@ IntNative main ( IntNative argc, Char *argv[] )
compress ( aa->name ); compress ( aa->name );
} }
} }
} }
else else
if (opMode == OM_UNZ) { if (opMode == OM_UNZ) {
@@ -2055,13 +2055,13 @@ IntNative main ( IntNative argc, Char *argv[] )
if (aa->name[0] == '-' && decode) continue; if (aa->name[0] == '-' && decode) continue;
numFilesProcessed++; numFilesProcessed++;
uncompress ( aa->name ); uncompress ( aa->name );
} }
} }
if (unzFailsExist) { if (unzFailsExist) {
setExit(2); setExit(2);
exit(exitValue); exit(exitValue);
} }
} }
else { else {
testFailsExist = False; testFailsExist = False;
@@ -2070,11 +2070,11 @@ IntNative main ( IntNative argc, Char *argv[] )
} else { } else {
decode = True; decode = True;
for (aa = argList; aa != NULL; aa = aa->link) { for (aa = argList; aa != NULL; aa = aa->link) {
if (ISFLAG("--")) { decode = False; continue; } if (ISFLAG("--")) { decode = False; continue; }
if (aa->name[0] == '-' && decode) continue; if (aa->name[0] == '-' && decode) continue;
numFilesProcessed++; numFilesProcessed++;
testf ( aa->name ); testf ( aa->name );
} }
} }
if (testFailsExist && noisy) { if (testFailsExist && noisy) {
fprintf ( stderr, fprintf ( stderr,
@@ -2087,7 +2087,7 @@ IntNative main ( IntNative argc, Char *argv[] )
} }
} }
/* Free the argument list memory to mollify leak detectors /* Free the argument list memory to mollify leak detectors
(eg) Purify, Checker. Serves no other useful purpose. (eg) Purify, Checker. Serves no other useful purpose.
*/ */
aa = argList; aa = argList;
@@ -5,7 +5,7 @@
/*-----------------------------------------------------------*/ /*-----------------------------------------------------------*/
/*-- /*--
This program is bzip2recover, a program to attempt data This program is bzip2recover, a program to attempt data
salvage from damaged files created by the accompanying salvage from damaged files created by the accompanying
bzip2-1.0.3 program. bzip2-1.0.3 program.
@@ -18,16 +18,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -107,7 +107,7 @@ MaybeUInt64 bytesIn = 0;
#define BZ_HDR_Z 0x5a /* 'Z' */ #define BZ_HDR_Z 0x5a /* 'Z' */
#define BZ_HDR_h 0x68 /* 'h' */ #define BZ_HDR_h 0x68 /* 'h' */
#define BZ_HDR_0 0x30 /* '0' */ #define BZ_HDR_0 0x30 /* '0' */
/*---------------------------------------------------*/ /*---------------------------------------------------*/
/*--- I/O errors ---*/ /*--- I/O errors ---*/
@@ -160,7 +160,7 @@ void tooManyBlocks ( Int32 max_handled_blocks )
fprintf ( stderr, fprintf ( stderr,
"%s: and cannot be handled. To fix, increase\n", "%s: and cannot be handled. To fix, increase\n",
progName ); progName );
fprintf ( stderr, fprintf ( stderr,
"%s: BZ_MAX_HANDLED_BLOCKS in bzip2recover.c, and recompile.\n", "%s: BZ_MAX_HANDLED_BLOCKS in bzip2recover.c, and recompile.\n",
progName ); progName );
exit ( 1 ); exit ( 1 );
@@ -344,7 +344,7 @@ Int32 main ( Int32 argc, Char** argv )
strcpy ( progName, argv[0] ); strcpy ( progName, argv[0] );
inFileName[0] = outFileName[0] = 0; inFileName[0] = outFileName[0] = 0;
fprintf ( stderr, fprintf ( stderr,
"bzip2recover 1.0.3: extracts blocks from damaged .bz2 files.\n" ); "bzip2recover 1.0.3: extracts blocks from damaged .bz2 files.\n" );
if (argc != 2) { if (argc != 2) {
@@ -352,18 +352,18 @@ Int32 main ( Int32 argc, Char** argv )
progName, progName ); progName, progName );
switch (sizeof(MaybeUInt64)) { switch (sizeof(MaybeUInt64)) {
case 8: case 8:
fprintf(stderr, fprintf(stderr,
"\trestrictions on size of recovered file: None\n"); "\trestrictions on size of recovered file: None\n");
break; break;
case 4: case 4:
fprintf(stderr, fprintf(stderr,
"\trestrictions on size of recovered file: 512 MB\n"); "\trestrictions on size of recovered file: 512 MB\n");
fprintf(stderr, fprintf(stderr,
"\tto circumvent, recompile with MaybeUInt64 as an\n" "\tto circumvent, recompile with MaybeUInt64 as an\n"
"\tunsigned 64-bit int.\n"); "\tunsigned 64-bit int.\n");
break; break;
default: default:
fprintf(stderr, fprintf(stderr,
"\tsizeof(MaybeUInt64) is not 4 or 8 -- " "\tsizeof(MaybeUInt64) is not 4 or 8 -- "
"configuration error.\n"); "configuration error.\n");
break; break;
@@ -372,7 +372,7 @@ Int32 main ( Int32 argc, Char** argv )
} }
if (strlen(argv[1]) >= BZ_MAX_FILENAME-20) { if (strlen(argv[1]) >= BZ_MAX_FILENAME-20) {
fprintf ( stderr, fprintf ( stderr,
"%s: supplied filename is suspiciously (>= %d chars) long. Bye!\n", "%s: supplied filename is suspiciously (>= %d chars) long. Bye!\n",
progName, (int)strlen(argv[1]) ); progName, (int)strlen(argv[1]) );
exit(1); exit(1);
@@ -404,7 +404,7 @@ Int32 main ( Int32 argc, Char** argv )
(bitsRead - bStart[currBlock]) >= 40) { (bitsRead - bStart[currBlock]) >= 40) {
bEnd[currBlock] = bitsRead-1; bEnd[currBlock] = bitsRead-1;
if (currBlock > 0) if (currBlock > 0)
fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT
" to " MaybeUInt64_FMT " (incomplete)\n", " to " MaybeUInt64_FMT " (incomplete)\n",
currBlock, bStart[currBlock], bEnd[currBlock] ); currBlock, bStart[currBlock], bEnd[currBlock] );
} else } else
@@ -413,10 +413,10 @@ Int32 main ( Int32 argc, Char** argv )
} }
buffHi = (buffHi << 1) | (buffLo >> 31); buffHi = (buffHi << 1) | (buffLo >> 31);
buffLo = (buffLo << 1) | (b & 1); buffLo = (buffLo << 1) | (b & 1);
if ( ( (buffHi & 0x0000ffff) == BLOCK_HEADER_HI if ( ( (buffHi & 0x0000ffff) == BLOCK_HEADER_HI
&& buffLo == BLOCK_HEADER_LO) && buffLo == BLOCK_HEADER_LO)
|| ||
( (buffHi & 0x0000ffff) == BLOCK_ENDMARK_HI ( (buffHi & 0x0000ffff) == BLOCK_ENDMARK_HI
&& buffLo == BLOCK_ENDMARK_LO) && buffLo == BLOCK_ENDMARK_LO)
) { ) {
if (bitsRead > 49) { if (bitsRead > 49) {
@@ -425,8 +425,8 @@ Int32 main ( Int32 argc, Char** argv )
bEnd[currBlock] = 0; bEnd[currBlock] = 0;
} }
if (currBlock > 0 && if (currBlock > 0 &&
(bEnd[currBlock] - bStart[currBlock]) >= 130) { (bEnd[currBlock] - bStart[currBlock]) >= 130) {
fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT fprintf ( stderr, " block %d runs from " MaybeUInt64_FMT
" to " MaybeUInt64_FMT "\n", " to " MaybeUInt64_FMT "\n",
rbCtr+1, bStart[currBlock], bEnd[currBlock] ); rbCtr+1, bStart[currBlock], bEnd[currBlock] );
rbStart[rbCtr] = bStart[currBlock]; rbStart[rbCtr] = bStart[currBlock];
@@ -472,7 +472,7 @@ Int32 main ( Int32 argc, Char** argv )
if (b == 2) break; if (b == 2) break;
buffHi = (buffHi << 1) | (buffLo >> 31); buffHi = (buffHi << 1) | (buffLo >> 31);
buffLo = (buffLo << 1) | (b & 1); buffLo = (buffLo << 1) | (b & 1);
if (bitsRead == 47+rbStart[wrBlock]) if (bitsRead == 47+rbStart[wrBlock])
blockCRC = (buffHi << 16) | (buffLo >> 16); blockCRC = (buffHi << 16) | (buffLo >> 16);
if (outFile != NULL && bitsRead >= rbStart[wrBlock] if (outFile != NULL && bitsRead >= rbStart[wrBlock]
@@ -494,11 +494,11 @@ Int32 main ( Int32 argc, Char** argv )
wrBlock++; wrBlock++;
} else } else
if (bitsRead == rbStart[wrBlock]) { if (bitsRead == rbStart[wrBlock]) {
/* Create the output file name, correctly handling leading paths. /* Create the output file name, correctly handling leading paths.
(31.10.2001 by Sergey E. Kusikov) */ (31.10.2001 by Sergey E. Kusikov) */
Char* split; Char* split;
Int32 ofs, k; Int32 ofs, k;
for (k = 0; k < BZ_MAX_FILENAME; k++) for (k = 0; k < BZ_MAX_FILENAME; k++)
outFileName[k] = 0; outFileName[k] = 0;
strcpy (outFileName, inFileName); strcpy (outFileName, inFileName);
split = strrchr (outFileName, BZ_SPLIT_SYM); split = strrchr (outFileName, BZ_SPLIT_SYM);
@@ -506,8 +506,8 @@ Int32 main ( Int32 argc, Char** argv )
split = outFileName; split = outFileName;
} else { } else {
++split; ++split;
} }
/* Now split points to the start of the basename. */ /* Now split points to the start of the basename. */
ofs = split - outFileName; ofs = split - outFileName;
sprintf (split, "rec%5d", wrBlock+1); sprintf (split, "rec%5d", wrBlock+1);
for (p = split; *p != 0; p++) if (*p == ' ') *p = '0'; for (p = split; *p != 0; p++) if (*p == ' ') *p = '0';
@@ -525,9 +525,9 @@ Int32 main ( Int32 argc, Char** argv )
exit(1); exit(1);
} }
bsWr = bsOpenWriteStream ( outFile ); bsWr = bsOpenWriteStream ( outFile );
bsPutUChar ( bsWr, BZ_HDR_B ); bsPutUChar ( bsWr, BZ_HDR_B );
bsPutUChar ( bsWr, BZ_HDR_Z ); bsPutUChar ( bsWr, BZ_HDR_Z );
bsPutUChar ( bsWr, BZ_HDR_h ); bsPutUChar ( bsWr, BZ_HDR_h );
bsPutUChar ( bsWr, BZ_HDR_0 + 9 ); bsPutUChar ( bsWr, BZ_HDR_0 + 9 );
bsPutUChar ( bsWr, 0x31 ); bsPutUChar ( bsWr, 0x41 ); bsPutUChar ( bsWr, 0x31 ); bsPutUChar ( bsWr, 0x41 );
bsPutUChar ( bsWr, 0x59 ); bsPutUChar ( bsWr, 0x26 ); bsPutUChar ( bsWr, 0x59 ); bsPutUChar ( bsWr, 0x26 );
+117 -117
View File
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -86,7 +86,7 @@
#ifndef BZ_NO_STDIO #ifndef BZ_NO_STDIO
void BZ2_bz__AssertH__fail ( int errcode ) void BZ2_bz__AssertH__fail ( int errcode )
{ {
fprintf(stderr, fprintf(stderr,
"\n\nbzip2/libbzip2: internal error number %d.\n" "\n\nbzip2/libbzip2: internal error number %d.\n"
"This is a bug in bzip2/libbzip2, %s.\n" "This is a bug in bzip2/libbzip2, %s.\n"
"Please report it to me at: [email protected]. If this happened\n" "Please report it to me at: [email protected]. If this happened\n"
@@ -191,8 +191,8 @@ Bool isempty_RL ( EState* s )
/*---------------------------------------------------*/ /*---------------------------------------------------*/
int BZ_API(BZ2_bzCompressInit) int BZ_API(BZ2_bzCompressInit)
( bz_stream* strm, ( bz_stream* strm,
int blockSize100k, int blockSize100k,
int verbosity, int verbosity,
int workFactor ) int workFactor )
@@ -202,7 +202,7 @@ int BZ_API(BZ2_bzCompressInit)
if (!bz_config_ok()) return BZ_CONFIG_ERROR; if (!bz_config_ok()) return BZ_CONFIG_ERROR;
if (strm == NULL || if (strm == NULL ||
blockSize100k < 1 || blockSize100k > 9 || blockSize100k < 1 || blockSize100k > 9 ||
workFactor < 0 || workFactor > 250) workFactor < 0 || workFactor > 250)
return BZ_PARAM_ERROR; return BZ_PARAM_ERROR;
@@ -345,7 +345,7 @@ Bool copy_input_until_stop ( EState* s )
/*-- no input? --*/ /*-- no input? --*/
if (s->strm->avail_in == 0) break; if (s->strm->avail_in == 0) break;
progress_in = True; progress_in = True;
ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) );
s->strm->next_in++; s->strm->next_in++;
s->strm->avail_in--; s->strm->avail_in--;
s->strm->total_in_lo32++; s->strm->total_in_lo32++;
@@ -363,7 +363,7 @@ Bool copy_input_until_stop ( EState* s )
/*-- flush/finish end? --*/ /*-- flush/finish end? --*/
if (s->avail_in_expect == 0) break; if (s->avail_in_expect == 0) break;
progress_in = True; progress_in = True;
ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) ); ADD_CHAR_TO_BLOCK ( s, (UInt32)(*((UChar*)(s->strm->next_in))) );
s->strm->next_in++; s->strm->next_in++;
s->strm->avail_in--; s->strm->avail_in--;
s->strm->total_in_lo32++; s->strm->total_in_lo32++;
@@ -409,18 +409,18 @@ Bool handle_compress ( bz_stream* strm )
Bool progress_in = False; Bool progress_in = False;
Bool progress_out = False; Bool progress_out = False;
EState* s = strm->state; EState* s = strm->state;
while (True) { while (True) {
if (s->state == BZ_S_OUTPUT) { if (s->state == BZ_S_OUTPUT) {
progress_out |= copy_output_until_stop ( s ); progress_out |= copy_output_until_stop ( s );
if (s->state_out_pos < s->numZ) break; if (s->state_out_pos < s->numZ) break;
if (s->mode == BZ_M_FINISHING && if (s->mode == BZ_M_FINISHING &&
s->avail_in_expect == 0 && s->avail_in_expect == 0 &&
isempty_RL(s)) break; isempty_RL(s)) break;
prepare_new_block ( s ); prepare_new_block ( s );
s->state = BZ_S_INPUT; s->state = BZ_S_INPUT;
if (s->mode == BZ_M_FLUSHING && if (s->mode == BZ_M_FLUSHING &&
s->avail_in_expect == 0 && s->avail_in_expect == 0 &&
isempty_RL(s)) break; isempty_RL(s)) break;
} }
@@ -469,9 +469,9 @@ int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action )
if (action == BZ_RUN) { if (action == BZ_RUN) {
progress = handle_compress ( strm ); progress = handle_compress ( strm );
return progress ? BZ_RUN_OK : BZ_PARAM_ERROR; return progress ? BZ_RUN_OK : BZ_PARAM_ERROR;
} }
else else
if (action == BZ_FLUSH) { if (action == BZ_FLUSH) {
s->avail_in_expect = strm->avail_in; s->avail_in_expect = strm->avail_in;
s->mode = BZ_M_FLUSHING; s->mode = BZ_M_FLUSHING;
goto preswitch; goto preswitch;
@@ -482,12 +482,12 @@ int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action )
s->mode = BZ_M_FINISHING; s->mode = BZ_M_FINISHING;
goto preswitch; goto preswitch;
} }
else else
return BZ_PARAM_ERROR; return BZ_PARAM_ERROR;
case BZ_M_FLUSHING: case BZ_M_FLUSHING:
if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR; if (action != BZ_FLUSH) return BZ_SEQUENCE_ERROR;
if (s->avail_in_expect != s->strm->avail_in) if (s->avail_in_expect != s->strm->avail_in)
return BZ_SEQUENCE_ERROR; return BZ_SEQUENCE_ERROR;
progress = handle_compress ( strm ); progress = handle_compress ( strm );
if (s->avail_in_expect > 0 || !isempty_RL(s) || if (s->avail_in_expect > 0 || !isempty_RL(s) ||
@@ -497,7 +497,7 @@ int BZ_API(BZ2_bzCompress) ( bz_stream *strm, int action )
case BZ_M_FINISHING: case BZ_M_FINISHING:
if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR; if (action != BZ_FINISH) return BZ_SEQUENCE_ERROR;
if (s->avail_in_expect != s->strm->avail_in) if (s->avail_in_expect != s->strm->avail_in)
return BZ_SEQUENCE_ERROR; return BZ_SEQUENCE_ERROR;
progress = handle_compress ( strm ); progress = handle_compress ( strm );
if (!progress) return BZ_SEQUENCE_ERROR; if (!progress) return BZ_SEQUENCE_ERROR;
@@ -524,7 +524,7 @@ int BZ_API(BZ2_bzCompressEnd) ( bz_stream *strm )
if (s->ftab != NULL) BZFREE(s->ftab); if (s->ftab != NULL) BZFREE(s->ftab);
BZFREE(strm->state); BZFREE(strm->state);
strm->state = NULL; strm->state = NULL;
return BZ_OK; return BZ_OK;
} }
@@ -535,8 +535,8 @@ int BZ_API(BZ2_bzCompressEnd) ( bz_stream *strm )
/*---------------------------------------------------*/ /*---------------------------------------------------*/
/*---------------------------------------------------*/ /*---------------------------------------------------*/
int BZ_API(BZ2_bzDecompressInit) int BZ_API(BZ2_bzDecompressInit)
( bz_stream* strm, ( bz_stream* strm,
int verbosity, int verbosity,
int small ) int small )
{ {
@@ -601,34 +601,34 @@ Bool unRLE_obuf_to_output_FAST ( DState* s )
/* can a new run be started? */ /* can a new run be started? */
if (s->nblock_used == s->save_nblock+1) return False; if (s->nblock_used == s->save_nblock+1) return False;
/* Only caused by corrupt data stream? */ /* Only caused by corrupt data stream? */
if (s->nblock_used > s->save_nblock+1) if (s->nblock_used > s->save_nblock+1)
return True; return True;
s->state_out_len = 1; s->state_out_len = 1;
s->state_out_ch = s->k0; s->state_out_ch = s->k0;
BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
s->state_out_len = 2; s->state_out_len = 2;
BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
s->state_out_len = 3; s->state_out_len = 3;
BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
BZ_GET_FAST(k1); BZ_RAND_UPD_MASK; BZ_GET_FAST(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
s->state_out_len = ((Int32)k1) + 4; s->state_out_len = ((Int32)k1) + 4;
BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK; BZ_GET_FAST(s->k0); BZ_RAND_UPD_MASK;
s->k0 ^= BZ_RAND_MASK; s->nblock_used++; s->k0 ^= BZ_RAND_MASK; s->nblock_used++;
} }
@@ -665,7 +665,7 @@ Bool unRLE_obuf_to_output_FAST ( DState* s )
} }
s_state_out_len_eq_one: s_state_out_len_eq_one:
{ {
if (cs_avail_out == 0) { if (cs_avail_out == 0) {
c_state_out_len = 1; goto return_notr; c_state_out_len = 1; goto return_notr;
}; };
*( (UChar*)(cs_next_out) ) = c_state_out_ch; *( (UChar*)(cs_next_out) ) = c_state_out_ch;
@@ -673,7 +673,7 @@ Bool unRLE_obuf_to_output_FAST ( DState* s )
cs_next_out++; cs_next_out++;
cs_avail_out--; cs_avail_out--;
} }
} }
/* Only caused by corrupt data stream? */ /* Only caused by corrupt data stream? */
if (c_nblock_used > s_save_nblockPP) if (c_nblock_used > s_save_nblockPP)
return True; return True;
@@ -681,25 +681,25 @@ Bool unRLE_obuf_to_output_FAST ( DState* s )
/* can a new run be started? */ /* can a new run be started? */
if (c_nblock_used == s_save_nblockPP) { if (c_nblock_used == s_save_nblockPP) {
c_state_out_len = 0; goto return_notr; c_state_out_len = 0; goto return_notr;
}; };
c_state_out_ch = c_k0; c_state_out_ch = c_k0;
BZ_GET_FAST_C(k1); c_nblock_used++; BZ_GET_FAST_C(k1); c_nblock_used++;
if (k1 != c_k0) { if (k1 != c_k0) {
c_k0 = k1; goto s_state_out_len_eq_one; c_k0 = k1; goto s_state_out_len_eq_one;
}; };
if (c_nblock_used == s_save_nblockPP) if (c_nblock_used == s_save_nblockPP)
goto s_state_out_len_eq_one; goto s_state_out_len_eq_one;
c_state_out_len = 2; c_state_out_len = 2;
BZ_GET_FAST_C(k1); c_nblock_used++; BZ_GET_FAST_C(k1); c_nblock_used++;
if (c_nblock_used == s_save_nblockPP) continue; if (c_nblock_used == s_save_nblockPP) continue;
if (k1 != c_k0) { c_k0 = k1; continue; }; if (k1 != c_k0) { c_k0 = k1; continue; };
c_state_out_len = 3; c_state_out_len = 3;
BZ_GET_FAST_C(k1); c_nblock_used++; BZ_GET_FAST_C(k1); c_nblock_used++;
if (c_nblock_used == s_save_nblockPP) continue; if (c_nblock_used == s_save_nblockPP) continue;
if (k1 != c_k0) { c_k0 = k1; continue; }; if (k1 != c_k0) { c_k0 = k1; continue; };
BZ_GET_FAST_C(k1); c_nblock_used++; BZ_GET_FAST_C(k1); c_nblock_used++;
c_state_out_len = ((Int32)k1) + 4; c_state_out_len = ((Int32)k1) + 4;
BZ_GET_FAST_C(c_k0); c_nblock_used++; BZ_GET_FAST_C(c_k0); c_nblock_used++;
@@ -767,37 +767,37 @@ Bool unRLE_obuf_to_output_SMALL ( DState* s )
s->strm->total_out_lo32++; s->strm->total_out_lo32++;
if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;
} }
/* can a new run be started? */ /* can a new run be started? */
if (s->nblock_used == s->save_nblock+1) return False; if (s->nblock_used == s->save_nblock+1) return False;
/* Only caused by corrupt data stream? */ /* Only caused by corrupt data stream? */
if (s->nblock_used > s->save_nblock+1) if (s->nblock_used > s->save_nblock+1)
return True; return True;
s->state_out_len = 1; s->state_out_len = 1;
s->state_out_ch = s->k0; s->state_out_ch = s->k0;
BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
s->state_out_len = 2; s->state_out_len = 2;
BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
s->state_out_len = 3; s->state_out_len = 3;
BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK; BZ_GET_SMALL(k1); BZ_RAND_UPD_MASK;
k1 ^= BZ_RAND_MASK; s->nblock_used++; k1 ^= BZ_RAND_MASK; s->nblock_used++;
s->state_out_len = ((Int32)k1) + 4; s->state_out_len = ((Int32)k1) + 4;
BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK; BZ_GET_SMALL(s->k0); BZ_RAND_UPD_MASK;
s->k0 ^= BZ_RAND_MASK; s->nblock_used++; s->k0 ^= BZ_RAND_MASK; s->nblock_used++;
} }
@@ -816,30 +816,30 @@ Bool unRLE_obuf_to_output_SMALL ( DState* s )
s->strm->total_out_lo32++; s->strm->total_out_lo32++;
if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++; if (s->strm->total_out_lo32 == 0) s->strm->total_out_hi32++;
} }
/* can a new run be started? */ /* can a new run be started? */
if (s->nblock_used == s->save_nblock+1) return False; if (s->nblock_used == s->save_nblock+1) return False;
/* Only caused by corrupt data stream? */ /* Only caused by corrupt data stream? */
if (s->nblock_used > s->save_nblock+1) if (s->nblock_used > s->save_nblock+1)
return True; return True;
s->state_out_len = 1; s->state_out_len = 1;
s->state_out_ch = s->k0; s->state_out_ch = s->k0;
BZ_GET_SMALL(k1); s->nblock_used++; BZ_GET_SMALL(k1); s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
s->state_out_len = 2; s->state_out_len = 2;
BZ_GET_SMALL(k1); s->nblock_used++; BZ_GET_SMALL(k1); s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
s->state_out_len = 3; s->state_out_len = 3;
BZ_GET_SMALL(k1); s->nblock_used++; BZ_GET_SMALL(k1); s->nblock_used++;
if (s->nblock_used == s->save_nblock+1) continue; if (s->nblock_used == s->save_nblock+1) continue;
if (k1 != s->k0) { s->k0 = k1; continue; }; if (k1 != s->k0) { s->k0 = k1; continue; };
BZ_GET_SMALL(k1); s->nblock_used++; BZ_GET_SMALL(k1); s->nblock_used++;
s->state_out_len = ((Int32)k1) + 4; s->state_out_len = ((Int32)k1) + 4;
BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_GET_SMALL(s->k0); s->nblock_used++;
@@ -868,14 +868,14 @@ int BZ_API(BZ2_bzDecompress) ( bz_stream *strm )
if (corrupt) return BZ_DATA_ERROR; if (corrupt) return BZ_DATA_ERROR;
if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) { if (s->nblock_used == s->save_nblock+1 && s->state_out_len == 0) {
BZ_FINALISE_CRC ( s->calculatedBlockCRC ); BZ_FINALISE_CRC ( s->calculatedBlockCRC );
if (s->verbosity >= 3) if (s->verbosity >= 3)
VPrintf2 ( " {0x%08x, 0x%08x}", s->storedBlockCRC, VPrintf2 ( " {0x%08x, 0x%08x}", s->storedBlockCRC,
s->calculatedBlockCRC ); s->calculatedBlockCRC );
if (s->verbosity >= 2) VPrintf0 ( "]" ); if (s->verbosity >= 2) VPrintf0 ( "]" );
if (s->calculatedBlockCRC != s->storedBlockCRC) if (s->calculatedBlockCRC != s->storedBlockCRC)
return BZ_DATA_ERROR; return BZ_DATA_ERROR;
s->calculatedCombinedCRC s->calculatedCombinedCRC
= (s->calculatedCombinedCRC << 1) | = (s->calculatedCombinedCRC << 1) |
(s->calculatedCombinedCRC >> 31); (s->calculatedCombinedCRC >> 31);
s->calculatedCombinedCRC ^= s->calculatedBlockCRC; s->calculatedCombinedCRC ^= s->calculatedBlockCRC;
s->state = BZ_X_BLKHDR_1; s->state = BZ_X_BLKHDR_1;
@@ -887,7 +887,7 @@ int BZ_API(BZ2_bzDecompress) ( bz_stream *strm )
Int32 r = BZ2_decompress ( s ); Int32 r = BZ2_decompress ( s );
if (r == BZ_STREAM_END) { if (r == BZ_STREAM_END) {
if (s->verbosity >= 3) if (s->verbosity >= 3)
VPrintf2 ( "\n combined CRCs: stored = 0x%08x, computed = 0x%08x", VPrintf2 ( "\n combined CRCs: stored = 0x%08x, computed = 0x%08x",
s->storedCombinedCRC, s->calculatedCombinedCRC ); s->storedCombinedCRC, s->calculatedCombinedCRC );
if (s->calculatedCombinedCRC != s->storedCombinedCRC) if (s->calculatedCombinedCRC != s->storedCombinedCRC)
return BZ_DATA_ERROR; return BZ_DATA_ERROR;
@@ -934,7 +934,7 @@ int BZ_API(BZ2_bzDecompressEnd) ( bz_stream *strm )
if (bzf != NULL) bzf->lastErr = eee; \ if (bzf != NULL) bzf->lastErr = eee; \
} }
typedef typedef
struct { struct {
FILE* handle; FILE* handle;
Char buf[BZ_MAX_UNUSED]; Char buf[BZ_MAX_UNUSED];
@@ -958,10 +958,10 @@ static Bool myfeof ( FILE* f )
/*---------------------------------------------------*/ /*---------------------------------------------------*/
BZFILE* BZ_API(BZ2_bzWriteOpen) BZFILE* BZ_API(BZ2_bzWriteOpen)
( int* bzerror, ( int* bzerror,
FILE* f, FILE* f,
int blockSize100k, int blockSize100k,
int verbosity, int verbosity,
int workFactor ) int workFactor )
{ {
@@ -993,23 +993,23 @@ BZFILE* BZ_API(BZ2_bzWriteOpen)
bzf->strm.opaque = NULL; bzf->strm.opaque = NULL;
if (workFactor == 0) workFactor = 30; if (workFactor == 0) workFactor = 30;
ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k, ret = BZ2_bzCompressInit ( &(bzf->strm), blockSize100k,
verbosity, workFactor ); verbosity, workFactor );
if (ret != BZ_OK) if (ret != BZ_OK)
{ BZ_SETERR(ret); free(bzf); return NULL; }; { BZ_SETERR(ret); free(bzf); return NULL; };
bzf->strm.avail_in = 0; bzf->strm.avail_in = 0;
bzf->initialisedOk = True; bzf->initialisedOk = True;
return bzf; return bzf;
} }
/*---------------------------------------------------*/ /*---------------------------------------------------*/
void BZ_API(BZ2_bzWrite) void BZ_API(BZ2_bzWrite)
( int* bzerror, ( int* bzerror,
BZFILE* b, BZFILE* b,
void* buf, void* buf,
int len ) int len )
{ {
Int32 n, n2, ret; Int32 n, n2, ret;
@@ -1038,7 +1038,7 @@ void BZ_API(BZ2_bzWrite)
if (bzf->strm.avail_out < BZ_MAX_UNUSED) { if (bzf->strm.avail_out < BZ_MAX_UNUSED) {
n = BZ_MAX_UNUSED - bzf->strm.avail_out; n = BZ_MAX_UNUSED - bzf->strm.avail_out;
n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar),
n, bzf->handle ); n, bzf->handle );
if (n != n2 || ferror(bzf->handle)) if (n != n2 || ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return; }; { BZ_SETERR(BZ_IO_ERROR); return; };
@@ -1052,20 +1052,20 @@ void BZ_API(BZ2_bzWrite)
/*---------------------------------------------------*/ /*---------------------------------------------------*/
void BZ_API(BZ2_bzWriteClose) void BZ_API(BZ2_bzWriteClose)
( int* bzerror, ( int* bzerror,
BZFILE* b, BZFILE* b,
int abandon, int abandon,
unsigned int* nbytes_in, unsigned int* nbytes_in,
unsigned int* nbytes_out ) unsigned int* nbytes_out )
{ {
BZ2_bzWriteClose64 ( bzerror, b, abandon, BZ2_bzWriteClose64 ( bzerror, b, abandon,
nbytes_in, NULL, nbytes_out, NULL ); nbytes_in, NULL, nbytes_out, NULL );
} }
void BZ_API(BZ2_bzWriteClose64) void BZ_API(BZ2_bzWriteClose64)
( int* bzerror, ( int* bzerror,
BZFILE* b, BZFILE* b,
int abandon, int abandon,
unsigned int* nbytes_in_lo32, unsigned int* nbytes_in_lo32,
unsigned int* nbytes_in_hi32, unsigned int* nbytes_in_hi32,
@@ -1097,7 +1097,7 @@ void BZ_API(BZ2_bzWriteClose64)
if (bzf->strm.avail_out < BZ_MAX_UNUSED) { if (bzf->strm.avail_out < BZ_MAX_UNUSED) {
n = BZ_MAX_UNUSED - bzf->strm.avail_out; n = BZ_MAX_UNUSED - bzf->strm.avail_out;
n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar), n2 = fwrite ( (void*)(bzf->buf), sizeof(UChar),
n, bzf->handle ); n, bzf->handle );
if (n != n2 || ferror(bzf->handle)) if (n != n2 || ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return; }; { BZ_SETERR(BZ_IO_ERROR); return; };
@@ -1129,9 +1129,9 @@ void BZ_API(BZ2_bzWriteClose64)
/*---------------------------------------------------*/ /*---------------------------------------------------*/
BZFILE* BZ_API(BZ2_bzReadOpen) BZFILE* BZ_API(BZ2_bzReadOpen)
( int* bzerror, ( int* bzerror,
FILE* f, FILE* f,
int verbosity, int verbosity,
int small, int small,
void* unused, void* unused,
@@ -1142,7 +1142,7 @@ BZFILE* BZ_API(BZ2_bzReadOpen)
BZ_SETERR(BZ_OK); BZ_SETERR(BZ_OK);
if (f == NULL || if (f == NULL ||
(small != 0 && small != 1) || (small != 0 && small != 1) ||
(verbosity < 0 || verbosity > 4) || (verbosity < 0 || verbosity > 4) ||
(unused == NULL && nUnused != 0) || (unused == NULL && nUnused != 0) ||
@@ -1153,7 +1153,7 @@ BZFILE* BZ_API(BZ2_bzReadOpen)
{ BZ_SETERR(BZ_IO_ERROR); return NULL; }; { BZ_SETERR(BZ_IO_ERROR); return NULL; };
bzf = malloc ( sizeof(bzFile) ); bzf = malloc ( sizeof(bzFile) );
if (bzf == NULL) if (bzf == NULL)
{ BZ_SETERR(BZ_MEM_ERROR); return NULL; }; { BZ_SETERR(BZ_MEM_ERROR); return NULL; };
BZ_SETERR(BZ_OK); BZ_SETERR(BZ_OK);
@@ -1165,7 +1165,7 @@ BZFILE* BZ_API(BZ2_bzReadOpen)
bzf->strm.bzalloc = NULL; bzf->strm.bzalloc = NULL;
bzf->strm.bzfree = NULL; bzf->strm.bzfree = NULL;
bzf->strm.opaque = NULL; bzf->strm.opaque = NULL;
while (nUnused > 0) { while (nUnused > 0) {
bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++; bzf->buf[bzf->bufN] = *((UChar*)(unused)); bzf->bufN++;
unused = ((void*)( 1 + ((UChar*)(unused)) )); unused = ((void*)( 1 + ((UChar*)(unused)) ));
@@ -1180,7 +1180,7 @@ BZFILE* BZ_API(BZ2_bzReadOpen)
bzf->strm.next_in = bzf->buf; bzf->strm.next_in = bzf->buf;
bzf->initialisedOk = True; bzf->initialisedOk = True;
return bzf; return bzf;
} }
@@ -1203,10 +1203,10 @@ void BZ_API(BZ2_bzReadClose) ( int *bzerror, BZFILE *b )
/*---------------------------------------------------*/ /*---------------------------------------------------*/
int BZ_API(BZ2_bzRead) int BZ_API(BZ2_bzRead)
( int* bzerror, ( int* bzerror,
BZFILE* b, BZFILE* b,
void* buf, void* buf,
int len ) int len )
{ {
Int32 n, ret; Int32 n, ret;
@@ -1228,11 +1228,11 @@ int BZ_API(BZ2_bzRead)
while (True) { while (True) {
if (ferror(bzf->handle)) if (ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return 0; }; { BZ_SETERR(BZ_IO_ERROR); return 0; };
if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) { if (bzf->strm.avail_in == 0 && !myfeof(bzf->handle)) {
n = fread ( bzf->buf, sizeof(UChar), n = fread ( bzf->buf, sizeof(UChar),
BZ_MAX_UNUSED, bzf->handle ); BZ_MAX_UNUSED, bzf->handle );
if (ferror(bzf->handle)) if (ferror(bzf->handle))
{ BZ_SETERR(BZ_IO_ERROR); return 0; }; { BZ_SETERR(BZ_IO_ERROR); return 0; };
@@ -1246,7 +1246,7 @@ int BZ_API(BZ2_bzRead)
if (ret != BZ_OK && ret != BZ_STREAM_END) if (ret != BZ_OK && ret != BZ_STREAM_END)
{ BZ_SETERR(ret); return 0; }; { BZ_SETERR(ret); return 0; };
if (ret == BZ_OK && myfeof(bzf->handle) && if (ret == BZ_OK && myfeof(bzf->handle) &&
bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0) bzf->strm.avail_in == 0 && bzf->strm.avail_out > 0)
{ BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; }; { BZ_SETERR(BZ_UNEXPECTED_EOF); return 0; };
@@ -1255,7 +1255,7 @@ int BZ_API(BZ2_bzRead)
return len - bzf->strm.avail_out; }; return len - bzf->strm.avail_out; };
if (bzf->strm.avail_out == 0) if (bzf->strm.avail_out == 0)
{ BZ_SETERR(BZ_OK); return len; }; { BZ_SETERR(BZ_OK); return len; };
} }
return 0; /*not reached*/ return 0; /*not reached*/
@@ -1263,10 +1263,10 @@ int BZ_API(BZ2_bzRead)
/*---------------------------------------------------*/ /*---------------------------------------------------*/
void BZ_API(BZ2_bzReadGetUnused) void BZ_API(BZ2_bzReadGetUnused)
( int* bzerror, ( int* bzerror,
BZFILE* b, BZFILE* b,
void** unused, void** unused,
int* nUnused ) int* nUnused )
{ {
bzFile* bzf = (bzFile*)b; bzFile* bzf = (bzFile*)b;
@@ -1289,30 +1289,30 @@ void BZ_API(BZ2_bzReadGetUnused)
/*---------------------------------------------------*/ /*---------------------------------------------------*/
/*---------------------------------------------------*/ /*---------------------------------------------------*/
int BZ_API(BZ2_bzBuffToBuffCompress) int BZ_API(BZ2_bzBuffToBuffCompress)
( char* dest, ( char* dest,
unsigned int* destLen, unsigned int* destLen,
char* source, char* source,
unsigned int sourceLen, unsigned int sourceLen,
int blockSize100k, int blockSize100k,
int verbosity, int verbosity,
int workFactor ) int workFactor )
{ {
bz_stream strm; bz_stream strm;
int ret; int ret;
if (dest == NULL || destLen == NULL || if (dest == NULL || destLen == NULL ||
source == NULL || source == NULL ||
blockSize100k < 1 || blockSize100k > 9 || blockSize100k < 1 || blockSize100k > 9 ||
verbosity < 0 || verbosity > 4 || verbosity < 0 || verbosity > 4 ||
workFactor < 0 || workFactor > 250) workFactor < 0 || workFactor > 250)
return BZ_PARAM_ERROR; return BZ_PARAM_ERROR;
if (workFactor == 0) workFactor = 30; if (workFactor == 0) workFactor = 30;
strm.bzalloc = NULL; strm.bzalloc = NULL;
strm.bzfree = NULL; strm.bzfree = NULL;
strm.opaque = NULL; strm.opaque = NULL;
ret = BZ2_bzCompressInit ( &strm, blockSize100k, ret = BZ2_bzCompressInit ( &strm, blockSize100k,
verbosity, workFactor ); verbosity, workFactor );
if (ret != BZ_OK) return ret; if (ret != BZ_OK) return ret;
@@ -1326,7 +1326,7 @@ int BZ_API(BZ2_bzBuffToBuffCompress)
if (ret != BZ_STREAM_END) goto errhandler; if (ret != BZ_STREAM_END) goto errhandler;
/* normal termination */ /* normal termination */
*destLen -= strm.avail_out; *destLen -= strm.avail_out;
BZ2_bzCompressEnd ( &strm ); BZ2_bzCompressEnd ( &strm );
return BZ_OK; return BZ_OK;
@@ -1341,10 +1341,10 @@ int BZ_API(BZ2_bzBuffToBuffCompress)
/*---------------------------------------------------*/ /*---------------------------------------------------*/
int BZ_API(BZ2_bzBuffToBuffDecompress) int BZ_API(BZ2_bzBuffToBuffDecompress)
( char* dest, ( char* dest,
unsigned int* destLen, unsigned int* destLen,
char* source, char* source,
unsigned int sourceLen, unsigned int sourceLen,
int small, int small,
int verbosity ) int verbosity )
@@ -1352,10 +1352,10 @@ int BZ_API(BZ2_bzBuffToBuffDecompress)
bz_stream strm; bz_stream strm;
int ret; int ret;
if (dest == NULL || destLen == NULL || if (dest == NULL || destLen == NULL ||
source == NULL || source == NULL ||
(small != 0 && small != 1) || (small != 0 && small != 1) ||
verbosity < 0 || verbosity > 4) verbosity < 0 || verbosity > 4)
return BZ_PARAM_ERROR; return BZ_PARAM_ERROR;
strm.bzalloc = NULL; strm.bzalloc = NULL;
@@ -1385,11 +1385,11 @@ int BZ_API(BZ2_bzBuffToBuffDecompress)
} else { } else {
BZ2_bzDecompressEnd ( &strm ); BZ2_bzDecompressEnd ( &strm );
return BZ_OUTBUFF_FULL; return BZ_OUTBUFF_FULL;
}; };
errhandler: errhandler:
BZ2_bzDecompressEnd ( &strm ); BZ2_bzDecompressEnd ( &strm );
return ret; return ret;
} }
@@ -1442,7 +1442,7 @@ BZFILE * bzopen_or_bzdopen
int verbosity = 0; int verbosity = 0;
int workFactor = 30; int workFactor = 30;
int smallMode = 0; int smallMode = 0;
int nUnused = 0; int nUnused = 0;
if (mode == NULL) return NULL; if (mode == NULL) return NULL;
while (*mode) { while (*mode) {
@@ -1482,7 +1482,7 @@ BZFILE * bzopen_or_bzdopen
if (writing) { if (writing) {
/* Guard against total chaos and anarchy -- JRS */ /* Guard against total chaos and anarchy -- JRS */
if (blockSize100k < 1) blockSize100k = 1; if (blockSize100k < 1) blockSize100k = 1;
if (blockSize100k > 9) blockSize100k = 9; if (blockSize100k > 9) blockSize100k = 9;
bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k, bzfp = BZ2_bzWriteOpen(&bzerr,fp,blockSize100k,
verbosity,workFactor); verbosity,workFactor);
} else { } else {
@@ -1561,7 +1561,7 @@ void BZ_API(BZ2_bzclose) (BZFILE* b)
{ {
int bzerr; int bzerr;
FILE *fp = ((bzFile *)b)->handle; FILE *fp = ((bzFile *)b)->handle;
if (b==NULL) {return;} if (b==NULL) {return;}
if(((bzFile*)b)->writing){ if(((bzFile*)b)->writing){
BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL); BZ2_bzWriteClose(&bzerr,b,0,NULL,NULL);
@@ -1579,7 +1579,7 @@ void BZ_API(BZ2_bzclose) (BZFILE* b)
/*---------------------------------------------------*/ /*---------------------------------------------------*/
/*-- /*--
return last error code return last error code
--*/ --*/
static char *bzerrorstrings[] = { static char *bzerrorstrings[] = {
"OK" "OK"
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -85,7 +85,7 @@ extern "C" {
#define BZ_OUTBUFF_FULL (-8) #define BZ_OUTBUFF_FULL (-8)
#define BZ_CONFIG_ERROR (-9) #define BZ_CONFIG_ERROR (-9)
typedef typedef
struct { struct {
char *next_in; char *next_in;
unsigned int avail_in; unsigned int avail_in;
@@ -102,7 +102,7 @@ typedef
void *(*bzalloc)(void *,int,int); void *(*bzalloc)(void *,int,int);
void (*bzfree)(void *,void *); void (*bzfree)(void *,void *);
void *opaque; void *opaque;
} }
bz_stream; bz_stream;
@@ -137,34 +137,34 @@ typedef
/*-- Core (low-level) library functions --*/ /*-- Core (low-level) library functions --*/
BZ_EXTERN int BZ_API(BZ2_bzCompressInit) ( BZ_EXTERN int BZ_API(BZ2_bzCompressInit) (
bz_stream* strm, bz_stream* strm,
int blockSize100k, int blockSize100k,
int verbosity, int verbosity,
int workFactor int workFactor
); );
BZ_EXTERN int BZ_API(BZ2_bzCompress) ( BZ_EXTERN int BZ_API(BZ2_bzCompress) (
bz_stream* strm, bz_stream* strm,
int action int action
); );
BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) ( BZ_EXTERN int BZ_API(BZ2_bzCompressEnd) (
bz_stream* strm bz_stream* strm
); );
BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) ( BZ_EXTERN int BZ_API(BZ2_bzDecompressInit) (
bz_stream *strm, bz_stream *strm,
int verbosity, int verbosity,
int small int small
); );
BZ_EXTERN int BZ_API(BZ2_bzDecompress) ( BZ_EXTERN int BZ_API(BZ2_bzDecompress) (
bz_stream* strm bz_stream* strm
); );
BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) ( BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) (
bz_stream *strm bz_stream *strm
); );
@@ -176,64 +176,64 @@ BZ_EXTERN int BZ_API(BZ2_bzDecompressEnd) (
typedef void BZFILE; typedef void BZFILE;
BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) ( BZ_EXTERN BZFILE* BZ_API(BZ2_bzReadOpen) (
int* bzerror, int* bzerror,
FILE* f, FILE* f,
int verbosity, int verbosity,
int small, int small,
void* unused, void* unused,
int nUnused int nUnused
); );
BZ_EXTERN void BZ_API(BZ2_bzReadClose) ( BZ_EXTERN void BZ_API(BZ2_bzReadClose) (
int* bzerror, int* bzerror,
BZFILE* b BZFILE* b
); );
BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) ( BZ_EXTERN void BZ_API(BZ2_bzReadGetUnused) (
int* bzerror, int* bzerror,
BZFILE* b, BZFILE* b,
void** unused, void** unused,
int* nUnused int* nUnused
); );
BZ_EXTERN int BZ_API(BZ2_bzRead) ( BZ_EXTERN int BZ_API(BZ2_bzRead) (
int* bzerror, int* bzerror,
BZFILE* b, BZFILE* b,
void* buf, void* buf,
int len int len
); );
BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) ( BZ_EXTERN BZFILE* BZ_API(BZ2_bzWriteOpen) (
int* bzerror, int* bzerror,
FILE* f, FILE* f,
int blockSize100k, int blockSize100k,
int verbosity, int verbosity,
int workFactor int workFactor
); );
BZ_EXTERN void BZ_API(BZ2_bzWrite) ( BZ_EXTERN void BZ_API(BZ2_bzWrite) (
int* bzerror, int* bzerror,
BZFILE* b, BZFILE* b,
void* buf, void* buf,
int len int len
); );
BZ_EXTERN void BZ_API(BZ2_bzWriteClose) ( BZ_EXTERN void BZ_API(BZ2_bzWriteClose) (
int* bzerror, int* bzerror,
BZFILE* b, BZFILE* b,
int abandon, int abandon,
unsigned int* nbytes_in, unsigned int* nbytes_in,
unsigned int* nbytes_out unsigned int* nbytes_out
); );
BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) ( BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) (
int* bzerror, int* bzerror,
BZFILE* b, BZFILE* b,
int abandon, int abandon,
unsigned int* nbytes_in_lo32, unsigned int* nbytes_in_lo32,
unsigned int* nbytes_in_hi32, unsigned int* nbytes_in_hi32,
unsigned int* nbytes_out_lo32, unsigned int* nbytes_out_lo32,
unsigned int* nbytes_out_hi32 unsigned int* nbytes_out_hi32
); );
#endif #endif
@@ -241,23 +241,23 @@ BZ_EXTERN void BZ_API(BZ2_bzWriteClose64) (
/*-- Utility functions --*/ /*-- Utility functions --*/
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) ( BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffCompress) (
char* dest, char* dest,
unsigned int* destLen, unsigned int* destLen,
char* source, char* source,
unsigned int sourceLen, unsigned int sourceLen,
int blockSize100k, int blockSize100k,
int verbosity, int verbosity,
int workFactor int workFactor
); );
BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) ( BZ_EXTERN int BZ_API(BZ2_bzBuffToBuffDecompress) (
char* dest, char* dest,
unsigned int* destLen, unsigned int* destLen,
char* source, char* source,
unsigned int sourceLen, unsigned int sourceLen,
int small, int small,
int verbosity int verbosity
); );
@@ -285,17 +285,17 @@ BZ_EXTERN BZFILE * BZ_API(BZ2_bzdopen) (
int fd, int fd,
const char *mode const char *mode
); );
BZ_EXTERN int BZ_API(BZ2_bzread) ( BZ_EXTERN int BZ_API(BZ2_bzread) (
BZFILE* b, BZFILE* b,
void* buf, void* buf,
int len int len
); );
BZ_EXTERN int BZ_API(BZ2_bzwrite) ( BZ_EXTERN int BZ_API(BZ2_bzwrite) (
BZFILE* b, BZFILE* b,
void* buf, void* buf,
int len int len
); );
BZ_EXTERN int BZ_API(BZ2_bzflush) ( BZ_EXTERN int BZ_API(BZ2_bzflush) (
@@ -307,7 +307,7 @@ BZ_EXTERN void BZ_API(BZ2_bzclose) (
); );
BZ_EXTERN const char * BZ_API(BZ2_bzerror) ( BZ_EXTERN const char * BZ_API(BZ2_bzerror) (
BZFILE *b, BZFILE *b,
int *errnum int *errnum
); );
#endif #endif
@@ -321,4 +321,3 @@ BZ_EXTERN const char * BZ_API(BZ2_bzerror) (
/*-------------------------------------------------------------*/ /*-------------------------------------------------------------*/
/*--- end bzlib.h ---*/ /*--- end bzlib.h ---*/
/*-------------------------------------------------------------*/ /*-------------------------------------------------------------*/
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -91,7 +91,7 @@ typedef unsigned short UInt16;
#ifndef __GNUC__ #ifndef __GNUC__
#define __inline__ /* */ #define __inline__ /* */
#endif #endif
#ifndef BZ_NO_STDIO #ifndef BZ_NO_STDIO
extern void BZ2_bz__AssertH__fail ( int errcode ); extern void BZ2_bz__AssertH__fail ( int errcode );
@@ -143,7 +143,7 @@ extern void bz_internal_error ( int errcode );
#define BZ_HDR_Z 0x5a /* 'Z' */ #define BZ_HDR_Z 0x5a /* 'Z' */
#define BZ_HDR_h 0x68 /* 'h' */ #define BZ_HDR_h 0x68 /* 'h' */
#define BZ_HDR_0 0x30 /* '0' */ #define BZ_HDR_0 0x30 /* '0' */
/*-- Constants for the back end. --*/ /*-- Constants for the back end. --*/
#define BZ_MAX_ALPHA_SIZE 258 #define BZ_MAX_ALPHA_SIZE 258
@@ -303,19 +303,19 @@ typedef
/*-- externs for compression. --*/ /*-- externs for compression. --*/
extern void extern void
BZ2_blockSort ( EState* ); BZ2_blockSort ( EState* );
extern void extern void
BZ2_compressBlock ( EState*, Bool ); BZ2_compressBlock ( EState*, Bool );
extern void extern void
BZ2_bsInitWrite ( EState* ); BZ2_bsInitWrite ( EState* );
extern void extern void
BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 ); BZ2_hbAssignCodes ( Int32*, UChar*, Int32, Int32, Int32 );
extern void extern void
BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 ); BZ2_hbMakeCodeLengths ( UChar*, Int32*, Int32, Int32 );
@@ -459,7 +459,7 @@ typedef
Int32 save_N; Int32 save_N;
Int32 save_curr; Int32 save_curr;
Int32 save_zt; Int32 save_zt;
Int32 save_zn; Int32 save_zn;
Int32 save_zvec; Int32 save_zvec;
Int32 save_zj; Int32 save_zj;
Int32 save_gSel; Int32 save_gSel;
@@ -509,13 +509,13 @@ typedef
/*-- externs for decompression. --*/ /*-- externs for decompression. --*/
extern Int32 extern Int32
BZ2_indexIntoF ( Int32, Int32* ); BZ2_indexIntoF ( Int32, Int32* );
extern Int32 extern Int32
BZ2_decompress ( DState* ); BZ2_decompress ( DState* );
extern void extern void
BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*, BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,
Int32, Int32, Int32 ); Int32, Int32, Int32 );
@@ -535,4 +535,3 @@ BZ2_hbCreateDecodeTables ( Int32*, Int32*, Int32*, UChar*,
/*-------------------------------------------------------------*/ /*-------------------------------------------------------------*/
/*--- end bzlib_private.h ---*/ /*--- end bzlib_private.h ---*/
/*-------------------------------------------------------------*/ /*-------------------------------------------------------------*/
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -66,7 +66,7 @@
0.9.0a/b -- no changes in this file. 0.9.0a/b -- no changes in this file.
0.9.0c 0.9.0c
* changed setting of nGroups in sendMTFValues() so as to * changed setting of nGroups in sendMTFValues() so as to
do a bit better on small files do a bit better on small files
--*/ --*/
@@ -169,11 +169,11 @@ void generateMTFValues ( EState* s )
Int32 wr; Int32 wr;
Int32 EOB; Int32 EOB;
/* /*
After sorting (eg, here), After sorting (eg, here),
s->arr1 [ 0 .. s->nblock-1 ] holds sorted order, s->arr1 [ 0 .. s->nblock-1 ] holds sorted order,
and and
((UChar*)s->arr2) [ 0 .. s->nblock-1 ] ((UChar*)s->arr2) [ 0 .. s->nblock-1 ]
holds the original block data. holds the original block data.
The first thing to do is generate the MTF values, The first thing to do is generate the MTF values,
@@ -188,7 +188,7 @@ void generateMTFValues ( EState* s )
(UChar*) (&((UChar*)s->arr2)[s->nblock]) (UChar*) (&((UChar*)s->arr2)[s->nblock])
These storage aliases are set up in bzCompressInit(), These storage aliases are set up in bzCompressInit(),
except for the last one, which is arranged in except for the last one, which is arranged in
compressBlock(). compressBlock().
*/ */
UInt32* ptr = s->ptr; UInt32* ptr = s->ptr;
@@ -211,7 +211,7 @@ void generateMTFValues ( EState* s )
ll_i = s->unseqToSeq[block[j]]; ll_i = s->unseqToSeq[block[j]];
AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" ); AssertD ( ll_i < s->nInUse, "generateMTFValues(2a)" );
if (yy[0] == ll_i) { if (yy[0] == ll_i) {
zPend++; zPend++;
} else { } else {
@@ -219,11 +219,11 @@ void generateMTFValues ( EState* s )
zPend--; zPend--;
while (True) { while (True) {
if (zPend & 1) { if (zPend & 1) {
mtfv[wr] = BZ_RUNB; wr++; mtfv[wr] = BZ_RUNB; wr++;
s->mtfFreq[BZ_RUNB]++; s->mtfFreq[BZ_RUNB]++;
} else { } else {
mtfv[wr] = BZ_RUNA; wr++; mtfv[wr] = BZ_RUNA; wr++;
s->mtfFreq[BZ_RUNA]++; s->mtfFreq[BZ_RUNA]++;
} }
if (zPend < 2) break; if (zPend < 2) break;
zPend = (zPend - 2) / 2; zPend = (zPend - 2) / 2;
@@ -257,11 +257,11 @@ void generateMTFValues ( EState* s )
zPend--; zPend--;
while (True) { while (True) {
if (zPend & 1) { if (zPend & 1) {
mtfv[wr] = BZ_RUNB; wr++; mtfv[wr] = BZ_RUNB; wr++;
s->mtfFreq[BZ_RUNB]++; s->mtfFreq[BZ_RUNB]++;
} else { } else {
mtfv[wr] = BZ_RUNA; wr++; mtfv[wr] = BZ_RUNA; wr++;
s->mtfFreq[BZ_RUNA]++; s->mtfFreq[BZ_RUNA]++;
} }
if (zPend < 2) break; if (zPend < 2) break;
zPend = (zPend - 2) / 2; zPend = (zPend - 2) / 2;
@@ -304,7 +304,7 @@ void sendMTFValues ( EState* s )
if (s->verbosity >= 3) if (s->verbosity >= 3)
VPrintf3( " %d in block, %d after MTF & 1-2 coding, " VPrintf3( " %d in block, %d after MTF & 1-2 coding, "
"%d+2 syms in use\n", "%d+2 syms in use\n",
s->nblock, s->nMTF, s->nInUse ); s->nblock, s->nMTF, s->nInUse );
alphaSize = s->nInUse+2; alphaSize = s->nInUse+2;
@@ -321,7 +321,7 @@ void sendMTFValues ( EState* s )
nGroups = 6; nGroups = 6;
/*--- Generate an initial set of coding tables ---*/ /*--- Generate an initial set of coding tables ---*/
{ {
Int32 nPart, remF, tFreq, aFreq; Int32 nPart, remF, tFreq, aFreq;
nPart = nGroups; nPart = nGroups;
@@ -336,8 +336,8 @@ void sendMTFValues ( EState* s )
aFreq += s->mtfFreq[ge]; aFreq += s->mtfFreq[ge];
} }
if (ge > gs if (ge > gs
&& nPart != nGroups && nPart != 1 && nPart != nGroups && nPart != 1
&& ((nGroups-nPart) % 2 == 1)) { && ((nGroups-nPart) % 2 == 1)) {
aFreq -= s->mtfFreq[ge]; aFreq -= s->mtfFreq[ge];
ge--; ge--;
@@ -346,21 +346,21 @@ void sendMTFValues ( EState* s )
if (s->verbosity >= 3) if (s->verbosity >= 3)
VPrintf5( " initial group %d, [%d .. %d], " VPrintf5( " initial group %d, [%d .. %d], "
"has %d syms (%4.1f%%)\n", "has %d syms (%4.1f%%)\n",
nPart, gs, ge, aFreq, nPart, gs, ge, aFreq,
(100.0 * (float)aFreq) / (float)(s->nMTF) ); (100.0 * (float)aFreq) / (float)(s->nMTF) );
for (v = 0; v < alphaSize; v++) for (v = 0; v < alphaSize; v++)
if (v >= gs && v <= ge) if (v >= gs && v <= ge)
s->len[nPart-1][v] = BZ_LESSER_ICOST; else s->len[nPart-1][v] = BZ_LESSER_ICOST; else
s->len[nPart-1][v] = BZ_GREATER_ICOST; s->len[nPart-1][v] = BZ_GREATER_ICOST;
nPart--; nPart--;
gs = ge+1; gs = ge+1;
remF -= aFreq; remF -= aFreq;
} }
} }
/*--- /*---
Iterate up to BZ_N_ITERS times to improve the tables. Iterate up to BZ_N_ITERS times to improve the tables.
---*/ ---*/
for (iter = 0; iter < BZ_N_ITERS; iter++) { for (iter = 0; iter < BZ_N_ITERS; iter++) {
@@ -373,14 +373,14 @@ void sendMTFValues ( EState* s )
/*--- /*---
Set up an auxiliary length table which is used to fast-track Set up an auxiliary length table which is used to fast-track
the common case (nGroups == 6). the common case (nGroups == 6).
---*/ ---*/
if (nGroups == 6) { if (nGroups == 6) {
for (v = 0; v < alphaSize; v++) { for (v = 0; v < alphaSize; v++) {
s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v]; s->len_pack[v][0] = (s->len[1][v] << 16) | s->len[0][v];
s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v]; s->len_pack[v][1] = (s->len[3][v] << 16) | s->len[2][v];
s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v]; s->len_pack[v][2] = (s->len[5][v] << 16) | s->len[4][v];
} }
} }
nSelectors = 0; nSelectors = 0;
@@ -390,10 +390,10 @@ void sendMTFValues ( EState* s )
/*--- Set group start & end marks. --*/ /*--- Set group start & end marks. --*/
if (gs >= s->nMTF) break; if (gs >= s->nMTF) break;
ge = gs + BZ_G_SIZE - 1; ge = gs + BZ_G_SIZE - 1;
if (ge >= s->nMTF) ge = s->nMTF-1; if (ge >= s->nMTF) ge = s->nMTF-1;
/*-- /*--
Calculate the cost of this group as coded Calculate the cost of this group as coded
by each of the coding tables. by each of the coding tables.
--*/ --*/
@@ -429,14 +429,14 @@ void sendMTFValues ( EState* s )
cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16; cost[4] = cost45 & 0xffff; cost[5] = cost45 >> 16;
} else { } else {
/*--- slow version which correctly handles all situations ---*/ /*--- slow version which correctly handles all situations ---*/
for (i = gs; i <= ge; i++) { for (i = gs; i <= ge; i++) {
UInt16 icv = mtfv[i]; UInt16 icv = mtfv[i];
for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv]; for (t = 0; t < nGroups; t++) cost[t] += s->len[t][icv];
} }
} }
/*-- /*--
Find the coding table which is best for this group, Find the coding table which is best for this group,
and record its identity in the selector table. and record its identity in the selector table.
--*/ --*/
@@ -448,7 +448,7 @@ void sendMTFValues ( EState* s )
s->selector[nSelectors] = bt; s->selector[nSelectors] = bt;
nSelectors++; nSelectors++;
/*-- /*--
Increment the symbol frequencies for the selected table. Increment the symbol frequencies for the selected table.
--*/ --*/
if (nGroups == 6 && 50 == ge-gs+1) { if (nGroups == 6 && 50 == ge-gs+1) {
@@ -470,7 +470,7 @@ void sendMTFValues ( EState* s )
# undef BZ_ITUR # undef BZ_ITUR
} else { } else {
/*--- slow version which correctly handles all situations ---*/ /*--- slow version which correctly handles all situations ---*/
for (i = gs; i <= ge; i++) for (i = gs; i <= ge; i++)
s->rfreq[bt][ mtfv[i] ]++; s->rfreq[bt][ mtfv[i] ]++;
} }
@@ -478,7 +478,7 @@ void sendMTFValues ( EState* s )
gs = ge+1; gs = ge+1;
} }
if (s->verbosity >= 3) { if (s->verbosity >= 3) {
VPrintf2 ( " pass %d: size is %d, grp uses are ", VPrintf2 ( " pass %d: size is %d, grp uses are ",
iter+1, totc/8 ); iter+1, totc/8 );
for (t = 0; t < nGroups; t++) for (t = 0; t < nGroups; t++)
VPrintf1 ( "%d ", fave[t] ); VPrintf1 ( "%d ", fave[t] );
@@ -488,10 +488,10 @@ void sendMTFValues ( EState* s )
/*-- /*--
Recompute the tables based on the accumulated frequencies. Recompute the tables based on the accumulated frequencies.
--*/ --*/
/* maxLen was changed from 20 to 17 in bzip2-1.0.3. See /* maxLen was changed from 20 to 17 in bzip2-1.0.3. See
comment in huffman.c for details. */ comment in huffman.c for details. */
for (t = 0; t < nGroups; t++) for (t = 0; t < nGroups; t++)
BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]), BZ2_hbMakeCodeLengths ( &(s->len[t][0]), &(s->rfreq[t][0]),
alphaSize, 17 /*20*/ ); alphaSize, 17 /*20*/ );
} }
@@ -531,19 +531,19 @@ void sendMTFValues ( EState* s )
} }
AssertH ( !(maxLen > 17 /*20*/ ), 3004 ); AssertH ( !(maxLen > 17 /*20*/ ), 3004 );
AssertH ( !(minLen < 1), 3005 ); AssertH ( !(minLen < 1), 3005 );
BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]), BZ2_hbAssignCodes ( &(s->code[t][0]), &(s->len[t][0]),
minLen, maxLen, alphaSize ); minLen, maxLen, alphaSize );
} }
/*--- Transmit the mapping table. ---*/ /*--- Transmit the mapping table. ---*/
{ {
Bool inUse16[16]; Bool inUse16[16];
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
inUse16[i] = False; inUse16[i] = False;
for (j = 0; j < 16; j++) for (j = 0; j < 16; j++)
if (s->inUse[i * 16 + j]) inUse16[i] = True; if (s->inUse[i * 16 + j]) inUse16[i] = True;
} }
nBytes = s->numZ; nBytes = s->numZ;
for (i = 0; i < 16; i++) for (i = 0; i < 16; i++)
if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0); if (inUse16[i]) bsW(s,1,1); else bsW(s,1,0);
@@ -554,7 +554,7 @@ void sendMTFValues ( EState* s )
if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0); if (s->inUse[i * 16 + j]) bsW(s,1,1); else bsW(s,1,0);
} }
if (s->verbosity >= 3) if (s->verbosity >= 3)
VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes ); VPrintf1( " bytes: mapping %d, ", s->numZ-nBytes );
} }
@@ -562,7 +562,7 @@ void sendMTFValues ( EState* s )
nBytes = s->numZ; nBytes = s->numZ;
bsW ( s, 3, nGroups ); bsW ( s, 3, nGroups );
bsW ( s, 15, nSelectors ); bsW ( s, 15, nSelectors );
for (i = 0; i < nSelectors; i++) { for (i = 0; i < nSelectors; i++) {
for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1); for (j = 0; j < s->selectorMtf[i]; j++) bsW(s,1,1);
bsW(s,1,0); bsW(s,1,0);
} }
@@ -591,14 +591,14 @@ void sendMTFValues ( EState* s )
gs = 0; gs = 0;
while (True) { while (True) {
if (gs >= s->nMTF) break; if (gs >= s->nMTF) break;
ge = gs + BZ_G_SIZE - 1; ge = gs + BZ_G_SIZE - 1;
if (ge >= s->nMTF) ge = s->nMTF-1; if (ge >= s->nMTF) ge = s->nMTF-1;
AssertH ( s->selector[selCtr] < nGroups, 3006 ); AssertH ( s->selector[selCtr] < nGroups, 3006 );
if (nGroups == 6 && 50 == ge-gs+1) { if (nGroups == 6 && 50 == ge-gs+1) {
/*--- fast track the common case ---*/ /*--- fast track the common case ---*/
UInt16 mtfv_i; UInt16 mtfv_i;
UChar* s_len_sel_selCtr UChar* s_len_sel_selCtr
= &(s->len[s->selector[selCtr]][0]); = &(s->len[s->selector[selCtr]][0]);
Int32* s_code_sel_selCtr Int32* s_code_sel_selCtr
= &(s->code[s->selector[selCtr]][0]); = &(s->code[s->selector[selCtr]][0]);
@@ -623,9 +623,9 @@ void sendMTFValues ( EState* s )
# undef BZ_ITAH # undef BZ_ITAH
} else { } else {
/*--- slow version which correctly handles all situations ---*/ /*--- slow version which correctly handles all situations ---*/
for (i = gs; i <= ge; i++) { for (i = gs; i <= ge; i++) {
bsW ( s, bsW ( s,
s->len [s->selector[selCtr]] [mtfv[i]], s->len [s->selector[selCtr]] [mtfv[i]],
s->code [s->selector[selCtr]] [mtfv[i]] ); s->code [s->selector[selCtr]] [mtfv[i]] );
} }
@@ -680,8 +680,8 @@ void BZ2_compressBlock ( EState* s, Bool is_last_block )
/*-- Now the block's CRC, so it is in a known place. --*/ /*-- Now the block's CRC, so it is in a known place. --*/
bsPutUInt32 ( s, s->blockCRC ); bsPutUInt32 ( s, s->blockCRC );
/*-- /*--
Now a single bit indicating (non-)randomisation. Now a single bit indicating (non-)randomisation.
As of version 0.9.5, we use a better sorting algorithm As of version 0.9.5, we use a better sorting algorithm
which makes randomisation unnecessary. So always set which makes randomisation unnecessary. So always set
the randomised bit to 'no'. Of course, the decoder the randomised bit to 'no'. Of course, the decoder
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -167,7 +167,7 @@ Int32 BZ2_decompress ( DState* s )
Int32 N; Int32 N;
Int32 curr; Int32 curr;
Int32 zt; Int32 zt;
Int32 zn; Int32 zn;
Int32 zvec; Int32 zvec;
Int32 zj; Int32 zj;
Int32 gSel; Int32 gSel;
@@ -221,7 +221,7 @@ Int32 BZ2_decompress ( DState* s )
N = s->save_N; N = s->save_N;
curr = s->save_curr; curr = s->save_curr;
zt = s->save_zt; zt = s->save_zt;
zn = s->save_zn; zn = s->save_zn;
zvec = s->save_zvec; zvec = s->save_zvec;
zj = s->save_zj; zj = s->save_zj;
gSel = s->save_gSel; gSel = s->save_gSel;
@@ -244,14 +244,14 @@ Int32 BZ2_decompress ( DState* s )
if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC); if (uc != BZ_HDR_h) RETURN(BZ_DATA_ERROR_MAGIC);
GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8) GET_BITS(BZ_X_MAGIC_4, s->blockSize100k, 8)
if (s->blockSize100k < (BZ_HDR_0 + 1) || if (s->blockSize100k < (BZ_HDR_0 + 1) ||
s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC); s->blockSize100k > (BZ_HDR_0 + 9)) RETURN(BZ_DATA_ERROR_MAGIC);
s->blockSize100k -= BZ_HDR_0; s->blockSize100k -= BZ_HDR_0;
if (s->smallDecompress) { if (s->smallDecompress) {
s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) ); s->ll16 = BZALLOC( s->blockSize100k * 100000 * sizeof(UInt16) );
s->ll4 = BZALLOC( s->ll4 = BZALLOC(
((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar) ((1 + s->blockSize100k * 100000) >> 1) * sizeof(UChar)
); );
if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR); if (s->ll16 == NULL || s->ll4 == NULL) RETURN(BZ_MEM_ERROR);
} else { } else {
@@ -277,7 +277,7 @@ Int32 BZ2_decompress ( DState* s )
s->currBlockNo++; s->currBlockNo++;
if (s->verbosity >= 2) if (s->verbosity >= 2)
VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo ); VPrintf1 ( "\n [%d: huff+mtf ", s->currBlockNo );
s->storedBlockCRC = 0; s->storedBlockCRC = 0;
GET_UCHAR(BZ_X_BCRC_1, uc); GET_UCHAR(BZ_X_BCRC_1, uc);
s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc); s->storedBlockCRC = (s->storedBlockCRC << 8) | ((UInt32)uc);
@@ -300,14 +300,14 @@ Int32 BZ2_decompress ( DState* s )
if (s->origPtr < 0) if (s->origPtr < 0)
RETURN(BZ_DATA_ERROR); RETURN(BZ_DATA_ERROR);
if (s->origPtr > 10 + 100000*s->blockSize100k) if (s->origPtr > 10 + 100000*s->blockSize100k)
RETURN(BZ_DATA_ERROR); RETURN(BZ_DATA_ERROR);
/*--- Receive the mapping table ---*/ /*--- Receive the mapping table ---*/
for (i = 0; i < 16; i++) { for (i = 0; i < 16; i++) {
GET_BIT(BZ_X_MAPPING_1, uc); GET_BIT(BZ_X_MAPPING_1, uc);
if (uc == 1) if (uc == 1)
s->inUse16[i] = True; else s->inUse16[i] = True; else
s->inUse16[i] = False; s->inUse16[i] = False;
} }
@@ -343,7 +343,7 @@ Int32 BZ2_decompress ( DState* s )
{ {
UChar pos[BZ_N_GROUPS], tmp, v; UChar pos[BZ_N_GROUPS], tmp, v;
for (v = 0; v < nGroups; v++) pos[v] = v; for (v = 0; v < nGroups; v++) pos[v] = v;
for (i = 0; i < nSelectors; i++) { for (i = 0; i < nSelectors; i++) {
v = s->selectorMtf[i]; v = s->selectorMtf[i];
tmp = pos[v]; tmp = pos[v];
@@ -376,10 +376,10 @@ Int32 BZ2_decompress ( DState* s )
if (s->len[t][i] > maxLen) maxLen = s->len[t][i]; if (s->len[t][i] > maxLen) maxLen = s->len[t][i];
if (s->len[t][i] < minLen) minLen = s->len[t][i]; if (s->len[t][i] < minLen) minLen = s->len[t][i];
} }
BZ2_hbCreateDecodeTables ( BZ2_hbCreateDecodeTables (
&(s->limit[t][0]), &(s->limit[t][0]),
&(s->base[t][0]), &(s->base[t][0]),
&(s->perm[t][0]), &(s->perm[t][0]),
&(s->len[t][0]), &(s->len[t][0]),
minLen, maxLen, alphaSize minLen, maxLen, alphaSize
); );
@@ -471,23 +471,23 @@ Int32 BZ2_decompress ( DState* s )
s->mtfa[(z)-3] = s->mtfa[(z)-4]; s->mtfa[(z)-3] = s->mtfa[(z)-4];
nn -= 4; nn -= 4;
} }
while (nn > 0) { while (nn > 0) {
s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--; s->mtfa[(pp+nn)] = s->mtfa[(pp+nn)-1]; nn--;
}; };
s->mtfa[pp] = uc; s->mtfa[pp] = uc;
} else { } else {
/* general case */ /* general case */
lno = nn / MTFL_SIZE; lno = nn / MTFL_SIZE;
off = nn % MTFL_SIZE; off = nn % MTFL_SIZE;
pp = s->mtfbase[lno] + off; pp = s->mtfbase[lno] + off;
uc = s->mtfa[pp]; uc = s->mtfa[pp];
while (pp > s->mtfbase[lno]) { while (pp > s->mtfbase[lno]) {
s->mtfa[pp] = s->mtfa[pp-1]; pp--; s->mtfa[pp] = s->mtfa[pp-1]; pp--;
}; };
s->mtfbase[lno]++; s->mtfbase[lno]++;
while (lno > 0) { while (lno > 0) {
s->mtfbase[lno]--; s->mtfbase[lno]--;
s->mtfa[s->mtfbase[lno]] s->mtfa[s->mtfbase[lno]]
= s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1]; = s->mtfa[s->mtfbase[lno-1] + MTFL_SIZE - 1];
lno--; lno--;
} }
@@ -569,7 +569,7 @@ Int32 BZ2_decompress ( DState* s )
if (s->blockRandomised) { if (s->blockRandomised) {
BZ_RAND_INIT_MASK; BZ_RAND_INIT_MASK;
BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_GET_SMALL(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else { } else {
BZ_GET_SMALL(s->k0); s->nblock_used++; BZ_GET_SMALL(s->k0); s->nblock_used++;
} }
@@ -588,7 +588,7 @@ Int32 BZ2_decompress ( DState* s )
if (s->blockRandomised) { if (s->blockRandomised) {
BZ_RAND_INIT_MASK; BZ_RAND_INIT_MASK;
BZ_GET_FAST(s->k0); s->nblock_used++; BZ_GET_FAST(s->k0); s->nblock_used++;
BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK; BZ_RAND_UPD_MASK; s->k0 ^= BZ_RAND_MASK;
} else { } else {
BZ_GET_FAST(s->k0); s->nblock_used++; BZ_GET_FAST(s->k0); s->nblock_used++;
} }
@@ -657,7 +657,7 @@ Int32 BZ2_decompress ( DState* s )
s->save_gBase = gBase; s->save_gBase = gBase;
s->save_gPerm = gPerm; s->save_gPerm = gPerm;
return retVal; return retVal;
} }
@@ -19,7 +19,7 @@
#ifdef _WIN32 #ifdef _WIN32
#define BZ2_LIBNAME "libbz2-1.0.2.DLL" #define BZ2_LIBNAME "libbz2-1.0.2.DLL"
#include <windows.h> #include <windows.h>
static int BZ2DLLLoaded = 0; static int BZ2DLLLoaded = 0;
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -100,7 +100,7 @@
/*---------------------------------------------------*/ /*---------------------------------------------------*/
void BZ2_hbMakeCodeLengths ( UChar *len, void BZ2_hbMakeCodeLengths ( UChar *len,
Int32 *freq, Int32 *freq,
Int32 alphaSize, Int32 alphaSize,
Int32 maxLen ) Int32 maxLen )
@@ -114,7 +114,7 @@ void BZ2_hbMakeCodeLengths ( UChar *len,
Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ]; Int32 heap [ BZ_MAX_ALPHA_SIZE + 2 ];
Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ]; Int32 weight [ BZ_MAX_ALPHA_SIZE * 2 ];
Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ]; Int32 parent [ BZ_MAX_ALPHA_SIZE * 2 ];
for (i = 0; i < alphaSize; i++) for (i = 0; i < alphaSize; i++)
weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8; weight[i+1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
@@ -136,7 +136,7 @@ void BZ2_hbMakeCodeLengths ( UChar *len,
} }
AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 ); AssertH( nHeap < (BZ_MAX_ALPHA_SIZE+2), 2001 );
while (nHeap > 1) { while (nHeap > 1) {
n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); n1 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1); n2 = heap[1]; heap[1] = heap[nHeap]; nHeap--; DOWNHEAP(1);
@@ -159,7 +159,7 @@ void BZ2_hbMakeCodeLengths ( UChar *len,
len[i-1] = j; len[i-1] = j;
if (j > maxLen) tooLong = True; if (j > maxLen) tooLong = True;
} }
if (! tooLong) break; if (! tooLong) break;
/* 17 Oct 04: keep-going condition for the following loop used /* 17 Oct 04: keep-going condition for the following loop used
@@ -17,16 +17,16 @@
1. Redistributions of source code must retain the above copyright 1. Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer. notice, this list of conditions and the following disclaimer.
2. The origin of this software must not be misrepresented; you must 2. The origin of this software must not be misrepresented; you must
not claim that you wrote the original software. If you use this not claim that you wrote the original software. If you use this
software in a product, an acknowledgment in the product software in a product, an acknowledgment in the product
documentation would be appreciated but is not required. documentation would be appreciated but is not required.
3. Altered source versions must be plainly marked as such, and must 3. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software. not be misrepresented as being the original software.
4. The name of the author may not be used to endorse or promote 4. The name of the author may not be used to endorse or promote
products derived from this software without specific prior written products derived from this software without specific prior written
permission. permission.
THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS
@@ -63,58 +63,58 @@
/*---------------------------------------------*/ /*---------------------------------------------*/
Int32 BZ2_rNums[512] = { Int32 BZ2_rNums[512] = {
619, 720, 127, 481, 931, 816, 813, 233, 566, 247, 619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
985, 724, 205, 454, 863, 491, 741, 242, 949, 214, 985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
733, 859, 335, 708, 621, 574, 73, 654, 730, 472, 733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
419, 436, 278, 496, 867, 210, 399, 680, 480, 51, 419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
878, 465, 811, 169, 869, 675, 611, 697, 867, 561, 878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
862, 687, 507, 283, 482, 129, 807, 591, 733, 623, 862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
150, 238, 59, 379, 684, 877, 625, 169, 643, 105, 150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
170, 607, 520, 932, 727, 476, 693, 425, 174, 647, 170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
73, 122, 335, 530, 442, 853, 695, 249, 445, 515, 73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
909, 545, 703, 919, 874, 474, 882, 500, 594, 612, 909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
641, 801, 220, 162, 819, 984, 589, 513, 495, 799, 641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
161, 604, 958, 533, 221, 400, 386, 867, 600, 782, 161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
382, 596, 414, 171, 516, 375, 682, 485, 911, 276, 382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
98, 553, 163, 354, 666, 933, 424, 341, 533, 870, 98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
227, 730, 475, 186, 263, 647, 537, 686, 600, 224, 227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
469, 68, 770, 919, 190, 373, 294, 822, 808, 206, 469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
184, 943, 795, 384, 383, 461, 404, 758, 839, 887, 184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
715, 67, 618, 276, 204, 918, 873, 777, 604, 560, 715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
951, 160, 578, 722, 79, 804, 96, 409, 713, 940, 951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
652, 934, 970, 447, 318, 353, 859, 672, 112, 785, 652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
645, 863, 803, 350, 139, 93, 354, 99, 820, 908, 645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
609, 772, 154, 274, 580, 184, 79, 626, 630, 742, 609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
653, 282, 762, 623, 680, 81, 927, 626, 789, 125, 653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
411, 521, 938, 300, 821, 78, 343, 175, 128, 250, 411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
170, 774, 972, 275, 999, 639, 495, 78, 352, 126, 170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
857, 956, 358, 619, 580, 124, 737, 594, 701, 612, 857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
669, 112, 134, 694, 363, 992, 809, 743, 168, 974, 669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
944, 375, 748, 52, 600, 747, 642, 182, 862, 81, 944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
344, 805, 988, 739, 511, 655, 814, 334, 249, 515, 344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
897, 955, 664, 981, 649, 113, 974, 459, 893, 228, 897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
433, 837, 553, 268, 926, 240, 102, 654, 459, 51, 433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
686, 754, 806, 760, 493, 403, 415, 394, 687, 700, 686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
946, 670, 656, 610, 738, 392, 760, 799, 887, 653, 946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
978, 321, 576, 617, 626, 502, 894, 679, 243, 440, 978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
680, 879, 194, 572, 640, 724, 926, 56, 204, 700, 680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
707, 151, 457, 449, 797, 195, 791, 558, 945, 679, 707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
297, 59, 87, 824, 713, 663, 412, 693, 342, 606, 297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
134, 108, 571, 364, 631, 212, 174, 643, 304, 329, 134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
343, 97, 430, 751, 497, 314, 983, 374, 822, 928, 343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
140, 206, 73, 263, 980, 736, 876, 478, 430, 305, 140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
170, 514, 364, 692, 829, 82, 855, 953, 676, 246, 170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
369, 970, 294, 750, 807, 827, 150, 790, 288, 923, 369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
804, 378, 215, 828, 592, 281, 565, 555, 710, 82, 804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
896, 831, 547, 261, 524, 462, 293, 465, 502, 56, 896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
661, 821, 976, 991, 658, 869, 905, 758, 745, 193, 661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
768, 550, 608, 933, 378, 286, 215, 979, 792, 961, 768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
61, 688, 793, 644, 986, 403, 106, 366, 905, 644, 61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
372, 567, 466, 434, 645, 210, 389, 550, 919, 135, 372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
780, 773, 635, 389, 707, 100, 626, 958, 165, 504, 780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
920, 176, 193, 713, 857, 265, 203, 50, 668, 108, 920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
645, 990, 626, 197, 510, 357, 358, 850, 858, 364, 645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
936, 638 936, 638
}; };
@@ -4,7 +4,7 @@
support for large files (> 2GB) in a reasonable amount of time. support for large files (> 2GB) in a reasonable amount of time.
I suggest you use the undocumented --exponential option to I suggest you use the undocumented --exponential option to
bzip2 when compressing the resulting file; this saves a bit of bzip2 when compressing the resulting file; this saves a bit of
time. Note: *don't* bother with --exponential when compressing time. Note: *don't* bother with --exponential when compressing
Real Files; it'll just waste a lot of CPU time :-) Real Files; it'll just waste a lot of CPU time :-)
(but is otherwise harmless). (but is otherwise harmless).
*/ */
@@ -1,11 +1,11 @@
/* A test program written to test robustness to decompression of /* A test program written to test robustness to decompression of
corrupted data. Usage is corrupted data. Usage is
unzcrash filename unzcrash filename
and the program will read the specified file, compress it (in memory), and the program will read the specified file, compress it (in memory),
and then repeatedly decompress it, each time with a different bit of and then repeatedly decompress it, each time with a different bit of
the compressed data inverted, so as to test all possible one-bit errors. the compressed data inverted, so as to test all possible one-bit errors.
This should not cause any invalid memory accesses. If it does, This should not cause any invalid memory accesses. If it does,
I want to know about it! I want to know about it!
p.s. As you can see from the above description, the process is p.s. As you can see from the above description, the process is
@@ -100,9 +100,9 @@ int main ( int argc, char** argv )
return 1; return 1;
} else { } else {
for (i = 0; i < nOut; i++) for (i = 0; i < nOut; i++)
if (inbuf[i] != outbuf[i]) { if (inbuf[i] != outbuf[i]) {
fprintf(stderr, "mismatch at %d\n", i ); fprintf(stderr, "mismatch at %d\n", i );
return 1; return 1;
} }
if (i == nOut) fprintf(stderr, "really ok!\n" ); if (i == nOut) fprintf(stderr, "really ok!\n" );
} }
File diff suppressed because it is too large Load Diff
@@ -9,67 +9,67 @@
/* 03.05.03 2.00 Lad Added compression */ /* 03.05.03 2.00 Lad Added compression */
/* 08.12.03 2.01 Dan High-memory handling (> 0x80000000) */ /* 08.12.03 2.01 Dan High-memory handling (> 0x80000000) */
/*****************************************************************************/ /*****************************************************************************/
#ifndef __HUFFMAN_H__ #ifndef __HUFFMAN_H__
#define __HUFFMAN_H__ #define __HUFFMAN_H__
#include "../StormPort.h" #include "../StormPort.h"
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Defines // Defines
#define INSERT_ITEM 1 #define INSERT_ITEM 1
#define SWITCH_ITEMS 2 // Switch the item1 and item2 #define SWITCH_ITEMS 2 // Switch the item1 and item2
#define PTR_NOT(ptr) (THTreeItem *)(~(DWORD_PTR)(ptr)) #define PTR_NOT(ptr) (THTreeItem *)(~(DWORD_PTR)(ptr))
#define PTR_PTR(ptr) ((THTreeItem *)(ptr)) #define PTR_PTR(ptr) ((THTreeItem *)(ptr))
#define PTR_INT(ptr) (LONG_PTR)(ptr) #define PTR_INT(ptr) (LONG_PTR)(ptr)
#ifndef NULL #ifndef NULL
#define NULL 0 #define NULL 0
#endif #endif
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Structures and classes // Structures and classes
// Input stream for Huffmann decompression // Input stream for Huffmann decompression
class TInputStream class TInputStream
{ {
public: public:
unsigned long GetBit(); unsigned long GetBit();
unsigned long Get7Bits(); unsigned long Get7Bits();
unsigned long Get8Bits(); unsigned long Get8Bits();
unsigned char * pbInBuffer; // 00 - Input data unsigned char * pbInBuffer; // 00 - Input data
unsigned long dwBitBuff; // 04 - Input bit buffer unsigned long dwBitBuff; // 04 - Input bit buffer
unsigned int nBits; // 08 - Number of bits remaining in 'dwValue' unsigned int nBits; // 08 - Number of bits remaining in 'dwValue'
}; };
// Output stream for Huffmann compression // Output stream for Huffmann compression
class TOutputStream class TOutputStream
{ {
public: public:
void PutBits(unsigned long dwBuff, unsigned int nPutBits); void PutBits(unsigned long dwBuff, unsigned int nPutBits);
unsigned char * pbOutBuffer; // 00 : Output buffer unsigned char * pbOutBuffer; // 00 : Output buffer
unsigned long dwOutSize; // 04 : Size of output buffer unsigned long dwOutSize; // 04 : Size of output buffer
unsigned char * pbOutPos; // 08 : Current output position unsigned char * pbOutPos; // 08 : Current output position
unsigned long dwBitBuff; // 0C : Bit buffer unsigned long dwBitBuff; // 0C : Bit buffer
unsigned long nBits; // 10 : Number of bits in the bit buffer unsigned long nBits; // 10 : Number of bits in the bit buffer
}; };
// Huffmann tree item (?) // Huffmann tree item (?)
struct THTreeItem struct THTreeItem
{ {
public: public:
THTreeItem * Call1501DB70(THTreeItem * pLast); THTreeItem * Call1501DB70(THTreeItem * pLast);
THTreeItem * GetPrevItem(LONG_PTR value); THTreeItem * GetPrevItem(LONG_PTR value);
void ClearItemLinks(); void ClearItemLinks();
void RemoveItem(); void RemoveItem();
THTreeItem * next; // 00 - Pointer to next THTreeItem THTreeItem * next; // 00 - Pointer to next THTreeItem
THTreeItem * prev; // 04 - Pointer to prev THTreeItem (< 0 if none) THTreeItem * prev; // 04 - Pointer to prev THTreeItem (< 0 if none)
unsigned long dcmpByte; // 08 - Index of this item in item pointer array, decompressed byte value unsigned long dcmpByte; // 08 - Index of this item in item pointer array, decompressed byte value
@@ -78,7 +78,7 @@ struct THTreeItem
THTreeItem * child; // 14 - Pointer to child THTreeItem THTreeItem * child; // 14 - Pointer to child THTreeItem
int addressMultiplier; // -1 if object on negative address (>0x80000000), +1 if positive int addressMultiplier; // -1 if object on negative address (>0x80000000), +1 if positive
}; };
// Structure used for quick decompress. The 'bitCount' contains number of bits // Structure used for quick decompress. The 'bitCount' contains number of bits
// and byte value contains result decompressed byte value. // and byte value contains result decompressed byte value.
// After each walk through Huffman tree are filled all entries which are // After each walk through Huffman tree are filled all entries which are
@@ -96,48 +96,47 @@ struct TQDecompress
THTreeItem * pItem; // 08 - THTreeItem (if number of bits is greater than 7 THTreeItem * pItem; // 08 - THTreeItem (if number of bits is greater than 7
}; };
}; };
// Structure for Huffman tree (Size 0x3674 bytes). Because I'm not expert // Structure for Huffman tree (Size 0x3674 bytes). Because I'm not expert
// for the decompression, I do not know actually if the class is really a Hufmann // for the decompression, I do not know actually if the class is really a Hufmann
// tree. If someone knows the decompression details, please let me know // tree. If someone knows the decompression details, please let me know
class THuffmannTree class THuffmannTree
{ {
public: public:
THuffmannTree(); THuffmannTree();
void InitTree(bool bCompression); void InitTree(bool bCompression);
void BuildTree(unsigned int nCmpType); void BuildTree(unsigned int nCmpType);
// void ModifyTree(unsigned long dwIndex); // void ModifyTree(unsigned long dwIndex);
// void UninitTree(); // void UninitTree();
// void Call15007010(Bit32 dwInLength, THTreeItem * item); // void Call15007010(Bit32 dwInLength, THTreeItem * item);
THTreeItem * Call1500E740(unsigned int nValue); THTreeItem * Call1500E740(unsigned int nValue);
void Call1500E820(THTreeItem * pItem); void Call1500E820(THTreeItem * pItem);
unsigned int DoCompression(TOutputStream * os, unsigned char * pbInBuffer, int nInLength, int nCmpType); unsigned int DoCompression(TOutputStream * os, unsigned char * pbInBuffer, int nInLength, int nCmpType);
unsigned int DoDecompression(unsigned char * pbOutBuffer, unsigned int dwOutLength, TInputStream * is); unsigned int DoDecompression(unsigned char * pbOutBuffer, unsigned int dwOutLength, TInputStream * is);
unsigned long bIsCmp0; // 0000 - 1 if compression type 0 unsigned long bIsCmp0; // 0000 - 1 if compression type 0
unsigned long offs0004; // 0004 - Some flag unsigned long offs0004; // 0004 - Some flag
THTreeItem items0008[0x203]; // 0008 - HTree items THTreeItem items0008[0x203]; // 0008 - HTree items
//- Sometimes used as HTree item ----------- //- Sometimes used as HTree item -----------
THTreeItem * pItem3050; // 3050 - Always NULL (?) THTreeItem * pItem3050; // 3050 - Always NULL (?)
THTreeItem * pItem3054; // 3054 - Pointer to Huffman tree item THTreeItem * pItem3054; // 3054 - Pointer to Huffman tree item
THTreeItem * pItem3058; // 3058 - Pointer to Huffman tree item (< 0 if invalid) THTreeItem * pItem3058; // 3058 - Pointer to Huffman tree item (< 0 if invalid)
//- Sometimes used as HTree item ----------- //- Sometimes used as HTree item -----------
THTreeItem * pItem305C; // 305C - Usually NULL THTreeItem * pItem305C; // 305C - Usually NULL
THTreeItem * pFirst; // 3060 - Pointer to top (first) Huffman tree item THTreeItem * pFirst; // 3060 - Pointer to top (first) Huffman tree item
THTreeItem * pLast; // 3064 - Pointer to bottom (last) Huffman tree item (< 0 if invalid) THTreeItem * pLast; // 3064 - Pointer to bottom (last) Huffman tree item (< 0 if invalid)
unsigned long nItems; // 3068 - Number of used HTree items unsigned long nItems; // 3068 - Number of used HTree items
//------------------------------------------- //-------------------------------------------
THTreeItem * items306C[0x102]; // 306C - THTreeItem pointer array THTreeItem * items306C[0x102]; // 306C - THTreeItem pointer array
TQDecompress qd3474[0x80]; // 3474 - Array for quick decompression TQDecompress qd3474[0x80]; // 3474 - Array for quick decompression
int addressMultiplier; // -1 if object on negative address (>0x80000000), +1 if positive int addressMultiplier; // -1 if object on negative address (>0x80000000), +1 if positive
static unsigned char Table1502A630[];// Some table static unsigned char Table1502A630[];// Some table
}; };
#endif // __HUFFMAN_H__ #endif // __HUFFMAN_H__
@@ -18,7 +18,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Tables // Tables
static unsigned char DistBits[] = static unsigned char DistBits[] =
{ {
0x02, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x02, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
@@ -26,7 +26,7 @@ static unsigned char DistBits[] =
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08
}; };
static unsigned char DistCode[] = static unsigned char DistCode[] =
{ {
0x03, 0x0D, 0x05, 0x19, 0x09, 0x11, 0x01, 0x3E, 0x1E, 0x2E, 0x0E, 0x36, 0x16, 0x26, 0x06, 0x3A, 0x03, 0x0D, 0x05, 0x19, 0x09, 0x11, 0x01, 0x3E, 0x1E, 0x2E, 0x0E, 0x36, 0x16, 0x26, 0x06, 0x3A,
0x1A, 0x2A, 0x0A, 0x32, 0x12, 0x22, 0x42, 0x02, 0x7C, 0x3C, 0x5C, 0x1C, 0x6C, 0x2C, 0x4C, 0x0C, 0x1A, 0x2A, 0x0A, 0x32, 0x12, 0x22, 0x42, 0x02, 0x7C, 0x3C, 0x5C, 0x1C, 0x6C, 0x2C, 0x4C, 0x0C,
@@ -75,7 +75,7 @@ static unsigned char ChBitsAsc[] =
0x0D, 0x0D, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D 0x0D, 0x0D, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D
}; };
static unsigned short ChCodeAsc[] = static unsigned short ChCodeAsc[] =
{ {
0x0490, 0x0FE0, 0x07E0, 0x0BE0, 0x03E0, 0x0DE0, 0x05E0, 0x09E0, 0x0490, 0x0FE0, 0x07E0, 0x0BE0, 0x03E0, 0x0DE0, 0x05E0, 0x09E0,
0x01E0, 0x00B8, 0x0062, 0x0EE0, 0x06E0, 0x0022, 0x0AE0, 0x02E0, 0x01E0, 0x00B8, 0x0062, 0x0EE0, 0x06E0, 0x0022, 0x0AE0, 0x02E0,
@@ -108,7 +108,7 @@ static unsigned short ChCodeAsc[] =
0x0300, 0x0D40, 0x1D00, 0x0D00, 0x1500, 0x0540, 0x0500, 0x1900, 0x0300, 0x0D40, 0x1D00, 0x0D00, 0x1500, 0x0540, 0x0500, 0x1900,
0x0900, 0x0940, 0x1100, 0x0100, 0x1E00, 0x0E00, 0x0140, 0x1600, 0x0900, 0x0940, 0x1100, 0x0100, 0x1E00, 0x0E00, 0x0140, 0x1600,
0x0600, 0x1A00, 0x0E40, 0x0640, 0x0A40, 0x0A00, 0x1200, 0x0200, 0x0600, 0x1A00, 0x0E40, 0x0640, 0x0A40, 0x0A00, 0x1200, 0x0200,
0x1C00, 0x0C00, 0x1400, 0x0400, 0x1800, 0x0800, 0x1000, 0x0000 0x1C00, 0x0C00, 0x1400, 0x0400, 0x1800, 0x0800, 0x1000, 0x0000
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@@ -266,11 +266,11 @@ static unsigned long DecodeLit(TDcmpStruct * pWork)
{ {
// Skip current bit in the buffer // Skip current bit in the buffer
if(WasteBits(pWork, 1)) if(WasteBits(pWork, 1))
return 0x306; return 0x306;
// The next bits are position in buffers // The next bits are position in buffers
value = pWork->position2[(pWork->bit_buff & 0xFF)]; value = pWork->position2[(pWork->bit_buff & 0xFF)];
// Get number of bits to skip // Get number of bits to skip
if(WasteBits(pWork, pWork->LenBits[value])) if(WasteBits(pWork, pWork->LenBits[value]))
return 0x306; return 0x306;
@@ -337,7 +337,7 @@ static unsigned long DecodeLit(TDcmpStruct * pWork)
} }
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Retrieves the number of bytes to move back // Retrieves the number of bytes to move back
static unsigned long DecodeDist(TDcmpStruct * pWork, unsigned long dwLength) static unsigned long DecodeDist(TDcmpStruct * pWork, unsigned long dwLength)
{ {
@@ -402,7 +402,7 @@ static unsigned long Expand(TDcmpStruct * pWork)
} }
else else
pWork->out_buff[pWork->outputPos++] = (unsigned char)oneByte; pWork->out_buff[pWork->outputPos++] = (unsigned char)oneByte;
// If number of extracted bytes has reached 1/2 of output buffer, // If number of extracted bytes has reached 1/2 of output buffer,
// flush output buffer. // flush output buffer.
if(pWork->outputPos >= 0x2000) if(pWork->outputPos >= 0x2000)
@@ -453,7 +453,7 @@ unsigned int explode(
pWork->in_pos = 3; // Position in input buffer pWork->in_pos = 3; // Position in input buffer
// Test for the valid dictionary size // Test for the valid dictionary size
if(4 > pWork->dsize_bits || pWork->dsize_bits > 6) if(4 > pWork->dsize_bits || pWork->dsize_bits > 6)
return CMP_INVALID_DICTSIZE; return CMP_INVALID_DICTSIZE;
pWork->dsize_mask = 0xFFFF >> (0x10 - pWork->dsize_bits); // Shifted by 'sar' instruction pWork->dsize_mask = 0xFFFF >> (0x10 - pWork->dsize_bits); // Shifted by 'sar' instruction
@@ -475,6 +475,6 @@ unsigned int explode(
GenDecodeTabs(0x40, pWork->DistBits, DistCode, pWork->position1); GenDecodeTabs(0x40, pWork->DistBits, DistCode, pWork->position1);
if(Expand(pWork) != 0x306) if(Expand(pWork) != 0x306)
return CMP_NO_ERROR; return CMP_NO_ERROR;
return CMP_ABORT; return CMP_ABORT;
} }
@@ -28,7 +28,7 @@
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
// Tables // Tables
static unsigned char DistBits[] = static unsigned char DistBits[] =
{ {
0x02, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x02, 0x04, 0x04, 0x05, 0x05, 0x05, 0x05, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06,
0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x06, 0x06, 0x06, 0x06, 0x06, 0x06, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07, 0x07,
@@ -36,7 +36,7 @@ static unsigned char DistBits[] =
0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08, 0x08
}; };
static unsigned char DistCode[] = static unsigned char DistCode[] =
{ {
0x03, 0x0D, 0x05, 0x19, 0x09, 0x11, 0x01, 0x3E, 0x1E, 0x2E, 0x0E, 0x36, 0x16, 0x26, 0x06, 0x3A, 0x03, 0x0D, 0x05, 0x19, 0x09, 0x11, 0x01, 0x3E, 0x1E, 0x2E, 0x0E, 0x36, 0x16, 0x26, 0x06, 0x3A,
0x1A, 0x2A, 0x0A, 0x32, 0x12, 0x22, 0x42, 0x02, 0x7C, 0x3C, 0x5C, 0x1C, 0x6C, 0x2C, 0x4C, 0x0C, 0x1A, 0x2A, 0x0A, 0x32, 0x12, 0x22, 0x42, 0x02, 0x7C, 0x3C, 0x5C, 0x1C, 0x6C, 0x2C, 0x4C, 0x0C,
@@ -79,7 +79,7 @@ static unsigned char ChBitsAsc[] =
0x0D, 0x0D, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D 0x0D, 0x0D, 0x0C, 0x0C, 0x0C, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D, 0x0D
}; };
static unsigned short ChCodeAsc[] = static unsigned short ChCodeAsc[] =
{ {
0x0490, 0x0FE0, 0x07E0, 0x0BE0, 0x03E0, 0x0DE0, 0x05E0, 0x09E0, 0x0490, 0x0FE0, 0x07E0, 0x0BE0, 0x03E0, 0x0DE0, 0x05E0, 0x09E0,
0x01E0, 0x00B8, 0x0062, 0x0EE0, 0x06E0, 0x0022, 0x0AE0, 0x02E0, 0x01E0, 0x00B8, 0x0062, 0x0EE0, 0x06E0, 0x0022, 0x0AE0, 0x02E0,
@@ -112,7 +112,7 @@ static unsigned short ChCodeAsc[] =
0x0300, 0x0D40, 0x1D00, 0x0D00, 0x1500, 0x0540, 0x0500, 0x1900, 0x0300, 0x0D40, 0x1D00, 0x0D00, 0x1500, 0x0540, 0x0500, 0x1900,
0x0900, 0x0940, 0x1100, 0x0100, 0x1E00, 0x0E00, 0x0140, 0x1600, 0x0900, 0x0940, 0x1100, 0x0100, 0x1E00, 0x0E00, 0x0140, 0x1600,
0x0600, 0x1A00, 0x0E40, 0x0640, 0x0A40, 0x0A00, 0x1200, 0x0200, 0x0600, 0x1A00, 0x0E40, 0x0640, 0x0A40, 0x0A00, 0x1200, 0x0200,
0x1C00, 0x0C00, 0x1400, 0x0400, 0x1800, 0x0800, 0x1000, 0x0000 0x1C00, 0x0C00, 0x1400, 0x0400, 0x1800, 0x0800, 0x1000, 0x0000
}; };
//----------------------------------------------------------------------------- //-----------------------------------------------------------------------------
@@ -215,7 +215,7 @@ static void OutputBits(TCmpStruct * pWork, unsigned int nbits, unsigned long bit
{ {
pWork->out_bytes++; pWork->out_bytes++;
bit_buff >>= (8 - out_bits); bit_buff >>= (8 - out_bits);
pWork->out_buff[pWork->out_bytes] = (unsigned char)bit_buff; pWork->out_buff[pWork->out_bytes] = (unsigned char)bit_buff;
pWork->out_bits &= 7; pWork->out_bits &= 7;
} }
@@ -341,7 +341,7 @@ static unsigned long FindRep(TCmpStruct * pWork, unsigned char * srcbuff)
esi = nreps; esi = nreps;
pin27CC = pWork->work_buff + pin49D0[0] + nreps; pin27CC = pWork->work_buff + pin49D0[0] + nreps;
esp14 = pin27CC; esp14 = pin27CC;
for(;;) // 0040268B for(;;) // 0040268B
{ {
esi = pWork->offs09BC[esi]; esi = pWork->offs09BC[esi];
@@ -473,7 +473,7 @@ static void WriteCmpData(TCmpStruct * pWork)
// //
switch(esp20) switch(esp20)
{ {
case 0: case 0:
SortBuffer(pWork, uncmp_begin, uncmp_end + 1); SortBuffer(pWork, uncmp_begin, uncmp_end + 1);
esp20++; esp20++;
if(pWork->dsize_bytes != 0x1000) if(pWork->dsize_bytes != 0x1000)
@@ -590,7 +590,7 @@ unsigned int PKEXPORT implode(
// Initialize the work buffer. This is not in the Pklib, // Initialize the work buffer. This is not in the Pklib,
// but it seems to be a bug. Storm always pre-fills the data with zeros, // but it seems to be a bug. Storm always pre-fills the data with zeros,
// and always compresses one block only. So the bug will not appear. // and always compresses one block only. So the bug will not appear.
// But when a larger data block (size > 0x1000) is compressed, // But when a larger data block (size > 0x1000) is compressed,
// it may fail. // it may fail.
memset(pWork, 0, sizeof(TCmpStruct)); memset(pWork, 0, sizeof(TCmpStruct));
@@ -650,7 +650,7 @@ unsigned int PKEXPORT implode(
for(i = 0; i < 0x10; i++) for(i = 0; i < 0x10; i++)
{ {
int nCount2 = 0; // EBX int nCount2 = 0; // EBX
if((1 << ExLenBits[i]) == 0) if((1 << ExLenBits[i]) == 0)
continue; continue;
@@ -29,7 +29,7 @@
// Define calling convention // Define calling convention
#ifndef PKEXPORT #ifndef PKEXPORT
#define PKEXPORT //__cdecl // Use for normal __cdecl calling #define PKEXPORT //__cdecl // Use for normal __cdecl calling
#endif #endif
//#define PKEXPORT __stdcall //#define PKEXPORT __stdcall
//#define PKEXPORT __fastcall //#define PKEXPORT __fastcall
@@ -40,8 +40,8 @@
// Compression structure // Compression structure
typedef struct typedef struct
{ {
unsigned int offs0000; // 0000 : unsigned int offs0000; // 0000 :
unsigned int out_bytes; // 0004 : # bytes available in out_buff unsigned int out_bytes; // 0004 : # bytes available in out_buff
unsigned int out_bits; // 0008 : # of bits available in the last out byte unsigned int out_bits; // 0008 : # of bits available in the last out byte
unsigned int dsize_bits; // 000C : Dict size : 4=0x400, 5=0x800, 6=0x1000 unsigned int dsize_bits; // 000C : Dict size : 4=0x400, 5=0x800, 6=0x1000
unsigned int dsize_mask; // 0010 : Dict size : 0x0F=0x400, 0x1F=0x800, 0x3F=0x1000 unsigned int dsize_mask; // 0010 : Dict size : 0x0F=0x400, 0x1F=0x800, 0x3F=0x1000
@@ -49,23 +49,23 @@ typedef struct
unsigned int dsize_bytes; // 0018 : Dictionary size in bytes unsigned int dsize_bytes; // 0018 : Dictionary size in bytes
unsigned char dist_bits[0x40]; // 001C : Distance bits unsigned char dist_bits[0x40]; // 001C : Distance bits
unsigned char dist_codes[0x40]; // 005C : Distance codes unsigned char dist_codes[0x40]; // 005C : Distance codes
unsigned char nChBits[0x306]; // 009C : unsigned char nChBits[0x306]; // 009C :
unsigned short nChCodes[0x306]; // 03A2 : unsigned short nChCodes[0x306]; // 03A2 :
unsigned short offs09AE; // 09AE : unsigned short offs09AE; // 09AE :
void * param; // 09B0 : User parameter void * param; // 09B0 : User parameter
unsigned int (*read_buf)(char *buf, unsigned int *size, void *param); // 9B4 unsigned int (*read_buf)(char *buf, unsigned int *size, void *param); // 9B4
void (*write_buf)(char *buf, unsigned int *size, void *param); // 9B8 void (*write_buf)(char *buf, unsigned int *size, void *param); // 9B8
unsigned short offs09BC[0x204]; // 09BC : unsigned short offs09BC[0x204]; // 09BC :
unsigned long offs0DC4; // 0DC4 : unsigned long offs0DC4; // 0DC4 :
unsigned short offs0DC8[0x900]; // 0DC8 : unsigned short offs0DC8[0x900]; // 0DC8 :
unsigned short offs1FC8; // 1FC8 : unsigned short offs1FC8; // 1FC8 :
char out_buff[0x802]; // 1FCA : Output (compressed) data char out_buff[0x802]; // 1FCA : Output (compressed) data
unsigned char work_buff[0x2204]; // 27CC : Work buffer unsigned char work_buff[0x2204]; // 27CC : Work buffer
// + DICT_OFFSET => Dictionary // + DICT_OFFSET => Dictionary
// + UNCMP_OFFSET => Uncompressed data // + UNCMP_OFFSET => Uncompressed data
unsigned short offs49D0[0x2000]; // 49D0 : unsigned short offs49D0[0x2000]; // 49D0 :
} TCmpStruct; } TCmpStruct;
#define CMP_BUFFER_SIZE sizeof(TCmpStruct) // Size of compression buffer #define CMP_BUFFER_SIZE sizeof(TCmpStruct) // Size of compression buffer
@@ -91,15 +91,15 @@ typedef struct
unsigned char in_buff[0x800]; // 2234 - Buffer for data to be decompressed unsigned char in_buff[0x800]; // 2234 - Buffer for data to be decompressed
unsigned char position1[0x100]; // 2A34 - Positions in buffers unsigned char position1[0x100]; // 2A34 - Positions in buffers
unsigned char position2[0x100]; // 2B34 - Positions in buffers unsigned char position2[0x100]; // 2B34 - Positions in buffers
unsigned char offs2C34[0x100]; // 2C34 - Buffer for unsigned char offs2C34[0x100]; // 2C34 - Buffer for
unsigned char offs2D34[0x100]; // 2D34 - Buffer for unsigned char offs2D34[0x100]; // 2D34 - Buffer for
unsigned char offs2E34[0x80]; // 2EB4 - Buffer for unsigned char offs2E34[0x80]; // 2EB4 - Buffer for
unsigned char offs2EB4[0x100]; // 2EB4 - Buffer for unsigned char offs2EB4[0x100]; // 2EB4 - Buffer for
unsigned char ChBitsAsc[0x100]; // 2FB4 - Buffer for unsigned char ChBitsAsc[0x100]; // 2FB4 - Buffer for
unsigned char DistBits[0x40]; // 30B4 - Numbers of bytes to skip copied block length unsigned char DistBits[0x40]; // 30B4 - Numbers of bytes to skip copied block length
unsigned char LenBits[0x10]; // 30F4 - Numbers of bits for skip copied block length unsigned char LenBits[0x10]; // 30F4 - Numbers of bits for skip copied block length
unsigned char ExLenBits[0x10]; // 3104 - Number of valid bits for copied block unsigned char ExLenBits[0x10]; // 3104 - Number of valid bits for copied block
unsigned short LenBase[0x10]; // 3114 - Buffer for unsigned short LenBase[0x10]; // 3114 - Buffer for
} TDcmpStruct; } TDcmpStruct;
#define EXP_BUFFER_SIZE sizeof(TDcmpStruct) // Size of decompress buffer #define EXP_BUFFER_SIZE sizeof(TDcmpStruct) // Size of decompress buffer
@@ -135,4 +135,3 @@ unsigned long PKEXPORT crc32pk(char *buffer, unsigned int *size, unsigned long *
#endif #endif
#endif // __PKLIB_H__ #endif // __PKLIB_H__
@@ -35,8 +35,8 @@ static long Table1503F120[] =
{ {
0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000006, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000006,
0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007, 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007,
0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007, 0xFFFFFFFF, 0x00000001, 0xFFFFFFFF, 0x00000005, 0xFFFFFFFF, 0x00000003, 0xFFFFFFFF, 0x00000007,
0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000006, 0xFFFFFFFF, 0x00000008 0xFFFFFFFF, 0x00000002, 0xFFFFFFFF, 0x00000004, 0xFFFFFFFF, 0x00000006, 0xFFFFFFFF, 0x00000008
}; };
static long Table1503F1A0[] = static long Table1503F1A0[] =
@@ -112,10 +112,10 @@ int CompressWave(unsigned char * pbOutBuffer, int dwOutLength, short * pwInBuffe
nLength = (nLength / 2) - (int)(out.pb - pbOutBuffer); nLength = (nLength / 2) - (int)(out.pb - pbOutBuffer);
nLength = (nLength < 0) ? 0 : nLength; nLength = (nLength < 0) ? 0 : nLength;
nIndex = nChannels - 1; // edi nIndex = nChannels - 1; // edi
nWordsRemains = dwInLength / 2; // eax nWordsRemains = dwInLength / 2; // eax
// ebx - nChannels // ebx - nChannels
// ecx - pwOutPos // ecx - pwOutPos
for(int chnl = nChannels; chnl < nWordsRemains; chnl++) for(int chnl = nChannels; chnl < nWordsRemains; chnl++)
@@ -184,7 +184,7 @@ int CompressWave(unsigned char * pbOutBuffer, int dwOutLength, short * pwInBuffe
} }
if(dwBit == dwStopBit) if(dwBit == dwStopBit)
break; break;
nTableValue >>= 1; nTableValue >>= 1;
} }
@@ -205,7 +205,7 @@ int CompressWave(unsigned char * pbOutBuffer, int dwOutLength, short * pwInBuffe
SInt32Array2[nIndex] = nValue; SInt32Array2[nIndex] = nValue;
*out.pb++ = (unsigned char)(dwBitBuff | ebx); *out.pb++ = (unsigned char)(dwBitBuff | ebx);
nTableValue = Table1503F120[dwBitBuff & 0x1F]; nTableValue = Table1503F120[dwBitBuff & 0x1F];
SInt32Array1[nIndex] = SInt32Array1[nIndex] + nTableValue; SInt32Array1[nIndex] = SInt32Array1[nIndex] + nTableValue;
if(SInt32Array1[nIndex] < 0) if(SInt32Array1[nIndex] < 0)
SInt32Array1[nIndex] = 0; SInt32Array1[nIndex] = 0;
else if(SInt32Array1[nIndex] > 0x58) else if(SInt32Array1[nIndex] > 0x58)
@@ -280,7 +280,7 @@ int DecompressWave(unsigned char * pbOutBuffer, int dwOutLength, unsigned char *
SInt32Array1[nIndex] += 8; SInt32Array1[nIndex] += 8;
if(SInt32Array1[nIndex] > 0x58) if(SInt32Array1[nIndex] > 0x58)
SInt32Array1[nIndex] = 0x58; SInt32Array1[nIndex] = 0x58;
if(nChannels == 2) if(nChannels == 2)
nIndex = (nIndex == 0) ? 1 : 0; nIndex = (nIndex == 0) ? 1 : 0;
break; break;
@@ -354,4 +354,3 @@ int DecompressWave(unsigned char * pbOutBuffer, int dwOutLength, unsigned char *
} }
return (int)(out.pb - pbOutBuffer); return (int)(out.pb - pbOutBuffer);
} }
@@ -20,4 +20,3 @@ int CompressWave (unsigned char * pbOutBuffer, int dwOutLength, short * pwInBu
int DecompressWave(unsigned char * pbOutBuffer, int dwOutLength, unsigned char * pbInBuffer, int dwInLength, int nChannels); int DecompressWave(unsigned char * pbOutBuffer, int dwOutLength, unsigned char * pbInBuffer, int dwInLength, int nChannels);
#endif // __WAVE_H__ #endif // __WAVE_H__
@@ -1,6 +1,6 @@
/* adler32.c -- compute the Adler-32 checksum of a data stream /* adler32.c -- compute the Adler-32 checksum of a data stream
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* @(#) $Id$ */ /* @(#) $Id$ */
@@ -34,12 +34,12 @@ uLong ZEXPORT adler32(adler, buf, len)
len -= k; len -= k;
while (k >= 16) { while (k >= 16) {
DO16(buf); DO16(buf);
buf += 16; buf += 16;
k -= 16; k -= 16;
} }
if (k != 0) do { if (k != 0) do {
s1 += *buf++; s1 += *buf++;
s2 += s1; s2 += s1;
} while (--k); } while (--k);
s1 %= BASE; s1 %= BASE;
s2 %= BASE; s2 %= BASE;
@@ -1,6 +1,6 @@
/* compress.c -- compress a memory buffer /* compress.c -- compress a memory buffer
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* @(#) $Id$ */ /* @(#) $Id$ */
@@ -20,7 +20,7 @@
/* if your C compiler don't add underline before function name, /* if your C compiler don't add underline before function name,
define ADD_UNDERLINE_ASMFUNC */ define ADD_UNDERLINE_ASMFUNC */
#ifdef ADD_UNDERLINE_ASMFUNC #ifdef ADD_UNDERLINE_ASMFUNC
#define longest_match_7fff _longest_match_7fff #define longest_match_7fff _longest_match_7fff
#endif #endif
@@ -46,15 +46,15 @@ uInt longest_match(
deflate_state *s, deflate_state *s,
IPos cur_match) /* current match */ IPos cur_match) /* current match */
{ {
static uInt iIsPPro=2; static uInt iIsPPro=2;
if ((s->w_mask == 0x7fff) && (iIsPPro==0)) if ((s->w_mask == 0x7fff) && (iIsPPro==0))
return longest_match_7fff(s,cur_match); return longest_match_7fff(s,cur_match);
if (iIsPPro==2) if (iIsPPro==2)
iIsPPro = (((cpudetect32()/0x100)&0xf)>=6) ? 1 : 0; iIsPPro = (((cpudetect32()/0x100)&0xf)>=6) ? 1 : 0;
return longest_match_c(s,cur_match); return longest_match_c(s,cur_match);
} }
@@ -15,4 +15,3 @@ USEUNIT("trees.c");
// To add a file to the library use the Project menu 'Add to Project'. // To add a file to the library use the Project menu 'Add to Project'.
@@ -20,4 +20,3 @@ USEUNIT("zutil.c");
// To add a file to the library use the Project menu 'Add to Project'. // To add a file to the library use the Project menu 'Add to Project'.
@@ -40,4 +40,3 @@ int WINAPI DllEntryPoint(HINSTANCE hinst, unsigned long reason, void*)
{ {
return 1; return 1;
} }
@@ -22,4 +22,3 @@ int main() {
return 0; return 0;
} }
@@ -17,7 +17,7 @@ gzfilebuf::~gzfilebuf() {
} }
gzfilebuf *gzfilebuf::open( const char *name, gzfilebuf *gzfilebuf::open( const char *name,
int io_mode ) { int io_mode ) {
if ( is_open() ) if ( is_open() )
return NULL; return NULL;
@@ -58,7 +58,7 @@ gzfilebuf *gzfilebuf::open( const char *name,
} }
gzfilebuf *gzfilebuf::attach( int file_descriptor, gzfilebuf *gzfilebuf::attach( int file_descriptor,
int io_mode ) { int io_mode ) {
if ( is_open() ) if ( is_open() )
return NULL; return NULL;
@@ -151,7 +151,7 @@ int gzfilebuf::underflow() {
if ( out_waiting() ) { if ( out_waiting() ) {
if ( flushbuf() == EOF ) if ( flushbuf() == EOF )
return EOF; return EOF;
} }
} }
@@ -180,11 +180,11 @@ int gzfilebuf::overflow( int c ) {
setg(0,0,0); setg(0,0,0);
} else { } else {
if (in_avail()) { if (in_avail()) {
return EOF; return EOF;
} }
if (out_waiting()) { if (out_waiting()) {
if (flushbuf() == EOF) if (flushbuf() == EOF)
return EOF; return EOF;
} }
} }
@@ -287,7 +287,7 @@ gzfilebuf *gzfilestream_common::rdbuf() {
return &buffer; return &buffer;
} }
gzifstream::gzifstream() : gzifstream::gzifstream() :
ios( gzfilestream_common::rdbuf() ) ios( gzfilestream_common::rdbuf() )
{ {
@@ -327,4 +327,3 @@ gzofstream::gzofstream( int fd, int io_mode ) :
} }
gzofstream::~gzofstream() { } gzofstream::~gzofstream() { }
@@ -99,9 +99,9 @@ private:
}; };
template<class T> gzofstream &operator<<(gzofstream &s, template<class T> gzofstream &operator<<(gzofstream &s,
const gzomanip<T> &m) { const gzomanip<T> &m) {
return (*m.func)(s, m.val); return (*m.func)(s, m.val);
} }
inline gzofstream &setcompressionlevel( gzofstream &s, int l ) { inline gzofstream &setcompressionlevel( gzofstream &s, int l ) {
@@ -140,4 +140,3 @@ inline gzomanip<int> setcompressionstrategy(int l)
@@ -305,4 +305,3 @@ inline ostream& operator<<(ozstream& zs, const T& x) {
} }
#endif #endif
@@ -4,9 +4,9 @@
#include <iomanip.h> #include <iomanip.h>
void main() { void main() {
char h[256] = "Hello"; char h[256] = "Hello";
char* g = "Goodbye"; char* g = "Goodbye";
ozstream out("temp.gz"); ozstream out("temp.gz");
out < "This works well" < h < g; out < "This works well" < h < g;
out.close(); out.close();
@@ -23,4 +23,3 @@ void main() {
delete[] x; delete[] y; delete[] x; delete[] y;
} }
@@ -34,9 +34,9 @@
dosdate : the new date at the MSDos format (4 bytes) dosdate : the new date at the MSDos format (4 bytes)
tmu_date : the SAME new date at the tm_unz format */ tmu_date : the SAME new date at the tm_unz format */
void change_file_date(filename,dosdate,tmu_date) void change_file_date(filename,dosdate,tmu_date)
const char *filename; const char *filename;
uLong dosdate; uLong dosdate;
tm_unz tmu_date; tm_unz tmu_date;
{ {
#ifdef WIN32 #ifdef WIN32
HANDLE hFile; HANDLE hFile;
@@ -75,17 +75,17 @@ void change_file_date(filename,dosdate,tmu_date)
As I don't know well Unix, I wait feedback for the unix portion */ As I don't know well Unix, I wait feedback for the unix portion */
int mymkdir(dirname) int mymkdir(dirname)
const char* dirname; const char* dirname;
{ {
int ret=0; int ret=0;
#ifdef WIN32 #ifdef WIN32
ret = mkdir(dirname); ret = mkdir(dirname);
#else #else
#ifdef unix #ifdef unix
ret = mkdir (dirname,0775); ret = mkdir (dirname,0775);
#endif #endif
#endif #endif
return ret; return ret;
} }
int makedir (newdir) int makedir (newdir)
@@ -93,14 +93,14 @@ int makedir (newdir)
{ {
char *buffer ; char *buffer ;
char *p; char *p;
int len = strlen(newdir); int len = strlen(newdir);
if (len <= 0) if (len <= 0)
return 0; return 0;
buffer = (char*)malloc(len+1); buffer = (char*)malloc(len+1);
strcpy(buffer,newdir); strcpy(buffer,newdir);
if (buffer[len-1] == '/') { if (buffer[len-1] == '/') {
buffer[len-1] = '\0'; buffer[len-1] = '\0';
} }
@@ -135,104 +135,104 @@ int makedir (newdir)
void do_banner() void do_banner()
{ {
printf("MiniUnz 0.15, demo of zLib + Unz package written by Gilles Vollant\n"); printf("MiniUnz 0.15, demo of zLib + Unz package written by Gilles Vollant\n");
printf("more info at http://wwww.winimage/zLibDll/unzip.htm\n\n"); printf("more info at http://wwww.winimage/zLibDll/unzip.htm\n\n");
} }
void do_help() void do_help()
{ {
printf("Usage : miniunz [-exvlo] file.zip [file_to_extract]\n\n") ; printf("Usage : miniunz [-exvlo] file.zip [file_to_extract]\n\n") ;
} }
int do_list(uf) int do_list(uf)
unzFile uf; unzFile uf;
{ {
uLong i; uLong i;
unz_global_info gi; unz_global_info gi;
int err; int err;
err = unzGetGlobalInfo (uf,&gi); err = unzGetGlobalInfo (uf,&gi);
if (err!=UNZ_OK) if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err); printf("error %d with zipfile in unzGetGlobalInfo \n",err);
printf(" Length Method Size Ratio Date Time CRC-32 Name\n"); printf(" Length Method Size Ratio Date Time CRC-32 Name\n");
printf(" ------ ------ ---- ----- ---- ---- ------ ----\n"); printf(" ------ ------ ---- ----- ---- ---- ------ ----\n");
for (i=0;i<gi.number_entry;i++) for (i=0;i<gi.number_entry;i++)
{ {
char filename_inzip[256]; char filename_inzip[256];
unz_file_info file_info; unz_file_info file_info;
uLong ratio=0; uLong ratio=0;
const char *string_method; const char *string_method;
err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
if (err!=UNZ_OK) if (err!=UNZ_OK)
{ {
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err); printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
break; break;
} }
if (file_info.uncompressed_size>0) if (file_info.uncompressed_size>0)
ratio = (file_info.compressed_size*100)/file_info.uncompressed_size; ratio = (file_info.compressed_size*100)/file_info.uncompressed_size;
if (file_info.compression_method==0) if (file_info.compression_method==0)
string_method="Stored"; string_method="Stored";
else else
if (file_info.compression_method==Z_DEFLATED) if (file_info.compression_method==Z_DEFLATED)
{ {
uInt iLevel=(uInt)((file_info.flag & 0x6)/2); uInt iLevel=(uInt)((file_info.flag & 0x6)/2);
if (iLevel==0) if (iLevel==0)
string_method="Defl:N"; string_method="Defl:N";
else if (iLevel==1) else if (iLevel==1)
string_method="Defl:X"; string_method="Defl:X";
else if ((iLevel==2) || (iLevel==3)) else if ((iLevel==2) || (iLevel==3))
string_method="Defl:F"; /* 2:fast , 3 : extra fast*/ string_method="Defl:F"; /* 2:fast , 3 : extra fast*/
} }
else else
string_method="Unkn. "; string_method="Unkn. ";
printf("%7lu %6s %7lu %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n", printf("%7lu %6s %7lu %3lu%% %2.2lu-%2.2lu-%2.2lu %2.2lu:%2.2lu %8.8lx %s\n",
file_info.uncompressed_size,string_method,file_info.compressed_size, file_info.uncompressed_size,string_method,file_info.compressed_size,
ratio, ratio,
(uLong)file_info.tmu_date.tm_mon + 1, (uLong)file_info.tmu_date.tm_mon + 1,
(uLong)file_info.tmu_date.tm_mday, (uLong)file_info.tmu_date.tm_mday,
(uLong)file_info.tmu_date.tm_year % 100, (uLong)file_info.tmu_date.tm_year % 100,
(uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min, (uLong)file_info.tmu_date.tm_hour,(uLong)file_info.tmu_date.tm_min,
(uLong)file_info.crc,filename_inzip); (uLong)file_info.crc,filename_inzip);
if ((i+1)<gi.number_entry) if ((i+1)<gi.number_entry)
{ {
err = unzGoToNextFile(uf); err = unzGoToNextFile(uf);
if (err!=UNZ_OK) if (err!=UNZ_OK)
{ {
printf("error %d with zipfile in unzGoToNextFile\n",err); printf("error %d with zipfile in unzGoToNextFile\n",err);
break; break;
} }
} }
} }
return 0; return 0;
} }
int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite) int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite)
unzFile uf; unzFile uf;
const int* popt_extract_without_path; const int* popt_extract_without_path;
int* popt_overwrite; int* popt_overwrite;
{ {
char filename_inzip[256]; char filename_inzip[256];
char* filename_withoutpath; char* filename_withoutpath;
char* p; char* p;
int err=UNZ_OK; int err=UNZ_OK;
FILE *fout=NULL; FILE *fout=NULL;
void* buf; void* buf;
uInt size_buf; uInt size_buf;
unz_file_info file_info;
uLong ratio=0;
err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0);
unz_file_info file_info; if (err!=UNZ_OK)
uLong ratio=0; {
err = unzGetCurrentFileInfo(uf,&file_info,filename_inzip,sizeof(filename_inzip),NULL,0,NULL,0); printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
return err;
if (err!=UNZ_OK) }
{
printf("error %d with zipfile in unzGetCurrentFileInfo\n",err);
return err;
}
size_buf = WRITEBUFFERSIZE; size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf); buf = (void*)malloc(size_buf);
@@ -242,71 +242,71 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite)
return UNZ_INTERNALERROR; return UNZ_INTERNALERROR;
} }
p = filename_withoutpath = filename_inzip; p = filename_withoutpath = filename_inzip;
while ((*p) != '\0') while ((*p) != '\0')
{ {
if (((*p)=='/') || ((*p)=='\\')) if (((*p)=='/') || ((*p)=='\\'))
filename_withoutpath = p+1; filename_withoutpath = p+1;
p++; p++;
} }
if ((*filename_withoutpath)=='\0') if ((*filename_withoutpath)=='\0')
{ {
if ((*popt_extract_without_path)==0) if ((*popt_extract_without_path)==0)
{ {
printf("creating directory: %s\n",filename_inzip); printf("creating directory: %s\n",filename_inzip);
mymkdir(filename_inzip); mymkdir(filename_inzip);
} }
} }
else else
{ {
const char* write_filename; const char* write_filename;
int skip=0; int skip=0;
if ((*popt_extract_without_path)==0) if ((*popt_extract_without_path)==0)
write_filename = filename_inzip; write_filename = filename_inzip;
else else
write_filename = filename_withoutpath; write_filename = filename_withoutpath;
err = unzOpenCurrentFile(uf); err = unzOpenCurrentFile(uf);
if (err!=UNZ_OK) if (err!=UNZ_OK)
{ {
printf("error %d with zipfile in unzOpenCurrentFile\n",err); printf("error %d with zipfile in unzOpenCurrentFile\n",err);
} }
if (((*popt_overwrite)==0) && (err==UNZ_OK)) if (((*popt_overwrite)==0) && (err==UNZ_OK))
{ {
char rep; char rep;
FILE* ftestexist; FILE* ftestexist;
ftestexist = fopen(write_filename,"rb"); ftestexist = fopen(write_filename,"rb");
if (ftestexist!=NULL) if (ftestexist!=NULL)
{ {
fclose(ftestexist); fclose(ftestexist);
do do
{ {
char answer[128]; char answer[128];
printf("The file %s exist. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename); printf("The file %s exist. Overwrite ? [y]es, [n]o, [A]ll: ",write_filename);
scanf("%1s",answer); scanf("%1s",answer);
rep = answer[0] ; rep = answer[0] ;
if ((rep>='a') && (rep<='z')) if ((rep>='a') && (rep<='z'))
rep -= 0x20; rep -= 0x20;
} }
while ((rep!='Y') && (rep!='N') && (rep!='A')); while ((rep!='Y') && (rep!='N') && (rep!='A'));
} }
if (rep == 'N') if (rep == 'N')
skip = 1; skip = 1;
if (rep == 'A') if (rep == 'A')
*popt_overwrite=1; *popt_overwrite=1;
} }
if ((skip==0) && (err==UNZ_OK)) if ((skip==0) && (err==UNZ_OK))
{ {
fout=fopen(write_filename,"wb"); fout=fopen(write_filename,"wb");
/* some zipfile don't contain directory alone before file */ /* some zipfile don't contain directory alone before file */
if ((fout==NULL) && ((*popt_extract_without_path)==0) && if ((fout==NULL) && ((*popt_extract_without_path)==0) &&
(filename_withoutpath!=(char*)filename_inzip)) (filename_withoutpath!=(char*)filename_inzip))
{ {
char c=*(filename_withoutpath-1); char c=*(filename_withoutpath-1);
@@ -316,94 +316,94 @@ int do_extract_currentfile(uf,popt_extract_without_path,popt_overwrite)
fout=fopen(write_filename,"wb"); fout=fopen(write_filename,"wb");
} }
if (fout==NULL) if (fout==NULL)
{ {
printf("error opening %s\n",write_filename); printf("error opening %s\n",write_filename);
} }
} }
if (fout!=NULL) if (fout!=NULL)
{ {
printf(" extracting: %s\n",write_filename); printf(" extracting: %s\n",write_filename);
do do
{ {
err = unzReadCurrentFile(uf,buf,size_buf); err = unzReadCurrentFile(uf,buf,size_buf);
if (err<0) if (err<0)
{ {
printf("error %d with zipfile in unzReadCurrentFile\n",err); printf("error %d with zipfile in unzReadCurrentFile\n",err);
break; break;
} }
if (err>0) if (err>0)
if (fwrite(buf,err,1,fout)!=1) if (fwrite(buf,err,1,fout)!=1)
{ {
printf("error in writing extracted file\n"); printf("error in writing extracted file\n");
err=UNZ_ERRNO; err=UNZ_ERRNO;
break; break;
} }
} }
while (err>0); while (err>0);
fclose(fout); fclose(fout);
if (err==0) if (err==0)
change_file_date(write_filename,file_info.dosDate, change_file_date(write_filename,file_info.dosDate,
file_info.tmu_date); file_info.tmu_date);
} }
if (err==UNZ_OK) if (err==UNZ_OK)
{ {
err = unzCloseCurrentFile (uf); err = unzCloseCurrentFile (uf);
if (err!=UNZ_OK) if (err!=UNZ_OK)
{ {
printf("error %d with zipfile in unzCloseCurrentFile\n",err); printf("error %d with zipfile in unzCloseCurrentFile\n",err);
} }
} }
else else
unzCloseCurrentFile(uf); /* don't lose the error */ unzCloseCurrentFile(uf); /* don't lose the error */
} }
free(buf); free(buf);
return err; return err;
} }
int do_extract(uf,opt_extract_without_path,opt_overwrite) int do_extract(uf,opt_extract_without_path,opt_overwrite)
unzFile uf; unzFile uf;
int opt_extract_without_path; int opt_extract_without_path;
int opt_overwrite; int opt_overwrite;
{ {
uLong i; uLong i;
unz_global_info gi; unz_global_info gi;
int err; int err;
FILE* fout=NULL; FILE* fout=NULL;
err = unzGetGlobalInfo (uf,&gi); err = unzGetGlobalInfo (uf,&gi);
if (err!=UNZ_OK) if (err!=UNZ_OK)
printf("error %d with zipfile in unzGetGlobalInfo \n",err); printf("error %d with zipfile in unzGetGlobalInfo \n",err);
for (i=0;i<gi.number_entry;i++) for (i=0;i<gi.number_entry;i++)
{ {
if (do_extract_currentfile(uf,&opt_extract_without_path, if (do_extract_currentfile(uf,&opt_extract_without_path,
&opt_overwrite) != UNZ_OK) &opt_overwrite) != UNZ_OK)
break; break;
if ((i+1)<gi.number_entry) if ((i+1)<gi.number_entry)
{ {
err = unzGoToNextFile(uf); err = unzGoToNextFile(uf);
if (err!=UNZ_OK) if (err!=UNZ_OK)
{ {
printf("error %d with zipfile in unzGoToNextFile\n",err); printf("error %d with zipfile in unzGoToNextFile\n",err);
break; break;
} }
} }
} }
return 0; return 0;
} }
int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite) int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite)
unzFile uf; unzFile uf;
const char* filename; const char* filename;
int opt_extract_without_path; int opt_extract_without_path;
int opt_overwrite; int opt_overwrite;
{ {
int err = UNZ_OK; int err = UNZ_OK;
@@ -422,87 +422,87 @@ int do_extract_onefile(uf,filename,opt_extract_without_path,opt_overwrite)
int main(argc,argv) int main(argc,argv)
int argc; int argc;
char *argv[]; char *argv[];
{ {
const char *zipfilename=NULL; const char *zipfilename=NULL;
const char *filename_to_extract=NULL; const char *filename_to_extract=NULL;
int i; int i;
int opt_do_list=0; int opt_do_list=0;
int opt_do_extract=1; int opt_do_extract=1;
int opt_do_extract_withoutpath=0; int opt_do_extract_withoutpath=0;
int opt_overwrite=0; int opt_overwrite=0;
char filename_try[512]; char filename_try[512];
unzFile uf=NULL; unzFile uf=NULL;
do_banner(); do_banner();
if (argc==1) if (argc==1)
{ {
do_help(); do_help();
exit(0); exit(0);
} }
else else
{ {
for (i=1;i<argc;i++) for (i=1;i<argc;i++)
{ {
if ((*argv[i])=='-') if ((*argv[i])=='-')
{
const char *p=argv[i]+1;
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='l') || (c=='L'))
opt_do_list = 1;
if ((c=='v') || (c=='V'))
opt_do_list = 1;
if ((c=='x') || (c=='X'))
opt_do_extract = 1;
if ((c=='e') || (c=='E'))
opt_do_extract = opt_do_extract_withoutpath = 1;
if ((c=='o') || (c=='O'))
opt_overwrite=1;
}
}
else
{ {
const char *p=argv[i]+1; if (zipfilename == NULL)
zipfilename = argv[i];
while ((*p)!='\0')
{
char c=*(p++);;
if ((c=='l') || (c=='L'))
opt_do_list = 1;
if ((c=='v') || (c=='V'))
opt_do_list = 1;
if ((c=='x') || (c=='X'))
opt_do_extract = 1;
if ((c=='e') || (c=='E'))
opt_do_extract = opt_do_extract_withoutpath = 1;
if ((c=='o') || (c=='O'))
opt_overwrite=1;
}
}
else
{
if (zipfilename == NULL)
zipfilename = argv[i];
else if (filename_to_extract==NULL) else if (filename_to_extract==NULL)
filename_to_extract = argv[i] ; filename_to_extract = argv[i] ;
} }
} }
} }
if (zipfilename!=NULL) if (zipfilename!=NULL)
{ {
strcpy(filename_try,zipfilename); strcpy(filename_try,zipfilename);
uf = unzOpen(zipfilename); uf = unzOpen(zipfilename);
if (uf==NULL) if (uf==NULL)
{ {
strcat(filename_try,".zip"); strcat(filename_try,".zip");
uf = unzOpen(filename_try); uf = unzOpen(filename_try);
} }
} }
if (uf==NULL) if (uf==NULL)
{ {
printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename); printf("Cannot open %s or %s.zip\n",zipfilename,zipfilename);
exit (1); exit (1);
} }
printf("%s opened\n",filename_try); printf("%s opened\n",filename_try);
if (opt_do_list==1) if (opt_do_list==1)
return do_list(uf); return do_list(uf);
else if (opt_do_extract==1) else if (opt_do_extract==1)
{ {
if (filename_to_extract == NULL) if (filename_to_extract == NULL)
return do_extract(uf,opt_do_extract_withoutpath,opt_overwrite); return do_extract(uf,opt_do_extract_withoutpath,opt_overwrite);
else else
return do_extract_onefile(uf,filename_to_extract, return do_extract_onefile(uf,filename_to_extract,
opt_do_extract_withoutpath,opt_overwrite); opt_do_extract_withoutpath,opt_overwrite);
} }
unzCloseCurrentFile(uf); unzCloseCurrentFile(uf);
return 0; /* to avoid warning */ return 0; /* to avoid warning */
} }
@@ -55,7 +55,7 @@ uLong filetime(f, tmzip, dt)
struct stat s; /* results of stat() */ struct stat s; /* results of stat() */
struct tm* filedate; struct tm* filedate;
time_t tm_t=0; time_t tm_t=0;
if (strcmp(f,"-")!=0) if (strcmp(f,"-")!=0)
{ {
char name[MAXFILENAME]; char name[MAXFILENAME];
@@ -98,10 +98,10 @@ uLong filetime(f, tmzip, dt)
int check_exist_file(filename) int check_exist_file(filename)
const char* filename; const char* filename;
{ {
FILE* ftestexist; FILE* ftestexist;
int ret = 1; int ret = 1;
ftestexist = fopen(filename,"rb"); ftestexist = fopen(filename,"rb");
if (ftestexist==NULL) if (ftestexist==NULL)
ret = 0; ret = 0;
else else
fclose(ftestexist); fclose(ftestexist);
@@ -110,59 +110,59 @@ int check_exist_file(filename)
void do_banner() void do_banner()
{ {
printf("MiniZip 0.15, demo of zLib + Zip package written by Gilles Vollant\n"); printf("MiniZip 0.15, demo of zLib + Zip package written by Gilles Vollant\n");
printf("more info at http://wwww.winimage/zLibDll/unzip.htm\n\n"); printf("more info at http://wwww.winimage/zLibDll/unzip.htm\n\n");
} }
void do_help() void do_help()
{ {
printf("Usage : minizip [-o] file.zip [files_to_add]\n\n") ; printf("Usage : minizip [-o] file.zip [files_to_add]\n\n") ;
} }
int main(argc,argv) int main(argc,argv)
int argc; int argc;
char *argv[]; char *argv[];
{ {
int i; int i;
int opt_overwrite=0; int opt_overwrite=0;
int opt_compress_level=Z_DEFAULT_COMPRESSION; int opt_compress_level=Z_DEFAULT_COMPRESSION;
int zipfilenamearg = 0; int zipfilenamearg = 0;
char filename_try[MAXFILENAME]; char filename_try[MAXFILENAME];
int zipok; int zipok;
int err=0; int err=0;
int size_buf=0; int size_buf=0;
void* buf=NULL, void* buf=NULL,
do_banner(); do_banner();
if (argc==1) if (argc==1)
{ {
do_help(); do_help();
exit(0); exit(0);
return 0; return 0;
} }
else else
{ {
for (i=1;i<argc;i++) for (i=1;i<argc;i++)
{ {
if ((*argv[i])=='-') if ((*argv[i])=='-')
{ {
const char *p=argv[i]+1; const char *p=argv[i]+1;
while ((*p)!='\0') while ((*p)!='\0')
{ {
char c=*(p++);; char c=*(p++);;
if ((c=='o') || (c=='O')) if ((c=='o') || (c=='O'))
opt_overwrite = 1; opt_overwrite = 1;
if ((c>='0') && (c<='9')) if ((c>='0') && (c<='9'))
opt_compress_level = c-'0'; opt_compress_level = c-'0';
} }
} }
else else
if (zipfilenamearg == 0) if (zipfilenamearg == 0)
zipfilenamearg = i ; zipfilenamearg = i ;
} }
} }
size_buf = WRITEBUFFERSIZE; size_buf = WRITEBUFFERSIZE;
buf = (void*)malloc(size_buf); buf = (void*)malloc(size_buf);
@@ -172,15 +172,15 @@ int main(argc,argv)
return ZIP_INTERNALERROR; return ZIP_INTERNALERROR;
} }
if (zipfilenamearg==0) if (zipfilenamearg==0)
zipok=0; zipok=0;
else else
{ {
int i,len; int i,len;
int dot_found=0; int dot_found=0;
zipok = 1 ; zipok = 1 ;
strcpy(filename_try,argv[zipfilenamearg]); strcpy(filename_try,argv[zipfilenamearg]);
len=strlen(filename_try); len=strlen(filename_try);
for (i=0;i<len;i++) for (i=0;i<len;i++)
if (filename_try[i]=='.') if (filename_try[i]=='.')
@@ -191,21 +191,21 @@ int main(argc,argv)
if (opt_overwrite==0) if (opt_overwrite==0)
if (check_exist_file(filename_try)!=0) if (check_exist_file(filename_try)!=0)
{ {
char rep; char rep;
do do
{ {
char answer[128]; char answer[128];
printf("The file %s exist. Overwrite ? [y]es, [n]o : ",filename_try); printf("The file %s exist. Overwrite ? [y]es, [n]o : ",filename_try);
scanf("%1s",answer); scanf("%1s",answer);
rep = answer[0] ; rep = answer[0] ;
if ((rep>='a') && (rep<='z')) if ((rep>='a') && (rep<='z'))
rep -= 0x20; rep -= 0x20;
} }
while ((rep!='Y') && (rep!='N')); while ((rep!='Y') && (rep!='N'));
if (rep=='N') if (rep=='N')
zipok = 0; zipok = 0;
} }
} }
if (zipok==1) if (zipok==1)
@@ -218,7 +218,7 @@ int main(argc,argv)
printf("error opening %s\n",filename_try); printf("error opening %s\n",filename_try);
err= ZIP_ERRNO; err= ZIP_ERRNO;
} }
else else
printf("creating %s\n",filename_try); printf("creating %s\n",filename_try);
for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++) for (i=zipfilenamearg+1;(i<argc) && (err==ZIP_OK);i++)
@@ -230,7 +230,7 @@ int main(argc,argv)
const char* filenameinzip = argv[i]; const char* filenameinzip = argv[i];
zip_fileinfo zi; zip_fileinfo zi;
zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour = zi.tmz_date.tm_sec = zi.tmz_date.tm_min = zi.tmz_date.tm_hour =
zi.tmz_date.tm_mday = zi.tmz_date.tm_min = zi.tmz_date.tm_year = 0; zi.tmz_date.tm_mday = zi.tmz_date.tm_min = zi.tmz_date.tm_year = 0;
zi.dosDate = 0; zi.dosDate = 0;
zi.internal_fa = 0; zi.internal_fa = 0;
@@ -275,7 +275,7 @@ int main(argc,argv)
printf("error in writing %s in the zipfile\n", printf("error in writing %s in the zipfile\n",
filenameinzip); filenameinzip);
} }
} }
} while ((err == ZIP_OK) && (size_read>0)); } while ((err == ZIP_OK) && (size_read>0));
@@ -283,7 +283,7 @@ int main(argc,argv)
if (err<0) if (err<0)
err=ZIP_ERRNO; err=ZIP_ERRNO;
else else
{ {
err = zipCloseFileInZip(zf); err = zipCloseFileInZip(zf);
if (err!=ZIP_OK) if (err!=ZIP_OK)
printf("error in closing %s in the zipfile\n", printf("error in closing %s in the zipfile\n",
@@ -298,5 +298,5 @@ int main(argc,argv)
free(buf); free(buf);
exit(0); exit(0);
return 0; /* to avoid warning */ return 0; /* to avoid warning */
} }
File diff suppressed because it is too large Load Diff
@@ -1,4 +1,4 @@
/* unzip.h -- IO for uncompress .zip files using zlib /* unzip.h -- IO for uncompress .zip files using zlib
Version 0.15 beta, Mar 19th, 1998, Version 0.15 beta, Mar 19th, 1998,
Copyright (C) 1998 Gilles Vollant Copyright (C) 1998 Gilles Vollant
@@ -33,7 +33,7 @@
*/ */
/* for more info about .ZIP format, see /* for more info about .ZIP format, see
ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
PkWare has also a specification at : PkWare has also a specification at :
ftp://ftp.pkware.com/probdesc.zip */ ftp://ftp.pkware.com/probdesc.zip */
@@ -52,7 +52,7 @@ extern "C" {
#if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP) #if defined(STRICTUNZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted /* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */ from (void*) without cast */
typedef struct TagunzFile__ { int unused; } unzFile__; typedef struct TagunzFile__ { int unused; } unzFile__;
typedef unzFile__ *unzFile; typedef unzFile__ *unzFile;
#else #else
typedef voidp unzFile; typedef voidp unzFile;
@@ -69,23 +69,23 @@ typedef voidp unzFile;
#define UNZ_CRCERROR (-105) #define UNZ_CRCERROR (-105)
/* tm_unz contain date/time info */ /* tm_unz contain date/time info */
typedef struct tm_unz_s typedef struct tm_unz_s
{ {
uInt tm_sec; /* seconds after the minute - [0,59] */ uInt tm_sec; /* seconds after the minute - [0,59] */
uInt tm_min; /* minutes after the hour - [0,59] */ uInt tm_min; /* minutes after the hour - [0,59] */
uInt tm_hour; /* hours since midnight - [0,23] */ uInt tm_hour; /* hours since midnight - [0,23] */
uInt tm_mday; /* day of the month - [1,31] */ uInt tm_mday; /* day of the month - [1,31] */
uInt tm_mon; /* months since January - [0,11] */ uInt tm_mon; /* months since January - [0,11] */
uInt tm_year; /* years - [1980..2044] */ uInt tm_year; /* years - [1980..2044] */
} tm_unz; } tm_unz;
/* unz_global_info structure contain global data about the ZIPfile /* unz_global_info structure contain global data about the ZIPfile
These data comes from the end of central dir */ These data comes from the end of central dir */
typedef struct unz_global_info_s typedef struct unz_global_info_s
{ {
uLong number_entry; /* total number of entries in uLong number_entry; /* total number of entries in
the central dir on this disk */ the central dir on this disk */
uLong size_comment; /* size of the global comment of the zipfile */ uLong size_comment; /* size of the global comment of the zipfile */
} unz_global_info; } unz_global_info;
@@ -98,8 +98,8 @@ typedef struct unz_file_info_s
uLong compression_method; /* compression method 2 bytes */ uLong compression_method; /* compression method 2 bytes */
uLong dosDate; /* last mod file date in Dos fmt 4 bytes */ uLong dosDate; /* last mod file date in Dos fmt 4 bytes */
uLong crc; /* crc-32 4 bytes */ uLong crc; /* crc-32 4 bytes */
uLong compressed_size; /* compressed size 4 bytes */ uLong compressed_size; /* compressed size 4 bytes */
uLong uncompressed_size; /* uncompressed size 4 bytes */ uLong uncompressed_size; /* uncompressed size 4 bytes */
uLong size_filename; /* filename length 2 bytes */ uLong size_filename; /* filename length 2 bytes */
uLong size_file_extra; /* extra field length 2 bytes */ uLong size_file_extra; /* extra field length 2 bytes */
uLong size_file_comment; /* file comment length 2 bytes */ uLong size_file_comment; /* file comment length 2 bytes */
@@ -112,15 +112,15 @@ typedef struct unz_file_info_s
} unz_file_info; } unz_file_info;
extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1, extern int ZEXPORT unzStringFileNameCompare OF ((const char* fileName1,
const char* fileName2, const char* fileName2,
int iCaseSensitivity)); int iCaseSensitivity));
/* /*
Compare two filename (fileName1,fileName2). Compare two filename (fileName1,fileName2).
If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp) If iCaseSenisivity = 1, comparision is case sensitivity (like strcmp)
If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi If iCaseSenisivity = 2, comparision is not case sensitivity (like strcmpi
or strcasecmp) or strcasecmp)
If iCaseSenisivity = 0, case sensitivity is defaut of your operating system If iCaseSenisivity = 0, case sensitivity is defaut of your operating system
(like 1 on Unix, 2 on Windows) (like 1 on Unix, 2 on Windows)
*/ */
@@ -128,11 +128,11 @@ extern unzFile ZEXPORT unzOpen OF((const char *path));
/* /*
Open a Zip file. path contain the full pathname (by example, Open a Zip file. path contain the full pathname (by example,
on a Windows NT computer "c:\\zlib\\zlib111.zip" or on an Unix computer on a Windows NT computer "c:\\zlib\\zlib111.zip" or on an Unix computer
"zlib/zlib111.zip". "zlib/zlib111.zip".
If the zipfile cannot be opened (file don't exist or in not valid), the If the zipfile cannot be opened (file don't exist or in not valid), the
return value is NULL. return value is NULL.
Else, the return value is a unzFile Handle, usable with other function Else, the return value is a unzFile Handle, usable with other function
of this unzip package. of this unzip package.
*/ */
extern int ZEXPORT unzClose OF((unzFile file)); extern int ZEXPORT unzClose OF((unzFile file));
@@ -143,7 +143,7 @@ extern int ZEXPORT unzClose OF((unzFile file));
return UNZ_OK if there is no problem. */ return UNZ_OK if there is no problem. */
extern int ZEXPORT unzGetGlobalInfo OF((unzFile file, extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
unz_global_info *pglobal_info)); unz_global_info *pglobal_info));
/* /*
Write info about the ZipFile in the *pglobal_info structure. Write info about the ZipFile in the *pglobal_info structure.
No preparation of the structure is needed No preparation of the structure is needed
@@ -151,8 +151,8 @@ extern int ZEXPORT unzGetGlobalInfo OF((unzFile file,
extern int ZEXPORT unzGetGlobalComment OF((unzFile file, extern int ZEXPORT unzGetGlobalComment OF((unzFile file,
char *szComment, char *szComment,
uLong uSizeBuf)); uLong uSizeBuf));
/* /*
Get the global comment string of the ZipFile, in the szComment buffer. Get the global comment string of the ZipFile, in the szComment buffer.
uSizeBuf is the size of the szComment buffer. uSizeBuf is the size of the szComment buffer.
@@ -176,9 +176,9 @@ extern int ZEXPORT unzGoToNextFile OF((unzFile file));
return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest. return UNZ_END_OF_LIST_OF_FILE if the actual file was the latest.
*/ */
extern int ZEXPORT unzLocateFile OF((unzFile file, extern int ZEXPORT unzLocateFile OF((unzFile file,
const char *szFileName, const char *szFileName,
int iCaseSensitivity)); int iCaseSensitivity));
/* /*
Try locate the file szFileName in the zipfile. Try locate the file szFileName in the zipfile.
For the iCaseSensitivity signification, see unzStringFileNameCompare For the iCaseSensitivity signification, see unzStringFileNameCompare
@@ -190,24 +190,24 @@ extern int ZEXPORT unzLocateFile OF((unzFile file,
extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file, extern int ZEXPORT unzGetCurrentFileInfo OF((unzFile file,
unz_file_info *pfile_info, unz_file_info *pfile_info,
char *szFileName, char *szFileName,
uLong fileNameBufferSize, uLong fileNameBufferSize,
void *extraField, void *extraField,
uLong extraFieldBufferSize, uLong extraFieldBufferSize,
char *szComment, char *szComment,
uLong commentBufferSize)); uLong commentBufferSize));
/* /*
Get Info about the current file Get Info about the current file
if pfile_info!=NULL, the *pfile_info structure will contain somes info about if pfile_info!=NULL, the *pfile_info structure will contain somes info about
the current file the current file
if szFileName!=NULL, the filemane string will be copied in szFileName if szFileName!=NULL, the filemane string will be copied in szFileName
(fileNameBufferSize is the size of the buffer) (fileNameBufferSize is the size of the buffer)
if extraField!=NULL, the extra field information will be copied in extraField if extraField!=NULL, the extra field information will be copied in extraField
(extraFieldBufferSize is the size of the buffer). (extraFieldBufferSize is the size of the buffer).
This is the Central-header version of the extra field This is the Central-header version of the extra field
if szComment!=NULL, the comment string of the file will be copied in szComment if szComment!=NULL, the comment string of the file will be copied in szComment
(commentBufferSize is the size of the buffer) (commentBufferSize is the size of the buffer)
*/ */
/***************************************************************************/ /***************************************************************************/
@@ -227,10 +227,10 @@ extern int ZEXPORT unzCloseCurrentFile OF((unzFile file));
Return UNZ_CRCERROR if all the file was read but the CRC is not good Return UNZ_CRCERROR if all the file was read but the CRC is not good
*/ */
extern int ZEXPORT unzReadCurrentFile OF((unzFile file, extern int ZEXPORT unzReadCurrentFile OF((unzFile file,
voidp buf, voidp buf,
unsigned len)); unsigned len));
/* /*
Read bytes from the current file (opened by unzOpenCurrentFile) Read bytes from the current file (opened by unzOpenCurrentFile)
buf contain buffer where data must be copied buf contain buffer where data must be copied
@@ -249,12 +249,12 @@ extern z_off_t ZEXPORT unztell OF((unzFile file));
extern int ZEXPORT unzeof OF((unzFile file)); extern int ZEXPORT unzeof OF((unzFile file));
/* /*
return 1 if the end of file was reached, 0 elsewhere return 1 if the end of file was reached, 0 elsewhere
*/ */
extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file, extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
voidp buf, voidp buf,
unsigned len)); unsigned len));
/* /*
Read extra field from the current file (opened by unzOpenCurrentFile) Read extra field from the current file (opened by unzOpenCurrentFile)
This is the local-header version of the extra field (sometimes, there is This is the local-header version of the extra field (sometimes, there is
@@ -263,9 +263,9 @@ extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
if buf==NULL, it return the size of the local extra field if buf==NULL, it return the size of the local extra field
if buf!=NULL, len is the size of the buffer, the extra header is copied in if buf!=NULL, len is the size of the buffer, the extra header is copied in
buf. buf.
the return value is the number of bytes copied in buf, or (if <0) the return value is the number of bytes copied in buf, or (if <0)
the error code the error code
*/ */
#ifdef __cplusplus #ifdef __cplusplus
@@ -273,4 +273,3 @@ extern int ZEXPORT unzGetLocalExtrafield OF((unzFile file,
#endif #endif
#endif /* _unz_H */ #endif /* _unz_H */
@@ -1,4 +1,4 @@
/* zip.c -- IO on .zip files using zlib /* zip.c -- IO on .zip files using zlib
Version 0.15 beta, Mar 19th, 1998, Version 0.15 beta, Mar 19th, 1998,
Read zip.h for more info Read zip.h for more info
@@ -99,11 +99,11 @@ typedef struct linkedlist_data_s
typedef struct typedef struct
{ {
z_stream stream; /* zLib stream structure for inflate */ z_stream stream; /* zLib stream structure for inflate */
int stream_initialised; /* 1 is stream is initialised */ int stream_initialised; /* 1 is stream is initialised */
uInt pos_in_buffered_data; /* last written byte in buffered_data */ uInt pos_in_buffered_data; /* last written byte in buffered_data */
uLong pos_local_header; /* offset of the local header of the file uLong pos_local_header; /* offset of the local header of the file
currenty writing */ currenty writing */
char* central_header; /* central header data for the current file */ char* central_header; /* central header data for the current file */
uLong size_centralheader; /* size of the central header for cur file */ uLong size_centralheader; /* size of the central header for cur file */
@@ -166,7 +166,7 @@ local void free_linkedlist(ll)
local int add_data_in_datablock(ll,buf,len) local int add_data_in_datablock(ll,buf,len)
linkedlist_data* ll; linkedlist_data* ll;
const void* buf; const void* buf;
uLong len; uLong len;
{ {
@@ -222,7 +222,7 @@ local int add_data_in_datablock(ll,buf,len)
local int write_datablock(fout,ll) local int write_datablock(fout,ll)
FILE * fout; FILE * fout;
linkedlist_data* ll; linkedlist_data* ll;
{ {
linkedlist_datablock_internal* ldi; linkedlist_datablock_internal* ldi;
ldi = ll->first_block; ldi = ll->first_block;
@@ -322,7 +322,7 @@ extern zipFile ZEXPORT zipOpen (pathname, append)
return (zipFile)zi; return (zipFile)zi;
} }
extern int ZEXPORT zipOpenNewFileInZip (file, filename, zipfi, extern int ZEXPORT zipOpenNewFileInZip (file, filename, zipfi,
extrafield_local, size_extrafield_local, extrafield_local, size_extrafield_local,
extrafield_global, size_extrafield_global, extrafield_global, size_extrafield_global,
comment, method, level) comment, method, level)
@@ -390,7 +390,7 @@ extern int ZEXPORT zipOpenNewFileInZip (file, filename, zipfi,
zi->ci.stream_initialised = 0; zi->ci.stream_initialised = 0;
zi->ci.pos_in_buffered_data = 0; zi->ci.pos_in_buffered_data = 0;
zi->ci.pos_local_header = ftell(zi->filezip); zi->ci.pos_local_header = ftell(zi->filezip);
zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename + zi->ci.size_centralheader = SIZECENTRALHEADER + size_filename +
size_extrafield_global + size_comment; size_extrafield_global + size_comment;
zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader); zi->ci.central_header = (char*)ALLOC((uInt)zi->ci.size_centralheader);
@@ -410,12 +410,12 @@ extern int ZEXPORT zipOpenNewFileInZip (file, filename, zipfi,
ziplocal_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/ ziplocal_putValue_inmemory(zi->ci.central_header+34,(uLong)0,2); /*disk nm start*/
if (zipfi==NULL) if (zipfi==NULL)
ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2); ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)0,2);
else else
ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2); ziplocal_putValue_inmemory(zi->ci.central_header+36,(uLong)zipfi->internal_fa,2);
if (zipfi==NULL) if (zipfi==NULL)
ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4); ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)0,4);
else else
ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4); ziplocal_putValue_inmemory(zi->ci.central_header+38,(uLong)zipfi->external_fa,4);
@@ -568,10 +568,10 @@ extern int ZEXPORT zipCloseFileInZip (file)
return ZIP_PARAMERROR; return ZIP_PARAMERROR;
zi = (zip_internal*)file; zi = (zip_internal*)file;
if (zi->in_opened_file_inzip == 0) if (zi->in_opened_file_inzip == 0)
return ZIP_PARAMERROR; return ZIP_PARAMERROR;
zi->ci.stream.avail_in = 0; zi->ci.stream.avail_in = 0;
if (zi->ci.method == Z_DEFLATED) if (zi->ci.method == Z_DEFLATED)
while (err==ZIP_OK) while (err==ZIP_OK)
{ {
@@ -618,22 +618,22 @@ extern int ZEXPORT zipCloseFileInZip (file)
if (err==ZIP_OK) if (err==ZIP_OK)
{ {
long cur_pos_inzip = ftell(zi->filezip); long cur_pos_inzip = ftell(zi->filezip);
if (fseek(zi->filezip, if (fseek(zi->filezip,
zi->ci.pos_local_header + 14,SEEK_SET)!=0) zi->ci.pos_local_header + 14,SEEK_SET)!=0)
err = ZIP_ERRNO; err = ZIP_ERRNO;
if (err==ZIP_OK) if (err==ZIP_OK)
err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.crc32,4); /* crc 32, unknown */ err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.crc32,4); /* crc 32, unknown */
if (err==ZIP_OK) /* compressed size, unknown */ if (err==ZIP_OK) /* compressed size, unknown */
err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.stream.total_out,4); err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.stream.total_out,4);
if (err==ZIP_OK) /* uncompressed size, unknown */ if (err==ZIP_OK) /* uncompressed size, unknown */
err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.stream.total_in,4); err = ziplocal_putValue(zi->filezip,(uLong)zi->ci.stream.total_in,4);
if (fseek(zi->filezip, if (fseek(zi->filezip,
cur_pos_inzip,SEEK_SET)!=0) cur_pos_inzip,SEEK_SET)!=0)
err = ZIP_ERRNO; err = ZIP_ERRNO;
} }
zi->number_entry ++; zi->number_entry ++;
@@ -701,8 +701,8 @@ extern int ZEXPORT zipClose (file, global_comment)
if (err==ZIP_OK) /* size of the central directory */ if (err==ZIP_OK) /* size of the central directory */
err = ziplocal_putValue(zi->filezip,(uLong)size_centraldir,4); err = ziplocal_putValue(zi->filezip,(uLong)size_centraldir,4);
if (err==ZIP_OK) /* offset of start of central directory with respect to the if (err==ZIP_OK) /* offset of start of central directory with respect to the
starting disk number */ starting disk number */
err = ziplocal_putValue(zi->filezip,(uLong)centraldir_pos_inzip ,4); err = ziplocal_putValue(zi->filezip,(uLong)centraldir_pos_inzip ,4);
if (err==ZIP_OK) /* zipfile comment length */ if (err==ZIP_OK) /* zipfile comment length */
@@ -1,4 +1,4 @@
/* zip.h -- IO for compress .zip files using zlib /* zip.h -- IO for compress .zip files using zlib
Version 0.15 alpha, Mar 19th, 1998, Version 0.15 alpha, Mar 19th, 1998,
Copyright (C) 1998 Gilles Vollant Copyright (C) 1998 Gilles Vollant
@@ -36,7 +36,7 @@
*/ */
/* for more info about .ZIP format, see /* for more info about .ZIP format, see
ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip ftp://ftp.cdrom.com/pub/infozip/doc/appnote-970311-iz.zip
PkWare has also a specification at : PkWare has also a specification at :
ftp://ftp.pkware.com/probdesc.zip ftp://ftp.pkware.com/probdesc.zip
@@ -56,7 +56,7 @@ extern "C" {
#if defined(STRICTZIP) || defined(STRICTZIPUNZIP) #if defined(STRICTZIP) || defined(STRICTZIPUNZIP)
/* like the STRICT of WIN32, we define a pointer that cannot be converted /* like the STRICT of WIN32, we define a pointer that cannot be converted
from (void*) without cast */ from (void*) without cast */
typedef struct TagzipFile__ { int unused; } zipFile__; typedef struct TagzipFile__ { int unused; } zipFile__;
typedef zipFile__ *zipFile; typedef zipFile__ *zipFile;
#else #else
typedef voidp zipFile; typedef voidp zipFile;
@@ -68,19 +68,19 @@ typedef voidp zipFile;
#define ZIP_INTERNALERROR (-104) #define ZIP_INTERNALERROR (-104)
/* tm_zip contain date/time info */ /* tm_zip contain date/time info */
typedef struct tm_zip_s typedef struct tm_zip_s
{ {
uInt tm_sec; /* seconds after the minute - [0,59] */ uInt tm_sec; /* seconds after the minute - [0,59] */
uInt tm_min; /* minutes after the hour - [0,59] */ uInt tm_min; /* minutes after the hour - [0,59] */
uInt tm_hour; /* hours since midnight - [0,23] */ uInt tm_hour; /* hours since midnight - [0,23] */
uInt tm_mday; /* day of the month - [1,31] */ uInt tm_mday; /* day of the month - [1,31] */
uInt tm_mon; /* months since January - [0,11] */ uInt tm_mon; /* months since January - [0,11] */
uInt tm_year; /* years - [1980..2044] */ uInt tm_year; /* years - [1980..2044] */
} tm_zip; } tm_zip;
typedef struct typedef struct
{ {
tm_zip tmz_date; /* date in understandable format */ tm_zip tmz_date; /* date in understandable format */
uLong dosDate; /* if dos_date == 0, tmu_date is used */ uLong dosDate; /* if dos_date == 0, tmu_date is used */
/* uLong flag; */ /* general purpose bit flag 2 bytes */ /* uLong flag; */ /* general purpose bit flag 2 bytes */
@@ -91,27 +91,27 @@ typedef struct
extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append)); extern zipFile ZEXPORT zipOpen OF((const char *pathname, int append));
/* /*
Create a zipfile. Create a zipfile.
pathname contain on Windows NT a filename like "c:\\zlib\\zlib111.zip" or on pathname contain on Windows NT a filename like "c:\\zlib\\zlib111.zip" or on
an Unix computer "zlib/zlib111.zip". an Unix computer "zlib/zlib111.zip".
if the file pathname exist and append=1, the zip will be created at the end if the file pathname exist and append=1, the zip will be created at the end
of the file. (useful if the file contain a self extractor code) of the file. (useful if the file contain a self extractor code)
If the zipfile cannot be opened, the return value is NULL. If the zipfile cannot be opened, the return value is NULL.
Else, the return value is a zipFile Handle, usable with other function Else, the return value is a zipFile Handle, usable with other function
of this zip package. of this zip package.
*/ */
extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file, extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
const char* filename, const char* filename,
const zip_fileinfo* zipfi, const zip_fileinfo* zipfi,
const void* extrafield_local, const void* extrafield_local,
uInt size_extrafield_local, uInt size_extrafield_local,
const void* extrafield_global, const void* extrafield_global,
uInt size_extrafield_global, uInt size_extrafield_global,
const char* comment, const char* comment,
int method, int method,
int level)); int level));
/* /*
Open a file in the ZIP for writing. Open a file in the ZIP for writing.
filename : the filename in zip (if NULL, '-' without quote will be used filename : the filename in zip (if NULL, '-' without quote will be used
@@ -126,8 +126,8 @@ extern int ZEXPORT zipOpenNewFileInZip OF((zipFile file,
*/ */
extern int ZEXPORT zipWriteInFileInZip OF((zipFile file, extern int ZEXPORT zipWriteInFileInZip OF((zipFile file,
const voidp buf, const voidp buf,
unsigned len)); unsigned len));
/* /*
Write data in the zipfile Write data in the zipfile
*/ */
@@ -138,7 +138,7 @@ extern int ZEXPORT zipCloseFileInZip OF((zipFile file));
*/ */
extern int ZEXPORT zipClose OF((zipFile file, extern int ZEXPORT zipClose OF((zipFile file,
const char* global_comment)); const char* global_comment));
/* /*
Close the zipfile Close the zipfile
*/ */
@@ -148,4 +148,3 @@ extern int ZEXPORT zipClose OF((zipFile file,
#endif #endif
#endif /* _zip_H */ #endif /* _zip_H */
@@ -39,37 +39,37 @@
/* Values used in typeflag field. */ /* Values used in typeflag field. */
#define REGTYPE '0' /* regular file */ #define REGTYPE '0' /* regular file */
#define AREGTYPE '\0' /* regular file */ #define AREGTYPE '\0' /* regular file */
#define LNKTYPE '1' /* link */ #define LNKTYPE '1' /* link */
#define SYMTYPE '2' /* reserved */ #define SYMTYPE '2' /* reserved */
#define CHRTYPE '3' /* character special */ #define CHRTYPE '3' /* character special */
#define BLKTYPE '4' /* block special */ #define BLKTYPE '4' /* block special */
#define DIRTYPE '5' /* directory */ #define DIRTYPE '5' /* directory */
#define FIFOTYPE '6' /* FIFO special */ #define FIFOTYPE '6' /* FIFO special */
#define CONTTYPE '7' /* reserved */ #define CONTTYPE '7' /* reserved */
#define BLOCKSIZE 512 #define BLOCKSIZE 512
struct tar_header struct tar_header
{ /* byte offset */ { /* byte offset */
char name[100]; /* 0 */ char name[100]; /* 0 */
char mode[8]; /* 100 */ char mode[8]; /* 100 */
char uid[8]; /* 108 */ char uid[8]; /* 108 */
char gid[8]; /* 116 */ char gid[8]; /* 116 */
char size[12]; /* 124 */ char size[12]; /* 124 */
char mtime[12]; /* 136 */ char mtime[12]; /* 136 */
char chksum[8]; /* 148 */ char chksum[8]; /* 148 */
char typeflag; /* 156 */ char typeflag; /* 156 */
char linkname[100]; /* 157 */ char linkname[100]; /* 157 */
char magic[6]; /* 257 */ char magic[6]; /* 257 */
char version[2]; /* 263 */ char version[2]; /* 263 */
char uname[32]; /* 265 */ char uname[32]; /* 265 */
char gname[32]; /* 297 */ char gname[32]; /* 297 */
char devmajor[8]; /* 329 */ char devmajor[8]; /* 329 */
char devminor[8]; /* 337 */ char devminor[8]; /* 337 */
char prefix[155]; /* 345 */ char prefix[155]; /* 345 */
/* 500 */ /* 500 */
}; };
union tar_buffer { union tar_buffer {
@@ -79,21 +79,21 @@ union tar_buffer {
enum { TGZ_EXTRACT = 0, TGZ_LIST }; enum { TGZ_EXTRACT = 0, TGZ_LIST };
static char *TGZfname OF((const char *)); static char *TGZfname OF((const char *));
void TGZnotfound OF((const char *)); void TGZnotfound OF((const char *));
int getoct OF((char *, int)); int getoct OF((char *, int));
char *strtime OF((time_t *)); char *strtime OF((time_t *));
int ExprMatch OF((char *,char *)); int ExprMatch OF((char *,char *));
int makedir OF((char *)); int makedir OF((char *));
int matchname OF((int,int,char **,char *)); int matchname OF((int,int,char **,char *));
void error OF((const char *)); void error OF((const char *));
int tar OF((gzFile, int, int, int, char **)); int tar OF((gzFile, int, int, int, char **));
void help OF((int)); void help OF((int));
int main OF((int, char **)); int main OF((int, char **));
char *prog; char *prog;
@@ -108,7 +108,7 @@ static char *TGZfname OF((const char *fname))
{ {
static char buffer[1024]; static char buffer[1024];
int origlen,i; int origlen,i;
strcpy(buffer,fname); strcpy(buffer,fname);
origlen = strlen(buffer); origlen = strlen(buffer);
@@ -142,14 +142,14 @@ int getoct(char *p,int width)
{ {
int result = 0; int result = 0;
char c; char c;
while (width --) while (width --)
{ {
c = *p++; c = *p++;
if (c == ' ') if (c == ' ')
continue; continue;
if (c == 0) if (c == 0)
break; break;
result = result * 8 + (c - '0'); result = result * 8 + (c - '0');
} }
return result; return result;
@@ -162,8 +162,8 @@ char *strtime (time_t *t)
local = localtime(t); local = localtime(t);
sprintf(result,"%2d/%02d/%4d %02d:%02d:%02d", sprintf(result,"%2d/%02d/%4d %02d:%02d:%02d",
local->tm_mday, local->tm_mon+1, local->tm_year+1900, local->tm_mday, local->tm_mon+1, local->tm_year+1900,
local->tm_hour, local->tm_min, local->tm_sec); local->tm_hour, local->tm_min, local->tm_sec);
return result; return result;
} }
@@ -177,30 +177,30 @@ int ExprMatch(char *string,char *expr)
while (1) while (1)
{ {
if (ISSPECIAL(*expr)) if (ISSPECIAL(*expr))
{ {
if (*expr == '/') if (*expr == '/')
{ {
if (*string != '\\' && *string != '/') if (*string != '\\' && *string != '/')
return 0; return 0;
string ++; expr++; string ++; expr++;
} }
else if (*expr == '*') else if (*expr == '*')
{ {
if (*expr ++ == 0) if (*expr ++ == 0)
return 1; return 1;
while (*++string != *expr) while (*++string != *expr)
if (*string == 0) if (*string == 0)
return 0; return 0;
} }
} }
else else
{ {
if (*string != *expr) if (*string != *expr)
return 0; return 0;
if (*expr++ == 0) if (*expr++ == 0)
return 1; return 1;
string++; string++;
} }
} }
} }
@@ -216,7 +216,7 @@ int makedir (char *newdir)
char *buffer = strdup(newdir); char *buffer = strdup(newdir);
char *p; char *p;
int len = strlen(buffer); int len = strlen(buffer);
if (len <= 0) { if (len <= 0) {
free(buffer); free(buffer);
return 0; return 0;
@@ -234,19 +234,19 @@ int makedir (char *newdir)
while (1) while (1)
{ {
char hold; char hold;
while(*p && *p != '\\' && *p != '/') while(*p && *p != '\\' && *p != '/')
p++; p++;
hold = *p; hold = *p;
*p = 0; *p = 0;
if ((mkdir(buffer, 0775) == -1) && (errno == ENOENT)) if ((mkdir(buffer, 0775) == -1) && (errno == ENOENT))
{ {
fprintf(stderr,"%s: couldn't create directory %s\n",prog,buffer); fprintf(stderr,"%s: couldn't create directory %s\n",prog,buffer);
free(buffer); free(buffer);
return 0; return 0;
} }
if (hold == 0) if (hold == 0)
break; break;
*p++ = hold; *p++ = hold;
} }
free(buffer); free(buffer);
@@ -255,7 +255,7 @@ int makedir (char *newdir)
int matchname (int arg,int argc,char **argv,char *fname) int matchname (int arg,int argc,char **argv,char *fname)
{ {
if (arg == argc) /* no arguments given (untgz tgzarchive) */ if (arg == argc) /* no arguments given (untgz tgzarchive) */
return 1; return 1;
while (arg < argc) while (arg < argc)
@@ -278,144 +278,144 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
FILE *outfile = NULL; FILE *outfile = NULL;
char fname[BLOCKSIZE]; char fname[BLOCKSIZE];
time_t tartime; time_t tartime;
if (action == TGZ_LIST) if (action == TGZ_LIST)
printf(" day time size file\n" printf(" day time size file\n"
" ---------- -------- --------- -------------------------------------\n"); " ---------- -------- --------- -------------------------------------\n");
while (1) while (1)
{ {
len = gzread(in, &buffer, BLOCKSIZE); len = gzread(in, &buffer, BLOCKSIZE);
if (len < 0) if (len < 0)
error (gzerror(in, &err)); error (gzerror(in, &err));
/* /*
* Always expect complete blocks to process * Always expect complete blocks to process
* the tar information. * the tar information.
*/ */
if (len != BLOCKSIZE) if (len != BLOCKSIZE)
error("gzread: incomplete block read"); error("gzread: incomplete block read");
/* /*
* If we have to get a tar header * If we have to get a tar header
*/ */
if (getheader == 1) if (getheader == 1)
{ {
/* /*
* if we met the end of the tar * if we met the end of the tar
* or the end-of-tar block, * or the end-of-tar block,
* we are done * we are done
*/ */
if ((len == 0) || (buffer.header.name[0]== 0)) break; if ((len == 0) || (buffer.header.name[0]== 0)) break;
tartime = (time_t)getoct(buffer.header.mtime,12); tartime = (time_t)getoct(buffer.header.mtime,12);
strcpy(fname,buffer.header.name); strcpy(fname,buffer.header.name);
switch (buffer.header.typeflag) switch (buffer.header.typeflag)
{ {
case DIRTYPE: case DIRTYPE:
if (action == TGZ_LIST) if (action == TGZ_LIST)
printf(" %s <dir> %s\n",strtime(&tartime),fname); printf(" %s <dir> %s\n",strtime(&tartime),fname);
if (action == TGZ_EXTRACT) if (action == TGZ_EXTRACT)
makedir(fname); makedir(fname);
break; break;
case REGTYPE: case REGTYPE:
case AREGTYPE: case AREGTYPE:
remaining = getoct(buffer.header.size,12); remaining = getoct(buffer.header.size,12);
if (action == TGZ_LIST) if (action == TGZ_LIST)
printf(" %s %9d %s\n",strtime(&tartime),remaining,fname); printf(" %s %9d %s\n",strtime(&tartime),remaining,fname);
if (action == TGZ_EXTRACT) if (action == TGZ_EXTRACT)
{ {
if ((remaining) && (matchname(arg,argc,argv,fname))) if ((remaining) && (matchname(arg,argc,argv,fname)))
{ {
outfile = fopen(fname,"wb"); outfile = fopen(fname,"wb");
if (outfile == NULL) { if (outfile == NULL) {
/* try creating directory */ /* try creating directory */
char *p = strrchr(fname, '/'); char *p = strrchr(fname, '/');
if (p != NULL) { if (p != NULL) {
*p = '\0'; *p = '\0';
makedir(fname); makedir(fname);
*p = '/'; *p = '/';
outfile = fopen(fname,"wb"); outfile = fopen(fname,"wb");
} }
} }
fprintf(stderr, fprintf(stderr,
"%s %s\n", "%s %s\n",
(outfile) ? "Extracting" : "Couldn't create", (outfile) ? "Extracting" : "Couldn't create",
fname); fname);
} }
else else
outfile = NULL; outfile = NULL;
} }
/* /*
* could have no contents * could have no contents
*/ */
getheader = (remaining) ? 0 : 1; getheader = (remaining) ? 0 : 1;
break; break;
default: default:
if (action == TGZ_LIST) if (action == TGZ_LIST)
printf(" %s <---> %s\n",strtime(&tartime),fname); printf(" %s <---> %s\n",strtime(&tartime),fname);
break; break;
} }
} }
else else
{ {
unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining; unsigned int bytes = (remaining > BLOCKSIZE) ? BLOCKSIZE : remaining;
if ((action == TGZ_EXTRACT) && (outfile != NULL)) if ((action == TGZ_EXTRACT) && (outfile != NULL))
{ {
if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes) if (fwrite(&buffer,sizeof(char),bytes,outfile) != bytes)
{ {
fprintf(stderr,"%s : error writing %s skipping...\n",prog,fname); fprintf(stderr,"%s : error writing %s skipping...\n",prog,fname);
fclose(outfile); fclose(outfile);
unlink(fname); unlink(fname);
} }
} }
remaining -= bytes; remaining -= bytes;
if (remaining == 0) if (remaining == 0)
{ {
getheader = 1; getheader = 1;
if ((action == TGZ_EXTRACT) && (outfile != NULL)) if ((action == TGZ_EXTRACT) && (outfile != NULL))
{ {
#ifdef WIN32 #ifdef WIN32
HANDLE hFile; HANDLE hFile;
FILETIME ftm,ftLocal; FILETIME ftm,ftLocal;
SYSTEMTIME st; SYSTEMTIME st;
struct tm localt; struct tm localt;
fclose(outfile);
fclose(outfile); localt = *localtime(&tartime);
localt = *localtime(&tartime); hFile = CreateFile(fname, GENERIC_READ | GENERIC_WRITE,
0, NULL, OPEN_EXISTING, 0, NULL);
st.wYear = (WORD)localt.tm_year+1900;
st.wMonth = (WORD)localt.tm_mon;
st.wDayOfWeek = (WORD)localt.tm_wday;
st.wDay = (WORD)localt.tm_mday;
st.wHour = (WORD)localt.tm_hour;
st.wMinute = (WORD)localt.tm_min;
st.wSecond = (WORD)localt.tm_sec;
st.wMilliseconds = 0;
SystemTimeToFileTime(&st,&ftLocal);
LocalFileTimeToFileTime(&ftLocal,&ftm);
SetFileTime(hFile,&ftm,NULL,&ftm);
CloseHandle(hFile);
hFile = CreateFile(fname, GENERIC_READ | GENERIC_WRITE, outfile = NULL;
0, NULL, OPEN_EXISTING, 0, NULL);
st.wYear = (WORD)localt.tm_year+1900;
st.wMonth = (WORD)localt.tm_mon;
st.wDayOfWeek = (WORD)localt.tm_wday;
st.wDay = (WORD)localt.tm_mday;
st.wHour = (WORD)localt.tm_hour;
st.wMinute = (WORD)localt.tm_min;
st.wSecond = (WORD)localt.tm_sec;
st.wMilliseconds = 0;
SystemTimeToFileTime(&st,&ftLocal);
LocalFileTimeToFileTime(&ftLocal,&ftm);
SetFileTime(hFile,&ftm,NULL,&ftm);
CloseHandle(hFile);
outfile = NULL;
#else #else
struct utimbuf settime; struct utimbuf settime;
settime.actime = settime.modtime = tartime; settime.actime = settime.modtime = tartime;
fclose(outfile); fclose(outfile);
outfile = NULL; outfile = NULL;
utime(fname,&settime); utime(fname,&settime);
#endif #endif
} }
} }
}
} }
}
if (gzclose(in) != Z_OK) if (gzclose(in) != Z_OK)
error("failed gzclose"); error("failed gzclose");
@@ -428,8 +428,8 @@ int tar (gzFile in,int action,int arg,int argc,char **argv)
void help(int exitval) void help(int exitval)
{ {
fprintf(stderr, fprintf(stderr,
"untgz v 0.1\n" "untgz v 0.1\n"
" an sample application of zlib 1.0.4\n\n" " an sample application of zlib 1.0.4\n\n"
"Usage : untgz TGZfile to extract all files\n" "Usage : untgz TGZfile to extract all files\n"
" untgz TGZfile fname ... to extract selected files\n" " untgz TGZfile fname ... to extract selected files\n"
" untgz -l TGZfile to list archive contents\n" " untgz -l TGZfile to list archive contents\n"
@@ -446,50 +446,50 @@ void error(const char *msg)
/* ====================================================================== */ /* ====================================================================== */
int _CRT_glob = 0; /* disable globbing of the arguments */ int _CRT_glob = 0; /* disable globbing of the arguments */
int main(int argc,char **argv) int main(int argc,char **argv)
{ {
int action = TGZ_EXTRACT; int action = TGZ_EXTRACT;
int arg = 1; int arg = 1;
char *TGZfile; char *TGZfile;
gzFile *f; gzFile *f;
prog = strrchr(argv[0],'\\'); prog = strrchr(argv[0],'\\');
if (prog == NULL) if (prog == NULL)
{ {
prog = strrchr(argv[0],'/'); prog = strrchr(argv[0],'/');
if (prog == NULL) if (prog == NULL)
{ {
prog = strrchr(argv[0],':'); prog = strrchr(argv[0],':');
if (prog == NULL) if (prog == NULL)
prog = argv[0]; prog = argv[0];
else else
prog++; prog++;
}
else
prog++;
} }
else else
prog++; prog++;
}
else
prog++;
if (argc == 1) if (argc == 1)
help(0); help(0);
if (strcmp(argv[arg],"-l") == 0) if (strcmp(argv[arg],"-l") == 0)
{ {
action = TGZ_LIST; action = TGZ_LIST;
if (argc == ++arg) if (argc == ++arg)
help(0); help(0);
} }
else if (strcmp(argv[arg],"-h") == 0) else if (strcmp(argv[arg],"-h") == 0)
{ {
help(0); help(0);
} }
if ((TGZfile = TGZfname(argv[arg])) == NULL) if ((TGZfile = TGZfname(argv[arg])) == NULL)
TGZnotfound(argv[arg]); TGZnotfound(argv[arg]);
++arg; ++arg;
if ((action == TGZ_LIST) && (arg != argc)) if ((action == TGZ_LIST) && (arg != argc))
@@ -502,20 +502,20 @@ int main(int argc,char **argv)
{ {
case TGZ_LIST: case TGZ_LIST:
case TGZ_EXTRACT: case TGZ_EXTRACT:
f = gzopen(TGZfile,"rb"); f = gzopen(TGZfile,"rb");
if (f == NULL) if (f == NULL)
{ {
fprintf(stderr,"%s: Couldn't gzopen %s\n", fprintf(stderr,"%s: Couldn't gzopen %s\n",
prog, prog,
TGZfile); TGZfile);
return 1; return 1;
} }
exit(tar(f, action, arg, argc, argv)); exit(tar(f, action, arg, argc, argv));
break; break;
default: default:
error("Unknown option!"); error("Unknown option!");
exit(1); exit(1);
} }
return 0; return 0;
@@ -1,6 +1,6 @@
/* crc32.c -- compute the CRC-32 of a data stream /* crc32.c -- compute the CRC-32 of a data stream
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* @(#) $Id$ */ /* @(#) $Id$ */
@@ -51,7 +51,7 @@ local void make_crc_table()
poly = 0L; poly = 0L;
for (n = 0; n < sizeof(p)/sizeof(Byte); n++) for (n = 0; n < sizeof(p)/sizeof(Byte); n++)
poly |= 1L << (31 - p[n]); poly |= 1L << (31 - p[n]);
for (n = 0; n < 256; n++) for (n = 0; n < 256; n++)
{ {
c = (uLong)n; c = (uLong)n;
+103 -103
View File
@@ -1,6 +1,6 @@
/* deflate.c -- compress data using the deflation algorithm /* deflate.c -- compress data using the deflation algorithm
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* /*
@@ -194,13 +194,13 @@ int ZEXPORT deflateInit_(strm, level, version, stream_size)
int stream_size; int stream_size;
{ {
return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, return deflateInit2_(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL,
Z_DEFAULT_STRATEGY, version, stream_size); Z_DEFAULT_STRATEGY, version, stream_size);
/* To do: ignore strm->next_in if we use it as window */ /* To do: ignore strm->next_in if we use it as window */
} }
/* ========================================================================= */ /* ========================================================================= */
int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy, int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
version, stream_size) version, stream_size)
z_streamp strm; z_streamp strm;
int level; int level;
int method; int method;
@@ -221,14 +221,14 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
if (version == Z_NULL || version[0] != my_version[0] || if (version == Z_NULL || version[0] != my_version[0] ||
stream_size != sizeof(z_stream)) { stream_size != sizeof(z_stream)) {
return Z_VERSION_ERROR; return Z_VERSION_ERROR;
} }
if (strm == Z_NULL) return Z_STREAM_ERROR; if (strm == Z_NULL) return Z_STREAM_ERROR;
strm->msg = Z_NULL; strm->msg = Z_NULL;
if (strm->zalloc == Z_NULL) { if (strm->zalloc == Z_NULL) {
strm->zalloc = zcalloc; strm->zalloc = zcalloc;
strm->opaque = (voidpf)0; strm->opaque = (voidpf)0;
} }
if (strm->zfree == Z_NULL) strm->zfree = zcfree; if (strm->zfree == Z_NULL) strm->zfree = zcfree;
@@ -243,7 +243,7 @@ int ZEXPORT deflateInit2_(strm, level, method, windowBits, memLevel, strategy,
} }
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED || if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method != Z_DEFLATED ||
windowBits < 9 || windowBits > 15 || level < 0 || level > 9 || windowBits < 9 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_HUFFMAN_ONLY) { strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state)); s = (deflate_state *) ZALLOC(strm, 1, sizeof(deflate_state));
@@ -306,9 +306,9 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
if (length < MIN_MATCH) return Z_OK; if (length < MIN_MATCH) return Z_OK;
if (length > MAX_DIST(s)) { if (length > MAX_DIST(s)) {
length = MAX_DIST(s); length = MAX_DIST(s);
#ifndef USE_DICT_HEAD #ifndef USE_DICT_HEAD
dictionary += dictLength - length; /* use the tail of the dictionary */ dictionary += dictLength - length; /* use the tail of the dictionary */
#endif #endif
} }
zmemcpy(s->window, dictionary, length); zmemcpy(s->window, dictionary, length);
@@ -322,7 +322,7 @@ int ZEXPORT deflateSetDictionary (strm, dictionary, dictLength)
s->ins_h = s->window[0]; s->ins_h = s->window[0];
UPDATE_HASH(s, s->ins_h, s->window[1]); UPDATE_HASH(s, s->ins_h, s->window[1]);
for (n = 0; n <= length - MIN_MATCH; n++) { for (n = 0; n <= length - MIN_MATCH; n++) {
INSERT_STRING(s, n, hash_head); INSERT_STRING(s, n, hash_head);
} }
if (hash_head) hash_head = 0; /* to make compiler happy */ if (hash_head) hash_head = 0; /* to make compiler happy */
return Z_OK; return Z_OK;
@@ -333,7 +333,7 @@ int ZEXPORT deflateReset (strm)
z_streamp strm; z_streamp strm;
{ {
deflate_state *s; deflate_state *s;
if (strm == Z_NULL || strm->state == Z_NULL || if (strm == Z_NULL || strm->state == Z_NULL ||
strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR; strm->zalloc == Z_NULL || strm->zfree == Z_NULL) return Z_STREAM_ERROR;
@@ -372,23 +372,23 @@ int ZEXPORT deflateParams(strm, level, strategy)
s = strm->state; s = strm->state;
if (level == Z_DEFAULT_COMPRESSION) { if (level == Z_DEFAULT_COMPRESSION) {
level = 6; level = 6;
} }
if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) { if (level < 0 || level > 9 || strategy < 0 || strategy > Z_HUFFMAN_ONLY) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
func = configuration_table[s->level].func; func = configuration_table[s->level].func;
if (func != configuration_table[level].func && strm->total_in != 0) { if (func != configuration_table[level].func && strm->total_in != 0) {
/* Flush the last buffer: */ /* Flush the last buffer: */
err = deflate(strm, Z_PARTIAL_FLUSH); err = deflate(strm, Z_PARTIAL_FLUSH);
} }
if (s->level != level) { if (s->level != level) {
s->level = level; s->level = level;
s->max_lazy_match = configuration_table[level].max_lazy; s->max_lazy_match = configuration_table[level].max_lazy;
s->good_match = configuration_table[level].good_length; s->good_match = configuration_table[level].good_length;
s->nice_match = configuration_table[level].nice_length; s->nice_match = configuration_table[level].nice_length;
s->max_chain_length = configuration_table[level].max_chain; s->max_chain_length = configuration_table[level].max_chain;
} }
s->strategy = strategy; s->strategy = strategy;
return err; return err;
@@ -405,7 +405,7 @@ local void putShortMSB (s, b)
{ {
put_byte(s, (Byte)(b >> 8)); put_byte(s, (Byte)(b >> 8));
put_byte(s, (Byte)(b & 0xff)); put_byte(s, (Byte)(b & 0xff));
} }
/* ========================================================================= /* =========================================================================
* Flush as much pending output as possible. All deflate() output goes * Flush as much pending output as possible. All deflate() output goes
@@ -441,14 +441,14 @@ int ZEXPORT deflate (strm, flush)
deflate_state *s; deflate_state *s;
if (strm == Z_NULL || strm->state == Z_NULL || if (strm == Z_NULL || strm->state == Z_NULL ||
flush > Z_FINISH || flush < 0) { flush > Z_FINISH || flush < 0) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
s = strm->state; s = strm->state;
if (strm->next_out == Z_NULL || if (strm->next_out == Z_NULL ||
(strm->next_in == Z_NULL && strm->avail_in != 0) || (strm->next_in == Z_NULL && strm->avail_in != 0) ||
(s->status == FINISH_STATE && flush != Z_FINISH)) { (s->status == FINISH_STATE && flush != Z_FINISH)) {
ERR_RETURN(strm, Z_STREAM_ERROR); ERR_RETURN(strm, Z_STREAM_ERROR);
} }
if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR); if (strm->avail_out == 0) ERR_RETURN(strm, Z_BUF_ERROR);
@@ -465,40 +465,40 @@ int ZEXPORT deflate (strm, flush)
if (level_flags > 3) level_flags = 3; if (level_flags > 3) level_flags = 3;
header |= (level_flags << 6); header |= (level_flags << 6);
if (s->strstart != 0) header |= PRESET_DICT; if (s->strstart != 0) header |= PRESET_DICT;
header += 31 - (header % 31); header += 31 - (header % 31);
s->status = BUSY_STATE; s->status = BUSY_STATE;
putShortMSB(s, header); putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */ /* Save the adler32 of the preset dictionary: */
if (s->strstart != 0) { if (s->strstart != 0) {
putShortMSB(s, (uInt)(strm->adler >> 16)); putShortMSB(s, (uInt)(strm->adler >> 16));
putShortMSB(s, (uInt)(strm->adler & 0xffff)); putShortMSB(s, (uInt)(strm->adler & 0xffff));
} }
strm->adler = 1L; strm->adler = 1L;
} }
/* Flush as much pending output as possible */ /* Flush as much pending output as possible */
if (s->pending != 0) { if (s->pending != 0) {
flush_pending(strm); flush_pending(strm);
if (strm->avail_out == 0) { if (strm->avail_out == 0) {
/* Since avail_out is 0, deflate will be called again with /* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and * more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do, * avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we * but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate: * return OK instead of BUF_ERROR at next call of deflate:
*/ */
s->last_flush = -1; s->last_flush = -1;
return Z_OK; return Z_OK;
} }
/* Make sure there is something to do and avoid duplicate consecutive /* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep * flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUFF_ERROR. * returning Z_STREAM_END instead of Z_BUFF_ERROR.
*/ */
} else if (strm->avail_in == 0 && flush <= old_flush && } else if (strm->avail_in == 0 && flush <= old_flush &&
flush != Z_FINISH) { flush != Z_FINISH) {
ERR_RETURN(strm, Z_BUF_ERROR); ERR_RETURN(strm, Z_BUF_ERROR);
} }
@@ -513,24 +513,24 @@ int ZEXPORT deflate (strm, flush)
(flush != Z_NO_FLUSH && s->status != FINISH_STATE)) { (flush != Z_NO_FLUSH && s->status != FINISH_STATE)) {
block_state bstate; block_state bstate;
bstate = (*(configuration_table[s->level].func))(s, flush); bstate = (*(configuration_table[s->level].func))(s, flush);
if (bstate == finish_started || bstate == finish_done) { if (bstate == finish_started || bstate == finish_done) {
s->status = FINISH_STATE; s->status = FINISH_STATE;
} }
if (bstate == need_more || bstate == finish_started) { if (bstate == need_more || bstate == finish_started) {
if (strm->avail_out == 0) { if (strm->avail_out == 0) {
s->last_flush = -1; /* avoid BUF_ERROR next call, see above */ s->last_flush = -1; /* avoid BUF_ERROR next call, see above */
} }
return Z_OK; return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call /* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure * of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an * that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also * empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most * ensures that for a very small output buffer, we emit at most
* one empty block. * one empty block.
*/ */
} }
if (bstate == block_done) { if (bstate == block_done) {
if (flush == Z_PARTIAL_FLUSH) { if (flush == Z_PARTIAL_FLUSH) {
_tr_align(s); _tr_align(s);
@@ -544,10 +544,10 @@ int ZEXPORT deflate (strm, flush)
} }
} }
flush_pending(strm); flush_pending(strm);
if (strm->avail_out == 0) { if (strm->avail_out == 0) {
s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */ s->last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK; return Z_OK;
} }
} }
} }
Assert(strm->avail_out > 0, "bug2"); Assert(strm->avail_out > 0, "bug2");
@@ -576,7 +576,7 @@ int ZEXPORT deflateEnd (strm)
status = strm->state->status; status = strm->state->status;
if (status != INIT_STATE && status != BUSY_STATE && if (status != INIT_STATE && status != BUSY_STATE &&
status != FINISH_STATE) { status != FINISH_STATE) {
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
} }
@@ -903,10 +903,10 @@ local uInt longest_match(s, cur_match)
*/ */
do { do {
} while (*++scan == *++match && *++scan == *++match && } while (*++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match &&
*++scan == *++match && *++scan == *++match && *++scan == *++match && *++scan == *++match &&
scan < strend); scan < strend);
Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan"); Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
@@ -933,10 +933,10 @@ local void check_match(s, start, match, length)
if (zmemcmp(s->window + match, if (zmemcmp(s->window + match,
s->window + start, length) != EQUAL) { s->window + start, length) != EQUAL) {
fprintf(stderr, " start %u, match %u, length %d\n", fprintf(stderr, " start %u, match %u, length %d\n",
start, match, length); start, match, length);
do { do {
fprintf(stderr, "%c%c", s->window[match++], s->window[start++]); fprintf(stderr, "%c%c", s->window[match++], s->window[start++]);
} while (--length != 0); } while (--length != 0);
z_error("invalid match"); z_error("invalid match");
} }
if (z_verbose > 1) { if (z_verbose > 1) {
@@ -995,23 +995,23 @@ local void fill_window(s)
later. (Using level 0 permanently is not an optimal usage of later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.) zlib, so we don't care about this pathological case.)
*/ */
n = s->hash_size; n = s->hash_size;
p = &s->head[n]; p = &s->head[n];
do { do {
m = *--p; m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL); *p = (Pos)(m >= wsize ? m-wsize : NIL);
} while (--n); } while (--n);
n = wsize; n = wsize;
#ifndef FASTEST #ifndef FASTEST
p = &s->prev[n]; p = &s->prev[n];
do { do {
m = *--p; m = *--p;
*p = (Pos)(m >= wsize ? m-wsize : NIL); *p = (Pos)(m >= wsize ? m-wsize : NIL);
/* If n is not on any hash chain, prev[n] is garbage but /* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used. * its value will never be used.
*/ */
} while (--n); } while (--n);
#endif #endif
more += wsize; more += wsize;
} }
@@ -1056,8 +1056,8 @@ local void fill_window(s)
_tr_flush_block(s, (s->block_start >= 0L ? \ _tr_flush_block(s, (s->block_start >= 0L ? \
(charf *)&s->window[(unsigned)s->block_start] : \ (charf *)&s->window[(unsigned)s->block_start] : \
(charf *)Z_NULL), \ (charf *)Z_NULL), \
(ulg)((long)s->strstart - s->block_start), \ (ulg)((long)s->strstart - s->block_start), \
(eof)); \ (eof)); \
s->block_start = s->strstart; \ s->block_start = s->strstart; \
flush_pending(s->strm); \ flush_pending(s->strm); \
Tracev((stderr,"[FLUSH]")); \ Tracev((stderr,"[FLUSH]")); \
@@ -1098,32 +1098,32 @@ local block_state deflate_stored(s, flush)
if (s->lookahead <= 1) { if (s->lookahead <= 1) {
Assert(s->strstart < s->w_size+MAX_DIST(s) || Assert(s->strstart < s->w_size+MAX_DIST(s) ||
s->block_start >= (long)s->w_size, "slide too late"); s->block_start >= (long)s->w_size, "slide too late");
fill_window(s); fill_window(s);
if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more; if (s->lookahead == 0 && flush == Z_NO_FLUSH) return need_more;
if (s->lookahead == 0) break; /* flush the current block */ if (s->lookahead == 0) break; /* flush the current block */
} }
Assert(s->block_start >= 0L, "block gone"); Assert(s->block_start >= 0L, "block gone");
s->strstart += s->lookahead; s->strstart += s->lookahead;
s->lookahead = 0; s->lookahead = 0;
/* Emit a stored block if pending_buf will be full: */ /* Emit a stored block if pending_buf will be full: */
max_start = s->block_start + max_block_size; max_start = s->block_start + max_block_size;
if (s->strstart == 0 || (ulg)s->strstart >= max_start) { if (s->strstart == 0 || (ulg)s->strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */ /* strstart == 0 is possible when wraparound on 16-bit machine */
s->lookahead = (uInt)(s->strstart - max_start); s->lookahead = (uInt)(s->strstart - max_start);
s->strstart = (uInt)max_start; s->strstart = (uInt)max_start;
FLUSH_BLOCK(s, 0); FLUSH_BLOCK(s, 0);
} }
/* Flush if we may have to slide, otherwise block_start may become /* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone: * negative and the data will be gone:
*/ */
if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) { if (s->strstart - (uInt)s->block_start >= MAX_DIST(s)) {
FLUSH_BLOCK(s, 0); FLUSH_BLOCK(s, 0);
} }
} }
FLUSH_BLOCK(s, flush == Z_FINISH); FLUSH_BLOCK(s, flush == Z_FINISH);
return flush == Z_FINISH ? finish_done : block_done; return flush == Z_FINISH ? finish_done : block_done;
@@ -1152,8 +1152,8 @@ local block_state deflate_fast(s, flush)
if (s->lookahead < MIN_LOOKAHEAD) { if (s->lookahead < MIN_LOOKAHEAD) {
fill_window(s); fill_window(s);
if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return need_more; return need_more;
} }
if (s->lookahead == 0) break; /* flush the current block */ if (s->lookahead == 0) break; /* flush the current block */
} }
@@ -1199,10 +1199,10 @@ local block_state deflate_fast(s, flush)
* always MIN_MATCH bytes ahead. * always MIN_MATCH bytes ahead.
*/ */
} while (--s->match_length != 0); } while (--s->match_length != 0);
s->strstart++; s->strstart++;
} else } else
#endif #endif
{ {
s->strstart += s->match_length; s->strstart += s->match_length;
s->match_length = 0; s->match_length = 0;
s->ins_h = s->window[s->strstart]; s->ins_h = s->window[s->strstart];
@@ -1219,7 +1219,7 @@ local block_state deflate_fast(s, flush)
Tracevv((stderr,"%c", s->window[s->strstart])); Tracevv((stderr,"%c", s->window[s->strstart]));
_tr_tally_lit (s, s->window[s->strstart], bflush); _tr_tally_lit (s, s->window[s->strstart], bflush);
s->lookahead--; s->lookahead--;
s->strstart++; s->strstart++;
} }
if (bflush) FLUSH_BLOCK(s, 0); if (bflush) FLUSH_BLOCK(s, 0);
} }
@@ -1249,8 +1249,8 @@ local block_state deflate_slow(s, flush)
if (s->lookahead < MIN_LOOKAHEAD) { if (s->lookahead < MIN_LOOKAHEAD) {
fill_window(s); fill_window(s);
if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) { if (s->lookahead < MIN_LOOKAHEAD && flush == Z_NO_FLUSH) {
return need_more; return need_more;
} }
if (s->lookahead == 0) break; /* flush the current block */ if (s->lookahead == 0) break; /* flush the current block */
} }
@@ -1297,7 +1297,7 @@ local block_state deflate_slow(s, flush)
check_match(s, s->strstart-1, s->prev_match, s->prev_length); check_match(s, s->strstart-1, s->prev_match, s->prev_length);
_tr_tally_dist(s, s->strstart -1 - s->prev_match, _tr_tally_dist(s, s->strstart -1 - s->prev_match,
s->prev_length - MIN_MATCH, bflush); s->prev_length - MIN_MATCH, bflush);
/* Insert in hash table all strings up to the end of the match. /* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not * strstart-1 and strstart are already inserted. If there is not
@@ -1323,8 +1323,8 @@ local block_state deflate_slow(s, flush)
* is longer, truncate the previous match to a single literal. * is longer, truncate the previous match to a single literal.
*/ */
Tracevv((stderr,"%c", s->window[s->strstart-1])); Tracevv((stderr,"%c", s->window[s->strstart-1]));
_tr_tally_lit(s, s->window[s->strstart-1], bflush); _tr_tally_lit(s, s->window[s->strstart-1], bflush);
if (bflush) { if (bflush) {
FLUSH_BLOCK_ONLY(s, 0); FLUSH_BLOCK_ONLY(s, 0);
} }
s->strstart++; s->strstart++;
@@ -1,6 +1,6 @@
/* deflate.h -- internal compression state /* deflate.h -- internal compression state
* Copyright (C) 1995-2002 Jean-loup Gailly * Copyright (C) 1995-2002 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* WARNING: this file should *not* be used by applications. It is /* WARNING: this file should *not* be used by applications. It is
@@ -269,7 +269,7 @@ typedef struct internal_state {
void _tr_init OF((deflate_state *s)); void _tr_init OF((deflate_state *s));
int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc)); int _tr_tally OF((deflate_state *s, unsigned dist, unsigned lc));
void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len, void _tr_flush_block OF((deflate_state *s, charf *buf, ulg stored_len,
int eof)); int eof));
void _tr_align OF((deflate_state *s)); void _tr_align OF((deflate_state *s));
void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len, void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
int eof)); int eof));
@@ -312,8 +312,7 @@ void _tr_stored_block OF((deflate_state *s, charf *buf, ulg stored_len,
#else #else
# define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c) # define _tr_tally_lit(s, c, flush) flush = _tr_tally(s, 0, c)
# define _tr_tally_dist(s, distance, length, flush) \ # define _tr_tally_dist(s, distance, length, flush) \
flush = _tr_tally(s, distance, length) flush = _tr_tally(s, distance, length)
#endif #endif
#endif #endif
@@ -1,6 +1,6 @@
/* example.c -- usage example of the zlib compression library /* example.c -- usage example of the zlib compression library
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* @(#) $Id$ */ /* @(#) $Id$ */
@@ -37,22 +37,22 @@ const char dictionary[] = "hello";
uLong dictId; /* Adler32 value of the dictionary */ uLong dictId; /* Adler32 value of the dictionary */
void test_compress OF((Byte *compr, uLong comprLen, void test_compress OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen)); Byte *uncompr, uLong uncomprLen));
void test_gzio OF((const char *out, const char *in, void test_gzio OF((const char *out, const char *in,
Byte *uncompr, int uncomprLen)); Byte *uncompr, int uncomprLen));
void test_deflate OF((Byte *compr, uLong comprLen)); void test_deflate OF((Byte *compr, uLong comprLen));
void test_inflate OF((Byte *compr, uLong comprLen, void test_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen)); Byte *uncompr, uLong uncomprLen));
void test_large_deflate OF((Byte *compr, uLong comprLen, void test_large_deflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen)); Byte *uncompr, uLong uncomprLen));
void test_large_inflate OF((Byte *compr, uLong comprLen, void test_large_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen)); Byte *uncompr, uLong uncomprLen));
void test_flush OF((Byte *compr, uLong *comprLen)); void test_flush OF((Byte *compr, uLong *comprLen));
void test_sync OF((Byte *compr, uLong comprLen, void test_sync OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen)); Byte *uncompr, uLong uncomprLen));
void test_dict_deflate OF((Byte *compr, uLong comprLen)); void test_dict_deflate OF((Byte *compr, uLong comprLen));
void test_dict_inflate OF((Byte *compr, uLong comprLen, void test_dict_inflate OF((Byte *compr, uLong comprLen,
Byte *uncompr, uLong uncomprLen)); Byte *uncompr, uLong uncomprLen));
int main OF((int argc, char *argv[])); int main OF((int argc, char *argv[]));
/* =========================================================================== /* ===========================================================================
@@ -75,7 +75,7 @@ void test_compress(compr, comprLen, uncompr, uncomprLen)
if (strcmp((char*)uncompr, hello)) { if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad uncompress\n"); fprintf(stderr, "bad uncompress\n");
exit(1); exit(1);
} else { } else {
printf("uncompress(): %s\n", (char *)uncompr); printf("uncompress(): %s\n", (char *)uncompr);
} }
@@ -103,11 +103,11 @@ void test_gzio(out, in, uncompr, uncomprLen)
gzputc(file, 'h'); gzputc(file, 'h');
if (gzputs(file, "ello") != 4) { if (gzputs(file, "ello") != 4) {
fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err)); fprintf(stderr, "gzputs err: %s\n", gzerror(file, &err));
exit(1); exit(1);
} }
if (gzprintf(file, ", %s!", "hello") != 8) { if (gzprintf(file, ", %s!", "hello") != 8) {
fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err)); fprintf(stderr, "gzprintf err: %s\n", gzerror(file, &err));
exit(1); exit(1);
} }
gzseek(file, 1L, SEEK_CUR); /* add one zero byte */ gzseek(file, 1L, SEEK_CUR); /* add one zero byte */
gzclose(file); gzclose(file);
@@ -121,36 +121,36 @@ void test_gzio(out, in, uncompr, uncomprLen)
uncomprLen = gzread(file, uncompr, (unsigned)uncomprLen); uncomprLen = gzread(file, uncompr, (unsigned)uncomprLen);
if (uncomprLen != len) { if (uncomprLen != len) {
fprintf(stderr, "gzread err: %s\n", gzerror(file, &err)); fprintf(stderr, "gzread err: %s\n", gzerror(file, &err));
exit(1); exit(1);
} }
if (strcmp((char*)uncompr, hello)) { if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad gzread: %s\n", (char*)uncompr); fprintf(stderr, "bad gzread: %s\n", (char*)uncompr);
exit(1); exit(1);
} else { } else {
printf("gzread(): %s\n", (char *)uncompr); printf("gzread(): %s\n", (char *)uncompr);
} }
pos = gzseek(file, -8L, SEEK_CUR); pos = gzseek(file, -8L, SEEK_CUR);
if (pos != 6 || gztell(file) != pos) { if (pos != 6 || gztell(file) != pos) {
fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n", fprintf(stderr, "gzseek error, pos=%ld, gztell=%ld\n",
(long)pos, (long)gztell(file)); (long)pos, (long)gztell(file));
exit(1); exit(1);
} }
if (gzgetc(file) != ' ') { if (gzgetc(file) != ' ') {
fprintf(stderr, "gzgetc error\n"); fprintf(stderr, "gzgetc error\n");
exit(1); exit(1);
} }
gzgets(file, (char*)uncompr, uncomprLen); gzgets(file, (char*)uncompr, uncomprLen);
uncomprLen = strlen((char*)uncompr); uncomprLen = strlen((char*)uncompr);
if (uncomprLen != 6) { /* "hello!" */ if (uncomprLen != 6) { /* "hello!" */
fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err)); fprintf(stderr, "gzgets err after gzseek: %s\n", gzerror(file, &err));
exit(1); exit(1);
} }
if (strcmp((char*)uncompr, hello+7)) { if (strcmp((char*)uncompr, hello+7)) {
fprintf(stderr, "bad gzgets after gzseek\n"); fprintf(stderr, "bad gzgets after gzseek\n");
exit(1); exit(1);
} else { } else {
printf("gzgets() after gzseek: %s\n", (char *)uncompr); printf("gzgets() after gzseek: %s\n", (char *)uncompr);
} }
@@ -231,7 +231,7 @@ void test_inflate(compr, comprLen, uncompr, uncomprLen)
if (strcmp((char*)uncompr, hello)) { if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate\n"); fprintf(stderr, "bad inflate\n");
exit(1); exit(1);
} else { } else {
printf("inflate(): %s\n", (char *)uncompr); printf("inflate(): %s\n", (char *)uncompr);
} }
@@ -266,7 +266,7 @@ void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
CHECK_ERR(err, "deflate"); CHECK_ERR(err, "deflate");
if (c_stream.avail_in != 0) { if (c_stream.avail_in != 0) {
fprintf(stderr, "deflate not greedy\n"); fprintf(stderr, "deflate not greedy\n");
exit(1); exit(1);
} }
/* Feed in already compressed data and switch to no compression: */ /* Feed in already compressed data and switch to no compression: */
@@ -286,7 +286,7 @@ void test_large_deflate(compr, comprLen, uncompr, uncomprLen)
err = deflate(&c_stream, Z_FINISH); err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) { if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n"); fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1); exit(1);
} }
err = deflateEnd(&c_stream); err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd"); CHECK_ERR(err, "deflateEnd");
@@ -316,7 +316,7 @@ void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
for (;;) { for (;;) {
d_stream.next_out = uncompr; /* discard the output */ d_stream.next_out = uncompr; /* discard the output */
d_stream.avail_out = (uInt)uncomprLen; d_stream.avail_out = (uInt)uncomprLen;
err = inflate(&d_stream, Z_NO_FLUSH); err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break; if (err == Z_STREAM_END) break;
CHECK_ERR(err, "large inflate"); CHECK_ERR(err, "large inflate");
@@ -327,7 +327,7 @@ void test_large_inflate(compr, comprLen, uncompr, uncomprLen)
if (d_stream.total_out != 2*uncomprLen + comprLen/2) { if (d_stream.total_out != 2*uncomprLen + comprLen/2) {
fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out); fprintf(stderr, "bad large inflate: %ld\n", d_stream.total_out);
exit(1); exit(1);
} else { } else {
printf("large_inflate(): OK\n"); printf("large_inflate(): OK\n");
} }
@@ -407,7 +407,7 @@ void test_sync(compr, comprLen, uncompr, uncomprLen)
if (err != Z_DATA_ERROR) { if (err != Z_DATA_ERROR) {
fprintf(stderr, "inflate should report DATA_ERROR\n"); fprintf(stderr, "inflate should report DATA_ERROR\n");
/* Because of incorrect adler32 */ /* Because of incorrect adler32 */
exit(1); exit(1);
} }
err = inflateEnd(&d_stream); err = inflateEnd(&d_stream);
CHECK_ERR(err, "inflateEnd"); CHECK_ERR(err, "inflateEnd");
@@ -433,7 +433,7 @@ void test_dict_deflate(compr, comprLen)
CHECK_ERR(err, "deflateInit"); CHECK_ERR(err, "deflateInit");
err = deflateSetDictionary(&c_stream, err = deflateSetDictionary(&c_stream,
(const Bytef*)dictionary, sizeof(dictionary)); (const Bytef*)dictionary, sizeof(dictionary));
CHECK_ERR(err, "deflateSetDictionary"); CHECK_ERR(err, "deflateSetDictionary");
dictId = c_stream.adler; dictId = c_stream.adler;
@@ -446,7 +446,7 @@ void test_dict_deflate(compr, comprLen)
err = deflate(&c_stream, Z_FINISH); err = deflate(&c_stream, Z_FINISH);
if (err != Z_STREAM_END) { if (err != Z_STREAM_END) {
fprintf(stderr, "deflate should report Z_STREAM_END\n"); fprintf(stderr, "deflate should report Z_STREAM_END\n");
exit(1); exit(1);
} }
err = deflateEnd(&c_stream); err = deflateEnd(&c_stream);
CHECK_ERR(err, "deflateEnd"); CHECK_ERR(err, "deflateEnd");
@@ -480,14 +480,14 @@ void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
for (;;) { for (;;) {
err = inflate(&d_stream, Z_NO_FLUSH); err = inflate(&d_stream, Z_NO_FLUSH);
if (err == Z_STREAM_END) break; if (err == Z_STREAM_END) break;
if (err == Z_NEED_DICT) { if (err == Z_NEED_DICT) {
if (d_stream.adler != dictId) { if (d_stream.adler != dictId) {
fprintf(stderr, "unexpected dictionary"); fprintf(stderr, "unexpected dictionary");
exit(1); exit(1);
} }
err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary, err = inflateSetDictionary(&d_stream, (const Bytef*)dictionary,
sizeof(dictionary)); sizeof(dictionary));
} }
CHECK_ERR(err, "inflate with dict"); CHECK_ERR(err, "inflate with dict");
} }
@@ -496,7 +496,7 @@ void test_dict_inflate(compr, comprLen, uncompr, uncomprLen)
if (strcmp((char*)uncompr, hello)) { if (strcmp((char*)uncompr, hello)) {
fprintf(stderr, "bad inflate with dict\n"); fprintf(stderr, "bad inflate with dict\n");
exit(1); exit(1);
} else { } else {
printf("inflate with dictionary: %s\n", (char *)uncompr); printf("inflate with dictionary: %s\n", (char *)uncompr);
} }
@@ -530,13 +530,13 @@ int main(argc, argv)
*/ */
if (compr == Z_NULL || uncompr == Z_NULL) { if (compr == Z_NULL || uncompr == Z_NULL) {
printf("out of memory\n"); printf("out of memory\n");
exit(1); exit(1);
} }
test_compress(compr, comprLen, uncompr, uncomprLen); test_compress(compr, comprLen, uncompr, uncomprLen);
test_gzio((argc > 1 ? argv[1] : TESTFILE), test_gzio((argc > 1 ? argv[1] : TESTFILE),
(argc > 2 ? argv[2] : TESTFILE), (argc > 2 ? argv[2] : TESTFILE),
uncompr, (int)uncomprLen); uncompr, (int)uncomprLen);
test_deflate(compr, comprLen); test_deflate(compr, comprLen);
test_inflate(compr, comprLen, uncompr, uncomprLen); test_inflate(compr, comprLen, uncompr, uncomprLen);
+151 -151
View File
@@ -112,17 +112,17 @@ local gzFile gz_open (path, mode, fd)
if (*p == 'r') s->mode = 'r'; if (*p == 'r') s->mode = 'r';
if (*p == 'w' || *p == 'a') s->mode = 'w'; if (*p == 'w' || *p == 'a') s->mode = 'w';
if (*p >= '0' && *p <= '9') { if (*p >= '0' && *p <= '9') {
level = *p - '0'; level = *p - '0';
} else if (*p == 'f') { } else if (*p == 'f') {
strategy = Z_FILTERED; strategy = Z_FILTERED;
} else if (*p == 'h') { } else if (*p == 'h') {
strategy = Z_HUFFMAN_ONLY; strategy = Z_HUFFMAN_ONLY;
} else { } else {
*m++ = *p; /* copy the mode */ *m++ = *p; /* copy the mode */
} }
} while (*p++ && m != fmode + sizeof(fmode)); } while (*p++ && m != fmode + sizeof(fmode));
if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL; if (s->mode == '\0') return destroy(s), (gzFile)Z_NULL;
if (s->mode == 'w') { if (s->mode == 'w') {
#ifdef NO_DEFLATE #ifdef NO_DEFLATE
err = Z_STREAM_ERROR; err = Z_STREAM_ERROR;
@@ -163,17 +163,17 @@ local gzFile gz_open (path, mode, fd)
*/ */
fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1], fprintf(s->file, "%c%c%c%c%c%c%c%c%c%c", gz_magic[0], gz_magic[1],
Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE); Z_DEFLATED, 0 /*flags*/, 0,0,0,0 /*time*/, 0 /*xflags*/, OS_CODE);
s->startpos = 10L; s->startpos = 10L;
/* We use 10L instead of ftell(s->file) to because ftell causes an /* We use 10L instead of ftell(s->file) to because ftell causes an
* fflush on some systems. This version of the library doesn't use * fflush on some systems. This version of the library doesn't use
* startpos anyway in write mode, so this initialization is not * startpos anyway in write mode, so this initialization is not
* necessary. * necessary.
*/ */
} else { } else {
check_header(s); /* skip the .gz header */ check_header(s); /* skip the .gz header */
s->startpos = (ftell(s->file) - s->stream.avail_in); s->startpos = (ftell(s->file) - s->stream.avail_in);
} }
return (gzFile)s; return (gzFile)s;
} }
@@ -218,11 +218,11 @@ int ZEXPORT gzsetparams (file, level, strategy)
/* Make room to allow flushing */ /* Make room to allow flushing */
if (s->stream.avail_out == 0) { if (s->stream.avail_out == 0) {
s->stream.next_out = s->outbuf; s->stream.next_out = s->outbuf;
if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) { if (fwrite(s->outbuf, 1, Z_BUFSIZE, s->file) != Z_BUFSIZE) {
s->z_err = Z_ERRNO; s->z_err = Z_ERRNO;
} }
s->stream.avail_out = Z_BUFSIZE; s->stream.avail_out = Z_BUFSIZE;
} }
return deflateParams (&(s->stream), level, strategy); return deflateParams (&(s->stream), level, strategy);
@@ -238,14 +238,14 @@ local int get_byte(s)
{ {
if (s->z_eof) return EOF; if (s->z_eof) return EOF;
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
errno = 0; errno = 0;
s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
s->z_eof = 1; s->z_eof = 1;
if (ferror(s->file)) s->z_err = Z_ERRNO; if (ferror(s->file)) s->z_err = Z_ERRNO;
return EOF; return EOF;
} }
s->stream.next_in = s->inbuf; s->stream.next_in = s->inbuf;
} }
s->stream.avail_in--; s->stream.avail_in--;
return *(s->stream.next_in)++; return *(s->stream.next_in)++;
@@ -270,41 +270,41 @@ local void check_header(s)
/* Check the gzip magic header */ /* Check the gzip magic header */
for (len = 0; len < 2; len++) { for (len = 0; len < 2; len++) {
c = get_byte(s); c = get_byte(s);
if (c != gz_magic[len]) { if (c != gz_magic[len]) {
if (len != 0) s->stream.avail_in++, s->stream.next_in--; if (len != 0) s->stream.avail_in++, s->stream.next_in--;
if (c != EOF) { if (c != EOF) {
s->stream.avail_in++, s->stream.next_in--; s->stream.avail_in++, s->stream.next_in--;
s->transparent = 1; s->transparent = 1;
} }
s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END; s->z_err = s->stream.avail_in != 0 ? Z_OK : Z_STREAM_END;
return; return;
} }
} }
method = get_byte(s); method = get_byte(s);
flags = get_byte(s); flags = get_byte(s);
if (method != Z_DEFLATED || (flags & RESERVED) != 0) { if (method != Z_DEFLATED || (flags & RESERVED) != 0) {
s->z_err = Z_DATA_ERROR; s->z_err = Z_DATA_ERROR;
return; return;
} }
/* Discard time, xflags and OS code: */ /* Discard time, xflags and OS code: */
for (len = 0; len < 6; len++) (void)get_byte(s); for (len = 0; len < 6; len++) (void)get_byte(s);
if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */ if ((flags & EXTRA_FIELD) != 0) { /* skip the extra field */
len = (uInt)get_byte(s); len = (uInt)get_byte(s);
len += ((uInt)get_byte(s))<<8; len += ((uInt)get_byte(s))<<8;
/* len is garbage if EOF but the loop below will quit anyway */ /* len is garbage if EOF but the loop below will quit anyway */
while (len-- != 0 && get_byte(s) != EOF) ; while (len-- != 0 && get_byte(s) != EOF) ;
} }
if ((flags & ORIG_NAME) != 0) { /* skip the original file name */ if ((flags & ORIG_NAME) != 0) { /* skip the original file name */
while ((c = get_byte(s)) != 0 && c != EOF) ; while ((c = get_byte(s)) != 0 && c != EOF) ;
} }
if ((flags & COMMENT) != 0) { /* skip the .gz file comment */ if ((flags & COMMENT) != 0) { /* skip the .gz file comment */
while ((c = get_byte(s)) != 0 && c != EOF) ; while ((c = get_byte(s)) != 0 && c != EOF) ;
} }
if ((flags & HEAD_CRC) != 0) { /* skip the header crc */ if ((flags & HEAD_CRC) != 0) { /* skip the header crc */
for (len = 0; len < 2; len++) (void)get_byte(s); for (len = 0; len < 2; len++) (void)get_byte(s);
} }
s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK; s->z_err = s->z_eof ? Z_DATA_ERROR : Z_OK;
} }
@@ -323,21 +323,21 @@ local int destroy (s)
TRYFREE(s->msg); TRYFREE(s->msg);
if (s->stream.state != NULL) { if (s->stream.state != NULL) {
if (s->mode == 'w') { if (s->mode == 'w') {
#ifdef NO_DEFLATE #ifdef NO_DEFLATE
err = Z_STREAM_ERROR; err = Z_STREAM_ERROR;
#else #else
err = deflateEnd(&(s->stream)); err = deflateEnd(&(s->stream));
#endif #endif
} else if (s->mode == 'r') { } else if (s->mode == 'r') {
err = inflateEnd(&(s->stream)); err = inflateEnd(&(s->stream));
} }
} }
if (s->file != NULL && fclose(s->file)) { if (s->file != NULL && fclose(s->file)) {
#ifdef ESPIPE #ifdef ESPIPE
if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */ if (errno != ESPIPE) /* fclose is broken for pipes in HP/UX */
#endif #endif
err = Z_ERRNO; err = Z_ERRNO;
} }
if (s->z_err < 0) err = s->z_err; if (s->z_err < 0) err = s->z_err;
@@ -372,69 +372,69 @@ int ZEXPORT gzread (file, buf, len)
while (s->stream.avail_out != 0) { while (s->stream.avail_out != 0) {
if (s->transparent) { if (s->transparent) {
/* Copy first the lookahead bytes: */ /* Copy first the lookahead bytes: */
uInt n = s->stream.avail_in; uInt n = s->stream.avail_in;
if (n > s->stream.avail_out) n = s->stream.avail_out; if (n > s->stream.avail_out) n = s->stream.avail_out;
if (n > 0) { if (n > 0) {
zmemcpy(s->stream.next_out, s->stream.next_in, n); zmemcpy(s->stream.next_out, s->stream.next_in, n);
next_out += n; next_out += n;
s->stream.next_out = next_out; s->stream.next_out = next_out;
s->stream.next_in += n; s->stream.next_in += n;
s->stream.avail_out -= n; s->stream.avail_out -= n;
s->stream.avail_in -= n; s->stream.avail_in -= n;
} }
if (s->stream.avail_out > 0) { if (s->stream.avail_out > 0) {
s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out, s->stream.avail_out -= fread(next_out, 1, s->stream.avail_out,
s->file); s->file);
} }
len -= s->stream.avail_out; len -= s->stream.avail_out;
s->stream.total_in += (uLong)len; s->stream.total_in += (uLong)len;
s->stream.total_out += (uLong)len; s->stream.total_out += (uLong)len;
if (len == 0) s->z_eof = 1; if (len == 0) s->z_eof = 1;
return (int)len; return (int)len;
} }
if (s->stream.avail_in == 0 && !s->z_eof) { if (s->stream.avail_in == 0 && !s->z_eof) {
errno = 0; errno = 0;
s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file); s->stream.avail_in = fread(s->inbuf, 1, Z_BUFSIZE, s->file);
if (s->stream.avail_in == 0) { if (s->stream.avail_in == 0) {
s->z_eof = 1; s->z_eof = 1;
if (ferror(s->file)) { if (ferror(s->file)) {
s->z_err = Z_ERRNO; s->z_err = Z_ERRNO;
break; break;
} }
} }
s->stream.next_in = s->inbuf; s->stream.next_in = s->inbuf;
} }
s->z_err = inflate(&(s->stream), Z_NO_FLUSH); s->z_err = inflate(&(s->stream), Z_NO_FLUSH);
if (s->z_err == Z_STREAM_END) { if (s->z_err == Z_STREAM_END) {
/* Check CRC and original size */ /* Check CRC and original size */
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
start = s->stream.next_out; start = s->stream.next_out;
if (getLong(s) != s->crc) { if (getLong(s) != s->crc) {
s->z_err = Z_DATA_ERROR; s->z_err = Z_DATA_ERROR;
} else { } else {
(void)getLong(s); (void)getLong(s);
/* The uncompressed length returned by above getlong() may /* The uncompressed length returned by above getlong() may
* be different from s->stream.total_out) in case of * be different from s->stream.total_out) in case of
* concatenated .gz files. Check for such files: * concatenated .gz files. Check for such files:
*/ */
check_header(s); check_header(s);
if (s->z_err == Z_OK) { if (s->z_err == Z_OK) {
uLong total_in = s->stream.total_in; uLong total_in = s->stream.total_in;
uLong total_out = s->stream.total_out; uLong total_out = s->stream.total_out;
inflateReset(&(s->stream)); inflateReset(&(s->stream));
s->stream.total_in = total_in; s->stream.total_in = total_in;
s->stream.total_out = total_out; s->stream.total_out = total_out;
s->crc = crc32(0L, Z_NULL, 0); s->crc = crc32(0L, Z_NULL, 0);
} }
} }
} }
if (s->z_err != Z_OK || s->z_eof) break; if (s->z_err != Z_OK || s->z_eof) break;
} }
s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start)); s->crc = crc32(s->crc, start, (uInt)(s->stream.next_out - start));
@@ -543,21 +543,21 @@ int ZEXPORTVA gzprintf (gzFile file, const char *format, /* args */ ...)
#else /* not ANSI C */ #else /* not ANSI C */
int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, int ZEXPORTVA gzprintf (file, format, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20) a11, a12, a13, a14, a15, a16, a17, a18, a19, a20)
gzFile file; gzFile file;
const char *format; const char *format;
int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, int a1, a2, a3, a4, a5, a6, a7, a8, a9, a10,
a11, a12, a13, a14, a15, a16, a17, a18, a19, a20; a11, a12, a13, a14, a15, a16, a17, a18, a19, a20;
{ {
char buf[Z_PRINTF_BUFSIZE]; char buf[Z_PRINTF_BUFSIZE];
int len; int len;
#ifdef HAS_snprintf #ifdef HAS_snprintf
snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8, snprintf(buf, sizeof(buf), format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
#else #else
sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8, sprintf(buf, format, a1, a2, a3, a4, a5, a6, a7, a8,
a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20); a9, a10, a11, a12, a13, a14, a15, a16, a17, a18, a19, a20);
#endif #endif
len = strlen(buf); /* old sprintf doesn't return the nb of bytes written */ len = strlen(buf); /* old sprintf doesn't return the nb of bytes written */
if (len <= 0) return 0; if (len <= 0) return 0;
@@ -623,14 +623,14 @@ local int do_flush (file, flush)
if (done) break; if (done) break;
s->z_err = deflate(&(s->stream), flush); s->z_err = deflate(&(s->stream), flush);
/* Ignore the second of two consecutive flushes: */ /* Ignore the second of two consecutive flushes: */
if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK; if (len == 0 && s->z_err == Z_BUF_ERROR) s->z_err = Z_OK;
/* deflate has finished flushing only when it hasn't used up /* deflate has finished flushing only when it hasn't used up
* all the available space in the output buffer: * all the available space in the output buffer:
*/ */
done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END); done = (s->stream.avail_out != 0 || s->z_err == Z_STREAM_END);
if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break; if (s->z_err != Z_OK && s->z_err != Z_STREAM_END) break;
} }
return s->z_err == Z_STREAM_END ? Z_OK : s->z_err; return s->z_err == Z_STREAM_END ? Z_OK : s->z_err;
@@ -665,84 +665,84 @@ z_off_t ZEXPORT gzseek (file, offset, whence)
gz_stream *s = (gz_stream*)file; gz_stream *s = (gz_stream*)file;
if (s == NULL || whence == SEEK_END || if (s == NULL || whence == SEEK_END ||
s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) { s->z_err == Z_ERRNO || s->z_err == Z_DATA_ERROR) {
return -1L; return -1L;
} }
if (s->mode == 'w') { if (s->mode == 'w') {
#ifdef NO_DEFLATE #ifdef NO_DEFLATE
return -1L; return -1L;
#else #else
if (whence == SEEK_SET) { if (whence == SEEK_SET) {
offset -= s->stream.total_in; offset -= s->stream.total_in;
} }
if (offset < 0) return -1L; if (offset < 0) return -1L;
/* At this point, offset is the number of zero bytes to write. */ /* At this point, offset is the number of zero bytes to write. */
if (s->inbuf == Z_NULL) { if (s->inbuf == Z_NULL) {
s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */ s->inbuf = (Byte*)ALLOC(Z_BUFSIZE); /* for seeking */
zmemzero(s->inbuf, Z_BUFSIZE); zmemzero(s->inbuf, Z_BUFSIZE);
} }
while (offset > 0) { while (offset > 0) {
uInt size = Z_BUFSIZE; uInt size = Z_BUFSIZE;
if (offset < Z_BUFSIZE) size = (uInt)offset; if (offset < Z_BUFSIZE) size = (uInt)offset;
size = gzwrite(file, s->inbuf, size); size = gzwrite(file, s->inbuf, size);
if (size == 0) return -1L; if (size == 0) return -1L;
offset -= size; offset -= size;
} }
return (z_off_t)s->stream.total_in; return (z_off_t)s->stream.total_in;
#endif #endif
} }
/* Rest of function is for reading only */ /* Rest of function is for reading only */
/* compute absolute position */ /* compute absolute position */
if (whence == SEEK_CUR) { if (whence == SEEK_CUR) {
offset += s->stream.total_out; offset += s->stream.total_out;
} }
if (offset < 0) return -1L; if (offset < 0) return -1L;
if (s->transparent) { if (s->transparent) {
/* map to fseek */ /* map to fseek */
s->stream.avail_in = 0; s->stream.avail_in = 0;
s->stream.next_in = s->inbuf; s->stream.next_in = s->inbuf;
if (fseek(s->file, offset, SEEK_SET) < 0) return -1L; if (fseek(s->file, offset, SEEK_SET) < 0) return -1L;
s->stream.total_in = s->stream.total_out = (uLong)offset; s->stream.total_in = s->stream.total_out = (uLong)offset;
return offset; return offset;
} }
/* For a negative seek, rewind and use positive seek */ /* For a negative seek, rewind and use positive seek */
if ((uLong)offset >= s->stream.total_out) { if ((uLong)offset >= s->stream.total_out) {
offset -= s->stream.total_out; offset -= s->stream.total_out;
} else if (gzrewind(file) < 0) { } else if (gzrewind(file) < 0) {
return -1L; return -1L;
} }
/* offset is now the number of bytes to skip. */ /* offset is now the number of bytes to skip. */
if (offset != 0 && s->outbuf == Z_NULL) { if (offset != 0 && s->outbuf == Z_NULL) {
s->outbuf = (Byte*)ALLOC(Z_BUFSIZE); s->outbuf = (Byte*)ALLOC(Z_BUFSIZE);
} }
while (offset > 0) { while (offset > 0) {
int size = Z_BUFSIZE; int size = Z_BUFSIZE;
if (offset < Z_BUFSIZE) size = (int)offset; if (offset < Z_BUFSIZE) size = (int)offset;
size = gzread(file, s->outbuf, (uInt)size); size = gzread(file, s->outbuf, (uInt)size);
if (size <= 0) return -1L; if (size <= 0) return -1L;
offset -= size; offset -= size;
} }
return (z_off_t)s->stream.total_out; return (z_off_t)s->stream.total_out;
} }
/* =========================================================================== /* ===========================================================================
Rewinds input file. Rewinds input file.
*/ */
int ZEXPORT gzrewind (file) int ZEXPORT gzrewind (file)
gzFile file; gzFile file;
{ {
gz_stream *s = (gz_stream*)file; gz_stream *s = (gz_stream*)file;
if (s == NULL || s->mode != 'r') return -1; if (s == NULL || s->mode != 'r') return -1;
s->z_err = Z_OK; s->z_err = Z_OK;
@@ -750,10 +750,10 @@ int ZEXPORT gzrewind (file)
s->stream.avail_in = 0; s->stream.avail_in = 0;
s->stream.next_in = s->inbuf; s->stream.next_in = s->inbuf;
s->crc = crc32(0L, Z_NULL, 0); s->crc = crc32(0L, Z_NULL, 0);
if (s->startpos == 0) { /* not a compressed file */ if (s->startpos == 0) { /* not a compressed file */
rewind(s->file); rewind(s->file);
return 0; return 0;
} }
(void) inflateReset(&s->stream); (void) inflateReset(&s->stream);
@@ -779,7 +779,7 @@ int ZEXPORT gzeof (file)
gzFile file; gzFile file;
{ {
gz_stream *s = (gz_stream*)file; gz_stream *s = (gz_stream*)file;
return (s == NULL || s->mode != 'r') ? 0 : s->z_eof; return (s == NULL || s->mode != 'r') ? 0 : s->z_eof;
} }
@@ -829,7 +829,7 @@ int ZEXPORT gzclose (file)
if (s->mode == 'w') { if (s->mode == 'w') {
#ifdef NO_DEFLATE #ifdef NO_DEFLATE
return Z_STREAM_ERROR; return Z_STREAM_ERROR;
#else #else
err = do_flush (file, Z_FINISH); err = do_flush (file, Z_FINISH);
if (err != Z_OK) return destroy((gz_stream*)file); if (err != Z_OK) return destroy((gz_stream*)file);
@@ -1,6 +1,6 @@
/* infblock.c -- interpret and process block types to last block /* infblock.c -- interpret and process block types to last block
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
#include "zutil.h" #include "zutil.h"
@@ -393,7 +393,7 @@ uInt n;
/* Returns true if inflate is currently at the end of a block generated /* Returns true if inflate is currently at the end of a block generated
* by Z_SYNC_FLUSH or Z_FULL_FLUSH. * by Z_SYNC_FLUSH or Z_FULL_FLUSH.
* IN assertion: s != Z_NULL * IN assertion: s != Z_NULL
*/ */
int inflate_blocks_sync_point(s) int inflate_blocks_sync_point(s)
@@ -1,6 +1,6 @@
/* infblock.h -- header to use infblock.c /* infblock.h -- header to use infblock.c
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* WARNING: this file should *not* be used by applications. It is /* WARNING: this file should *not* be used by applications. It is
@@ -37,4 +37,3 @@ extern void inflate_set_dictionary OF((
extern int inflate_blocks_sync_point OF(( extern int inflate_blocks_sync_point OF((
inflate_blocks_statef *s)); inflate_blocks_statef *s));
@@ -1,6 +1,6 @@
/* infcodes.c -- process literals and length/distance pairs /* infcodes.c -- process literals and length/distance pairs
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
#include "zutil.h" #include "zutil.h"
@@ -1,6 +1,6 @@
/* infcodes.h -- header to use infcodes.c /* infcodes.h -- header to use infcodes.c
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* WARNING: this file should *not* be used by applications. It is /* WARNING: this file should *not* be used by applications. It is
@@ -25,4 +25,3 @@ extern void inflate_codes_free OF((
inflate_codes_statef *, inflate_codes_statef *,
z_streamp )); z_streamp ));
@@ -1,6 +1,6 @@
/* inffast.c -- process literals and length/distance pairs fast /* inffast.c -- process literals and length/distance pairs fast
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
#include "zutil.h" #include "zutil.h"
@@ -1,6 +1,6 @@
/* inffast.h -- header to use inffast.c /* inffast.h -- header to use inffast.c
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* WARNING: this file should *not* be used by applications. It is /* WARNING: this file should *not* be used by applications. It is
@@ -15,4 +15,3 @@ extern int inflate_fast OF((
inflate_huft *, inflate_huft *,
inflate_blocks_statef *, inflate_blocks_statef *,
z_streamp )); z_streamp ));
@@ -149,4 +149,3 @@ local inflate_huft fixed_td[] = {
{{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289}, {{{80,5}},4}, {{{88,5}},769}, {{{84,5}},49}, {{{92,5}},12289},
{{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577} {{{82,5}},13}, {{{90,5}},3073}, {{{86,5}},193}, {{{192,5}},24577}
}; };
@@ -1,6 +1,6 @@
/* inflate.c -- zlib interface to inflate modules /* inflate.c -- zlib interface to inflate modules
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
#include "zutil.h" #include "zutil.h"
@@ -44,7 +44,7 @@ struct internal_state {
/* mode independent information */ /* mode independent information */
int nowrap; /* flag for no wrapper */ int nowrap; /* flag for no wrapper */
uInt wbits; /* log2(window size) (8..15, defaults to 15) */ uInt wbits; /* log2(window size) (8..15, defaults to 15) */
inflate_blocks_statef inflate_blocks_statef
*blocks; /* current inflate_blocks state */ *blocks; /* current inflate_blocks state */
}; };
@@ -1,6 +1,6 @@
/* inftrees.c -- generate Huffman trees for efficient decoding /* inftrees.c -- generate Huffman trees for efficient decoding
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
#include "zutil.h" #include "zutil.h"
@@ -1,6 +1,6 @@
/* inftrees.h -- header to use inftrees.c /* inftrees.h -- header to use inftrees.c
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* WARNING: this file should *not* be used by applications. It is /* WARNING: this file should *not* be used by applications. It is
@@ -56,4 +56,3 @@ extern int inflate_trees_fixed OF((
inflate_huft * FAR *, /* literal/length tree result */ inflate_huft * FAR *, /* literal/length tree result */
inflate_huft * FAR *, /* distance tree result */ inflate_huft * FAR *, /* distance tree result */
z_streamp)); /* for memory allocation */ z_streamp)); /* for memory allocation */
@@ -1,6 +1,6 @@
/* inflate_util.c -- data and routines common to blocks and codes /* inflate_util.c -- data and routines common to blocks and codes
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
#include "zutil.h" #include "zutil.h"
@@ -1,6 +1,6 @@
/* infutil.h -- types and macros common to blocks and codes /* infutil.h -- types and macros common to blocks and codes
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* WARNING: this file should *not* be used by applications. It is /* WARNING: this file should *not* be used by applications. It is
@@ -41,7 +41,7 @@ struct inflate_blocks_state {
inflate_huft *tb; /* bit length decoding tree */ inflate_huft *tb; /* bit length decoding tree */
} trees; /* if DTREE, decoding info for trees */ } trees; /* if DTREE, decoding info for trees */
struct { struct {
inflate_codes_statef inflate_codes_statef
*codes; *codes;
} decode; /* if CODES, current state */ } decode; /* if CODES, current state */
} sub; /* submode */ } sub; /* submode */
@@ -96,4 +96,3 @@ extern int inflate_flush OF((
struct internal_state {int dummy;}; /* for buggy compilers */ struct internal_state {int dummy;}; /* for buggy compilers */
#endif #endif
@@ -1,6 +1,6 @@
/* maketree.c -- make inffixed.h table for decoding fixed codes /* maketree.c -- make inffixed.h table for decoding fixed codes
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* WARNING: this file should *not* be used by applications. It is /* WARNING: this file should *not* be used by applications. It is
@@ -1,6 +1,6 @@
/* minigzip.c -- simulate gzip using the zlib compression library /* minigzip.c -- simulate gzip using the zlib compression library
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* /*
@@ -147,7 +147,7 @@ int gz_compress_mmap(in, out)
if (buf_len <= 0) return Z_ERRNO; if (buf_len <= 0) return Z_ERRNO;
/* Now do the actual mmap: */ /* Now do the actual mmap: */
buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0); buf = mmap((caddr_t) 0, buf_len, PROT_READ, MAP_SHARED, ifd, (off_t)0);
if (buf == (caddr_t)(-1)) return Z_ERRNO; if (buf == (caddr_t)(-1)) return Z_ERRNO;
/* Compress the whole file at once: */ /* Compress the whole file at once: */
@@ -179,8 +179,8 @@ void gz_uncompress(in, out)
if (len == 0) break; if (len == 0) break;
if ((int)fwrite(buf, 1, (unsigned)len, out) != len) { if ((int)fwrite(buf, 1, (unsigned)len, out) != len) {
error("failed fwrite"); error("failed fwrite");
} }
} }
if (fclose(out)) error("failed fclose"); if (fclose(out)) error("failed fclose");
@@ -282,16 +282,16 @@ int main(argc, argv)
while (argc > 0) { while (argc > 0) {
if (strcmp(*argv, "-d") == 0) if (strcmp(*argv, "-d") == 0)
uncompr = 1; uncompr = 1;
else if (strcmp(*argv, "-f") == 0) else if (strcmp(*argv, "-f") == 0)
outmode[3] = 'f'; outmode[3] = 'f';
else if (strcmp(*argv, "-h") == 0) else if (strcmp(*argv, "-h") == 0)
outmode[3] = 'h'; outmode[3] = 'h';
else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' && else if ((*argv)[0] == '-' && (*argv)[1] >= '1' && (*argv)[1] <= '9' &&
(*argv)[2] == 0) (*argv)[2] == 0)
outmode[2] = (*argv)[1]; outmode[2] = (*argv)[1];
else else
break; break;
argc--, argv++; argc--, argv++;
} }
if (argc == 0) { if (argc == 0) {
+39 -39
View File
@@ -1,6 +1,6 @@
/* trees.c -- output deflated data using Huffman coding /* trees.c -- output deflated data using Huffman coding
* Copyright (C) 1995-2002 Jean-loup Gailly * Copyright (C) 1995-2002 Jean-loup Gailly
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* /*
@@ -335,42 +335,42 @@ void gen_trees_header()
Assert (header != NULL, "Can't open trees.h"); Assert (header != NULL, "Can't open trees.h");
fprintf(header, fprintf(header,
"/* header created automatically with -DGEN_TREES_H */\n\n"); "/* header created automatically with -DGEN_TREES_H */\n\n");
fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n"); fprintf(header, "local const ct_data static_ltree[L_CODES+2] = {\n");
for (i = 0; i < L_CODES+2; i++) { for (i = 0; i < L_CODES+2; i++) {
fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code, fprintf(header, "{{%3u},{%3u}}%s", static_ltree[i].Code,
static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5)); static_ltree[i].Len, SEPARATOR(i, L_CODES+1, 5));
} }
fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n"); fprintf(header, "local const ct_data static_dtree[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) { for (i = 0; i < D_CODES; i++) {
fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code, fprintf(header, "{{%2u},{%2u}}%s", static_dtree[i].Code,
static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5)); static_dtree[i].Len, SEPARATOR(i, D_CODES-1, 5));
} }
fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n"); fprintf(header, "const uch _dist_code[DIST_CODE_LEN] = {\n");
for (i = 0; i < DIST_CODE_LEN; i++) { for (i = 0; i < DIST_CODE_LEN; i++) {
fprintf(header, "%2u%s", _dist_code[i], fprintf(header, "%2u%s", _dist_code[i],
SEPARATOR(i, DIST_CODE_LEN-1, 20)); SEPARATOR(i, DIST_CODE_LEN-1, 20));
} }
fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n"); fprintf(header, "const uch _length_code[MAX_MATCH-MIN_MATCH+1]= {\n");
for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) { for (i = 0; i < MAX_MATCH-MIN_MATCH+1; i++) {
fprintf(header, "%2u%s", _length_code[i], fprintf(header, "%2u%s", _length_code[i],
SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20)); SEPARATOR(i, MAX_MATCH-MIN_MATCH, 20));
} }
fprintf(header, "local const int base_length[LENGTH_CODES] = {\n"); fprintf(header, "local const int base_length[LENGTH_CODES] = {\n");
for (i = 0; i < LENGTH_CODES; i++) { for (i = 0; i < LENGTH_CODES; i++) {
fprintf(header, "%1u%s", base_length[i], fprintf(header, "%1u%s", base_length[i],
SEPARATOR(i, LENGTH_CODES-1, 20)); SEPARATOR(i, LENGTH_CODES-1, 20));
} }
fprintf(header, "local const int base_dist[D_CODES] = {\n"); fprintf(header, "local const int base_dist[D_CODES] = {\n");
for (i = 0; i < D_CODES; i++) { for (i = 0; i < D_CODES; i++) {
fprintf(header, "%5u%s", base_dist[i], fprintf(header, "%5u%s", base_dist[i],
SEPARATOR(i, D_CODES-1, 10)); SEPARATOR(i, D_CODES-1, 10));
} }
fclose(header); fclose(header);
@@ -930,39 +930,39 @@ void _tr_flush_block(s, buf, stored_len, eof)
/* Build the Huffman trees unless a stored block is forced */ /* Build the Huffman trees unless a stored block is forced */
if (s->level > 0) { if (s->level > 0) {
/* Check if the file is ascii or binary */ /* Check if the file is ascii or binary */
if (s->data_type == Z_UNKNOWN) set_data_type(s); if (s->data_type == Z_UNKNOWN) set_data_type(s);
/* Construct the literal and distance trees */ /* Construct the literal and distance trees */
build_tree(s, (tree_desc *)(&(s->l_desc))); build_tree(s, (tree_desc *)(&(s->l_desc)));
Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len, Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
s->static_len)); s->static_len));
build_tree(s, (tree_desc *)(&(s->d_desc))); build_tree(s, (tree_desc *)(&(s->d_desc)));
Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len, Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
s->static_len)); s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of /* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations. * the compressed block data, excluding the tree representations.
*/ */
/* Build the bit length tree for the above two trees, and get the index /* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send. * in bl_order of the last bit length code to send.
*/ */
max_blindex = build_bl_tree(s); max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute first the block length in bytes*/ /* Determine the best encoding. Compute first the block length in bytes*/
opt_lenb = (s->opt_len+3+7)>>3; opt_lenb = (s->opt_len+3+7)>>3;
static_lenb = (s->static_len+3+7)>>3; static_lenb = (s->static_len+3+7)>>3;
Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ", Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len, opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
s->last_lit)); s->last_lit));
if (static_lenb <= opt_lenb) opt_lenb = static_lenb; if (static_lenb <= opt_lenb) opt_lenb = static_lenb;
} else { } else {
Assert(buf != (char*)0, "lost buf"); Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */ opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
} }
#ifdef FORCE_STORED #ifdef FORCE_STORED
@@ -1199,7 +1199,7 @@ local void copy_block(s, buf, len, header)
s->last_eob_len = 8; /* enough lookahead for inflate */ s->last_eob_len = 8; /* enough lookahead for inflate */
if (header) { if (header) {
put_short(s, (ush)len); put_short(s, (ush)len);
put_short(s, (ush)~len); put_short(s, (ush)~len);
#ifdef DEBUG #ifdef DEBUG
s->bits_sent += 2*16; s->bits_sent += 2*16;
@@ -126,4 +126,3 @@ local const int base_dist[D_CODES] = {
1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576 1024, 1536, 2048, 3072, 4096, 6144, 8192, 12288, 16384, 24576
}; };
@@ -1,6 +1,6 @@
/* uncompr.c -- decompress a memory buffer /* uncompr.c -- decompress a memory buffer
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* @(#) $Id$ */ /* @(#) $Id$ */
+29 -30
View File
@@ -1,6 +1,6 @@
/* zconf.h -- configuration of the zlib compression library /* zconf.h -- configuration of the zlib compression library
* Copyright (C) 1995-2002 Jean-loup Gailly. * Copyright (C) 1995-2002 Jean-loup Gailly.
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
/* @(#) $Id$ */ /* @(#) $Id$ */
@@ -13,39 +13,39 @@
* compile with -DZ_PREFIX. The "standard" zlib should be compiled without it. * compile with -DZ_PREFIX. The "standard" zlib should be compiled without it.
*/ */
#ifdef Z_PREFIX #ifdef Z_PREFIX
# define deflateInit_ z_deflateInit_ # define deflateInit_ z_deflateInit_
# define deflate z_deflate # define deflate z_deflate
# define deflateEnd z_deflateEnd # define deflateEnd z_deflateEnd
# define inflateInit_ z_inflateInit_ # define inflateInit_ z_inflateInit_
# define inflate z_inflate # define inflate z_inflate
# define inflateEnd z_inflateEnd # define inflateEnd z_inflateEnd
# define deflateInit2_ z_deflateInit2_ # define deflateInit2_ z_deflateInit2_
# define deflateSetDictionary z_deflateSetDictionary # define deflateSetDictionary z_deflateSetDictionary
# define deflateCopy z_deflateCopy # define deflateCopy z_deflateCopy
# define deflateReset z_deflateReset # define deflateReset z_deflateReset
# define deflateParams z_deflateParams # define deflateParams z_deflateParams
# define inflateInit2_ z_inflateInit2_ # define inflateInit2_ z_inflateInit2_
# define inflateSetDictionary z_inflateSetDictionary # define inflateSetDictionary z_inflateSetDictionary
# define inflateSync z_inflateSync # define inflateSync z_inflateSync
# define inflateSyncPoint z_inflateSyncPoint # define inflateSyncPoint z_inflateSyncPoint
# define inflateReset z_inflateReset # define inflateReset z_inflateReset
# define compress z_compress # define compress z_compress
# define compress2 z_compress2 # define compress2 z_compress2
# define uncompress z_uncompress # define uncompress z_uncompress
# define adler32 z_adler32 # define adler32 z_adler32
# define crc32 z_crc32 # define crc32 z_crc32
# define get_crc_table z_get_crc_table # define get_crc_table z_get_crc_table
# define Byte z_Byte # define Byte z_Byte
# define uInt z_uInt # define uInt z_uInt
# define uLong z_uLong # define uLong z_uLong
# define Bytef z_Bytef # define Bytef z_Bytef
# define charf z_charf # define charf z_charf
# define intf z_intf # define intf z_intf
# define uIntf z_uIntf # define uIntf z_uIntf
# define uLongf z_uLongf # define uLongf z_uLongf
# define voidpf z_voidpf # define voidpf z_voidpf
# define voidp z_voidp # define voidp z_voidp
#endif #endif
#if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32) #if (defined(_WIN32) || defined(__WIN32__)) && !defined(WIN32)
@@ -277,4 +277,3 @@ typedef uLong FAR uLongf;
#endif #endif
#endif /* _ZCONF_H */ #endif /* _ZCONF_H */
+15 -16
View File
@@ -39,7 +39,7 @@ extern "C" {
#define ZLIB_VERSION "1.1.4" #define ZLIB_VERSION "1.1.4"
/* /*
The 'zlib' compression library provides in-memory compression and The 'zlib' compression library provides in-memory compression and
decompression functions, including integrity checks of the uncompressed decompression functions, including integrity checks of the uncompressed
data. This version of the library supports only one compression method data. This version of the library supports only one compression method
@@ -175,7 +175,7 @@ ZEXTERN const char * ZEXPORT zlibVersion OF((void));
This check is automatically made by deflateInit and inflateInit. This check is automatically made by deflateInit and inflateInit.
*/ */
/* /*
ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level)); ZEXTERN int ZEXPORT deflateInit OF((z_streamp strm, int level));
Initializes the internal stream state for compression. The fields Initializes the internal stream state for compression. The fields
@@ -253,7 +253,7 @@ ZEXTERN int ZEXPORT deflate OF((z_streamp strm, int flush));
more input data, until it returns with Z_STREAM_END or an error. After more input data, until it returns with Z_STREAM_END or an error. After
deflate has returned Z_STREAM_END, the only possible operations on the deflate has returned Z_STREAM_END, the only possible operations on the
stream are deflateReset or deflateEnd. stream are deflateReset or deflateEnd.
Z_FINISH can be used immediately after deflateInit if all the compression Z_FINISH can be used immediately after deflateInit if all the compression
is to be done in a single step. In this case, avail_out must be at least is to be done in a single step. In this case, avail_out must be at least
0.1% larger than avail_in plus 12 bytes. If deflate does not return 0.1% larger than avail_in plus 12 bytes. If deflate does not return
@@ -290,7 +290,7 @@ ZEXTERN int ZEXPORT deflateEnd OF((z_streamp strm));
*/ */
/* /*
ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm)); ZEXTERN int ZEXPORT inflateInit OF((z_streamp strm));
Initializes the internal stream state for decompression. The fields Initializes the internal stream state for decompression. The fields
@@ -359,7 +359,7 @@ ZEXTERN int ZEXPORT inflate OF((z_streamp strm, int flush));
If a preset dictionary is needed at this point (see inflateSetDictionary If a preset dictionary is needed at this point (see inflateSetDictionary
below), inflate sets strm-adler to the adler32 checksum of the below), inflate sets strm-adler to the adler32 checksum of the
dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise dictionary chosen by the compressor and returns Z_NEED_DICT; otherwise
it sets strm->adler to the adler32 checksum of all output produced it sets strm->adler to the adler32 checksum of all output produced
so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or so far (that is, total_out bytes) and returns Z_OK, Z_STREAM_END or
an error code as described below. At the end of the stream, inflate() an error code as described below. At the end of the stream, inflate()
@@ -397,7 +397,7 @@ ZEXTERN int ZEXPORT inflateEnd OF((z_streamp strm));
The following functions are needed only in some special applications. The following functions are needed only in some special applications.
*/ */
/* /*
ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm, ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
int level, int level,
int method, int method,
@@ -440,7 +440,7 @@ ZEXTERN int ZEXPORT deflateInit2 OF((z_streamp strm,
method). msg is set to null if there is no error message. deflateInit2 does method). msg is set to null if there is no error message. deflateInit2 does
not perform any compression: this will be done by deflate(). not perform any compression: this will be done by deflate().
*/ */
ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm, ZEXTERN int ZEXPORT deflateSetDictionary OF((z_streamp strm,
const Bytef *dictionary, const Bytef *dictionary,
uInt dictLength)); uInt dictLength));
@@ -507,8 +507,8 @@ ZEXTERN int ZEXPORT deflateReset OF((z_streamp strm));
*/ */
ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm, ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
int level, int level,
int strategy)); int strategy));
/* /*
Dynamically update the compression level and compression strategy. The Dynamically update the compression level and compression strategy. The
interpretation of level and strategy is as in deflateInit2. This can be interpretation of level and strategy is as in deflateInit2. This can be
@@ -527,7 +527,7 @@ ZEXTERN int ZEXPORT deflateParams OF((z_streamp strm,
if strm->avail_out was zero. if strm->avail_out was zero.
*/ */
/* /*
ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm, ZEXTERN int ZEXPORT inflateInit2 OF((z_streamp strm,
int windowBits)); int windowBits));
@@ -570,7 +570,7 @@ ZEXTERN int ZEXPORT inflateSetDictionary OF((z_streamp strm,
*/ */
ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm)); ZEXTERN int ZEXPORT inflateSync OF((z_streamp strm));
/* /*
Skips invalid compressed data until a full flush point (see above the Skips invalid compressed data until a full flush point (see above the
description of deflate with Z_FULL_FLUSH) can be found, or until all description of deflate with Z_FULL_FLUSH) can be found, or until all
available input is skipped. No output is provided. available input is skipped. No output is provided.
@@ -701,8 +701,8 @@ ZEXTERN int ZEXPORT gzread OF((gzFile file, voidp buf, unsigned len));
gzread returns the number of uncompressed bytes actually read (0 for gzread returns the number of uncompressed bytes actually read (0 for
end of file, -1 for error). */ end of file, -1 for error). */
ZEXTERN int ZEXPORT gzwrite OF((gzFile file, ZEXTERN int ZEXPORT gzwrite OF((gzFile file,
const voidp buf, unsigned len)); const voidp buf, unsigned len));
/* /*
Writes the given number of uncompressed bytes into the compressed file. Writes the given number of uncompressed bytes into the compressed file.
gzwrite returns the number of uncompressed bytes actually written gzwrite returns the number of uncompressed bytes actually written
@@ -755,8 +755,8 @@ ZEXTERN int ZEXPORT gzflush OF((gzFile file, int flush));
*/ */
ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file, ZEXTERN z_off_t ZEXPORT gzseek OF((gzFile file,
z_off_t offset, int whence)); z_off_t offset, int whence));
/* /*
Sets the starting position for the next gzread or gzwrite on the Sets the starting position for the next gzread or gzwrite on the
given compressed file. The offset represents a number of bytes in the given compressed file. The offset represents a number of bytes in the
uncompressed data stream. The whence parameter is defined as in lseek(2); uncompressed data stream. The whence parameter is defined as in lseek(2);
@@ -891,4 +891,3 @@ ZEXTERN const uLongf * ZEXPORT get_crc_table OF((void));
#endif #endif
#endif /* _ZLIB_H */ #endif /* _ZLIB_H */
@@ -1,6 +1,6 @@
/* inflate_util.c -- data and routines common to blocks and codes /* inflate_util.c -- data and routines common to blocks and codes
* Copyright (C) 1995-2002 Mark Adler * Copyright (C) 1995-2002 Mark Adler
* For conditions of distribution and use, see copyright notice in zlib.h * For conditions of distribution and use, see copyright notice in zlib.h
*/ */
#include "zutil.h" #include "zutil.h"
@@ -208,7 +208,7 @@ extern const char *z_errmsg[10]; /* indexed by 2-zlib_error */
typedef uLong (ZEXPORT *check_func) OF((uLong check, const Bytef *buf, typedef uLong (ZEXPORT *check_func) OF((uLong check, const Bytef *buf,
uInt len)); uInt len));
voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size)); voidpf zcalloc OF((voidpf opaque, unsigned items, unsigned size));
void zcfree OF((voidpf opaque, voidpf ptr)); void zcfree OF((voidpf opaque, voidpf ptr));
@@ -218,4 +218,3 @@ void zcfree OF((voidpf opaque, voidpf ptr));
#define TRY_FREE(s, p) {if (p) ZFREE(s, p);} #define TRY_FREE(s, p) {if (p) ZFREE(s, p);}
#endif /* _Z_UTIL_H */ #endif /* _Z_UTIL_H */
@@ -20,5 +20,5 @@ DWORD WINAPI DllMain(HINSTANCE hInst, DWORD dwReason, LPVOID lpReserved)
UNREFERENCED_PARAMETER(dwReason); UNREFERENCED_PARAMETER(dwReason);
UNREFERENCED_PARAMETER(lpReserved); UNREFERENCED_PARAMETER(lpReserved);
return TRUE; return TRUE;
} }
@@ -1,5 +1,6 @@
#include "adtfile.h" #include "adtfile.h"
#include <algorithm>
char * GetPlainName(char * FileName) char * GetPlainName(char * FileName)
{ {
@@ -12,7 +13,8 @@ char * GetPlainName(char * FileName)
void fixnamen(char *name, size_t len) void fixnamen(char *name, size_t len)
{ {
for (size_t i=0; i<len-3; i++) { for (size_t i=0; i<len-3; i++)
{
if (i>0 && name[i]>='A' && name[i]<='Z' && isalpha(name[i-1])) if (i>0 && name[i]>='A' && name[i]<='Z' && isalpha(name[i-1]))
{ {
name[i] |= 0x20; name[i] |= 0x20;
@@ -22,6 +24,7 @@ void fixnamen(char *name, size_t len)
} }
} }
} }
void fixname2(char *name, size_t len) void fixname2(char *name, size_t len)
{ {
for (size_t i=0; i<len-3; i++) for (size_t i=0; i<len-3; i++)
@@ -38,7 +41,6 @@ ADTFile::ADTFile(char* filename): ADT(filename)
bool ADTFile::init(char *map_id) bool ADTFile::init(char *map_id)
{ {
if(ADT.isEof ()) if(ADT.isEof ())
return false; return false;
@@ -68,8 +70,7 @@ bool ADTFile::init(char *map_id)
return false; return false;
} }
while (!ADT.isEof())
while (!ADT.isEof ())
{ {
char fourcc[5]; char fourcc[5];
ADT.read(&fourcc,4); ADT.read(&fourcc,4);
@@ -77,18 +78,16 @@ bool ADTFile::init(char *map_id)
flipcc(fourcc); flipcc(fourcc);
fourcc[4] = 0; fourcc[4] = 0;
size_t nextpos = ADT.getPos () + size; size_t nextpos = ADT.getPos() + size;
if (!strcmp(fourcc,"MCIN"))//MCIN if (!strcmp(fourcc,"MCIN"))
{ {
} }
else if (!strcmp(fourcc,"MTEX")) else if (!strcmp(fourcc,"MTEX"))
{ {
} }
else if (!strcmp(fourcc,"MMDX")) else if (!strcmp(fourcc,"MMDX"))
{ {
if (size) if (size)
{ {
char *buf = new char[size]; char *buf = new char[size];
@@ -104,35 +103,39 @@ bool ADTFile::init(char *map_id)
fixname2(s,strlen(s)); fixname2(s,strlen(s));
p=p+strlen(p)+1; p=p+strlen(p)+1;
ModelInstansName[t++] = s; ModelInstansName[t++] = s;
path.erase(path.length()-2,2);
path.append("2"); // < 3.1.0 ADT MMDX section store filename.mdx filenames for corresponded .m2 file
char* szLocalFile[512]; std::string ext3 = path.size() >= 4 ? path.substr(path.size()-4,4) : "";
sprintf((char*)szLocalFile, ".\\buildings\\%s", s); std::transform( ext3.begin(), ext3.end(), ext3.begin(), ::tolower );
FILE * output = fopen((char*)szLocalFile,"rb"); if(ext3 == ".mdx")
{
// replace .mdx -> .m2
path.erase(path.length()-2,2);
path.append("2");
}
// >= 3.1.0 ADT MMDX section store filename.m2 filenames for corresponded .m2 file
// nothing do
char szLocalFile[MAX_PATH];
sprintf(szLocalFile, ".\\buildings\\%s", s);
FILE * output = fopen(szLocalFile,"rb");
if(!output) if(!output)
{ {
Model * m2 = new Model(path); Model * m2 = new Model(path);
if(m2->open()) if(m2->open())
{ m2->ConvertToVMAPModel(szLocalFile);
m2->ConvertToVMAPModel((char*)szLocalFile);
}
delete m2; delete m2;
} }
else else
fclose(output); fclose(output);
} }
delete[] buf; delete[] buf;
} }
} }
else if (!strcmp(fourcc,"MWMO")) else if (!strcmp(fourcc,"MWMO"))
{ {
if (size) if (size)
{ {
char *buf = new char[size]; char *buf = new char[size];
ADT.read(buf, size); ADT.read(buf, size);
char *p=buf; char *p=buf;
@@ -148,23 +151,21 @@ bool ADTFile::init(char *map_id)
WmoInstansName[q++] = s; WmoInstansName[q++] = s;
} }
delete[] buf; delete[] buf;
} }
} }
//====================== //======================
else if (!strcmp(fourcc,"MDDF")) else if (!strcmp(fourcc,"MDDF"))
{ {
if (size) if (size)
{ {
nMDX = (int)size / 36; nMDX = (int)size / 36;
for (int i=0; i<nMDX; i++) for (int i=0; i<nMDX; ++i)
{ {
int id; int id;
ADT.read(&id, 4); ADT.read(&id, 4);
ModelInstance inst(ADT,ModelInstansName[id].c_str(),map_id, dirfile);//!!!!!!!!!!! ModelInstance inst(ADT,ModelInstansName[id].c_str(),map_id, dirfile);//!!!!!!!!!!!
} }
delete[] ModelInstansName; delete[] ModelInstansName;
} }
} }
else if (!strcmp(fourcc,"MODF")) else if (!strcmp(fourcc,"MODF"))
@@ -172,7 +173,7 @@ bool ADTFile::init(char *map_id)
if (size) if (size)
{ {
nWMO = (int)size / 64; nWMO = (int)size / 64;
for (int i=0; i<nWMO; i++) for (int i=0; i<nWMO; ++i)
{ {
int id; int id;
ADT.read(&id, 4); ADT.read(&id, 4);
@@ -187,14 +188,14 @@ bool ADTFile::init(char *map_id)
{ {
if (size) if (size)
{ {
nMDX = (int)size / 36; nMDX = (int)size / 36;
for (int i=0; i<nMDX; i++) for (int i=0; i<nMDX; ++i)
{ {
int id; int id;
ADT.read(&id, 4); ADT.read(&id, 4);
ModelInstance inst(ADT,ModelInstansName[id].c_str(),AdtMapNumber.c_str(), dirfile); ModelInstance inst(ADT,ModelInstansName[id].c_str(),AdtMapNumber.c_str(), dirfile);
} }
delete[] ModelInstansName; delete[] ModelInstansName;
} }
} }
else if (!strcmp(fourcc,"MODF")) else if (!strcmp(fourcc,"MODF"))
@@ -202,7 +203,7 @@ bool ADTFile::init(char *map_id)
if (size) if (size)
{ {
nWMO = (int)size / 64; nWMO = (int)size / 64;
for (int i=0; i<nWMO; i++) for (int i=0; i<nWMO; ++i)
{ {
int id; int id;
ADT.read(&id, 4); ADT.read(&id, 4);
@@ -223,6 +224,3 @@ ADTFile::~ADTFile()
{ {
ADT.close(); ADT.close();
} }
+29 -27
View File
@@ -17,43 +17,48 @@ typedef unsigned int uint32;
class Liquid; class Liquid;
typedef struct { typedef struct
float x; {
float y; float x;
float z; float y;
float z;
}svec; }svec;
typedef struct { struct vec
double x; {
double y; double x;
double z; double y;
}vec; double z;
};
typedef struct{ struct triangle
{
vec v[3]; vec v[3];
};
}triangle; typedef struct
{
typedef struct{ float v9[16*8+1][16*8+1];
float v9[16*8+1][16*8+1]; float v8[16*8][16*8];
float v8[16*8][16*8];
}Cell; }Cell;
typedef struct{ typedef struct
double v9[9][9]; {
double v8[8][8]; double v9[9][9];
uint16 area_id; double v8[8][8];
//Liquid *lq; uint16 area_id;
float waterlevel[9][9]; //Liquid *lq;
uint8 flag; float waterlevel[9][9];
uint8 flag;
}chunk; }chunk;
typedef struct typedef struct
{ {
chunk ch[16][16]; chunk ch[16][16];
}mcell; }mcell;
struct MapChunkHeader { struct MapChunkHeader
{
uint32 flags; uint32 flags;
uint32 ix; uint32 ix;
uint32 iy; uint32 iy;
@@ -119,7 +124,4 @@ private:
void fixnamen(char *name, size_t len); void fixnamen(char *name, size_t len);
//void fixMapNamen(char *name, size_t len); //void fixMapNamen(char *name, size_t len);
#endif #endif
@@ -22,8 +22,8 @@ bool DBCFile::open()
f.read(header,4); // File Header f.read(header,4); // File Header
if (header[0]!='W' || header[1]!='D' || header[2]!='B' || header[3] != 'C') { if (header[0]!='W' || header[1]!='D' || header[2]!='B' || header[3] != 'C')
{
f.close(); f.close();
data = NULL; data = NULL;
printf("Critical Error: An error occured while trying to read the DBCFile %s.", filename.c_str()); printf("Critical Error: An error occured while trying to read the DBCFile %s.", filename.c_str());
@@ -67,10 +67,9 @@ DBCFile::Iterator DBCFile::begin()
assert(data); assert(data);
return Iterator(*this, data); return Iterator(*this, data);
} }
DBCFile::Iterator DBCFile::end() DBCFile::Iterator DBCFile::end()
{ {
assert(data); assert(data);
return Iterator(*this, stringTable); return Iterator(*this, stringTable);
} }
@@ -137,4 +137,3 @@ private:
}; };
#endif #endif
+23 -28
View File
@@ -12,7 +12,7 @@ bool Model::open()
ok = !f.isEof(); ok = !f.isEof();
if (!ok) if (!ok)
{ {
f.close(); f.close();
printf("Error loading model %s\n", filename.c_str()); printf("Error loading model %s\n", filename.c_str());
@@ -20,20 +20,20 @@ bool Model::open()
} }
memcpy(&header, f.getBuffer(), sizeof(ModelHeader)); memcpy(&header, f.getBuffer(), sizeof(ModelHeader));
if(header.nBoundingTriangles > 0) if(header.nBoundingTriangles > 0)
{ {
f.seek(0); f.seek(0);
f.seekRelative(header.ofsBoundingVertices); f.seekRelative(header.ofsBoundingVertices);
vertices = new Vec3D[header.nBoundingVertices]; vertices = new Vec3D[header.nBoundingVertices];
f.read(vertices,header.nBoundingVertices*12); f.read(vertices,header.nBoundingVertices*12);
for (uint32 i=0; i<header.nBoundingVertices; i++) for (uint32 i=0; i<header.nBoundingVertices; i++)
{ {
vertices[i] = fixCoordSystem(vertices[i]); vertices[i] = fixCoordSystem(vertices[i]);
} }
f.seek(0); f.seek(0);
f.seekRelative(header.ofsBoundingTriangles); f.seekRelative(header.ofsBoundingTriangles);
indices = new uint16[header.nBoundingTriangles]; indices = new uint16[header.nBoundingTriangles];
f.read(indices,header.nBoundingTriangles*2); f.read(indices,header.nBoundingTriangles*2);
f.close(); f.close();
} }
else else
@@ -45,10 +45,8 @@ bool Model::open()
return true; return true;
} }
bool Model::ConvertToVMAPModel(char * outfilename) bool Model::ConvertToVMAPModel(char * outfilename)
{ {
int N[] = {0x00000000}; int N[] = {0x00000000};
FILE * output=fopen(outfilename,"wb"); FILE * output=fopen(outfilename,"wb");
if(!output) if(!output)
@@ -76,7 +74,7 @@ bool Model::ConvertToVMAPModel(char * outfilename)
wsize = sizeof(uint32) + sizeof(unsigned short) * nIndexes; wsize = sizeof(uint32) + sizeof(unsigned short) * nIndexes;
fwrite(&wsize, sizeof(int), 1, output); fwrite(&wsize, sizeof(int), 1, output);
fwrite(&nIndexes, sizeof(uint32), 1, output); fwrite(&nIndexes, sizeof(uint32), 1, output);
if(nIndexes >0) if(nIndexes >0)
{ {
fwrite(indices, sizeof(unsigned short), nIndexes, output); fwrite(indices, sizeof(unsigned short), nIndexes, output);
} }
@@ -84,7 +82,7 @@ bool Model::ConvertToVMAPModel(char * outfilename)
wsize = sizeof(int) + sizeof(float) * 3 * nVertices; wsize = sizeof(int) + sizeof(float) * 3 * nVertices;
fwrite(&wsize, sizeof(int), 1, output); fwrite(&wsize, sizeof(int), 1, output);
fwrite(&nVertices, sizeof(int), 1, output); fwrite(&nVertices, sizeof(int), 1, output);
if(nVertices >0) if(nVertices >0)
{ {
for(uint32 vpos=0; vpos <nVertices; ++vpos) for(uint32 vpos=0; vpos <nVertices; ++vpos)
{ {
@@ -133,27 +131,25 @@ ModelInstance::ModelInstance(MPQFile &f,const char* ModelInstName,const char*Map
sprintf(tempname, ".\\buildings\\%s", ModelInstName); sprintf(tempname, ".\\buildings\\%s", ModelInstName);
FILE *input; FILE *input;
input = fopen(tempname, "r+b"); input = fopen(tempname, "r+b");
if(!input)
{
return;
}
fseek(input, 8, SEEK_SET); // get the correct no of vertices
int nVertices;
fread(&nVertices, sizeof (int), 1, input);
fclose(input);
if(nVertices == 0)
{
return;
}
if(pDirfile) if(!input)
return;
fseek(input, 8, SEEK_SET); // get the correct no of vertices
int nVertices;
fread(&nVertices, sizeof (int), 1, input);
fclose(input);
if(nVertices == 0)
return;
if(pDirfile)
{ {
int realx1 = (int) ((float) pos.x / 533.333333f); int realx1 = (int) ((float) pos.x / 533.333333f);
int realy1 = (int) ((float) pos.z / 533.333333f); int realy1 = (int) ((float) pos.z / 533.333333f);
int realx2 = (int) ((float) pos.x / 533.333333f); int realx2 = (int) ((float) pos.x / 533.333333f);
int realy2 = (int) ((float) pos.z / 533.333333f); int realy2 = (int) ((float) pos.z / 533.333333f);
fprintf(pDirfile,"%s/%s %f,%f,%f_%f,%f,%f %f %d %d %d,%d %d\n", fprintf(pDirfile,"%s/%s %f,%f,%f_%f,%f,%f %f %d %d %d,%d %d\n",
MapName, MapName,
ModelInstName, ModelInstName,
@@ -163,7 +159,6 @@ ModelInstance::ModelInstance(MPQFile &f,const char* ModelInstName,const char*Map
nVertices, nVertices,
realx1, realy1, realx1, realy1,
realx2, realy2 realx2, realy2
); );
} }
} }
+20 -30
View File
@@ -11,51 +11,41 @@ class WMOInstance;
Vec3D fixCoordSystem(Vec3D v); Vec3D fixCoordSystem(Vec3D v);
class Model class Model
{ {
public: public:
ModelHeader header;
uint32 offsBB_vertices, offsBB_indices;
Vec3D *BB_vertices, *vertices;
uint16 *BB_indices, *indices;
size_t nIndices;
ModelHeader header; bool open();
bool ConvertToVMAPModel(char * outfilename);
public:
uint32 offsBB_vertices, offsBB_indices; bool ok;
Vec3D *BB_vertices, *vertices;
uint16 *BB_indices, *indices;
size_t nIndices;
bool open();
bool ConvertToVMAPModel(char * outfilename);
public: Model(std::string &filename);
~Model();
bool ok;
Model(std::string &filename);
~Model();
private: private:
std::string filename; std::string filename;
char outfilename; char outfilename;
}; };
class ModelInstance class ModelInstance
{ {
public: public:
Model *model; Model *model;
int id; int id;
Vec3D pos, rot; Vec3D pos, rot;
unsigned int d1, scale; unsigned int d1, scale;
float w,sc; float w,sc;
ModelInstance() {} ModelInstance() {}
ModelInstance(MPQFile &f,const char* ModelInstName,const char*MapName, FILE *pDirfile); ModelInstance(MPQFile &f,const char* ModelInstName,const char*MapName, FILE *pDirfile);
}; };
#endif #endif
@@ -10,74 +10,72 @@ typedef int int32;
#pragma pack(push,1) #pragma pack(push,1)
struct ModelHeader { struct ModelHeader
char id[4]; {
uint8 version[4]; char id[4];
uint32 nameLength; uint8 version[4];
uint32 nameOfs; uint32 nameLength;
uint32 type; uint32 nameOfs;
uint32 nGlobalSequences; uint32 type;
uint32 ofsGlobalSequences; uint32 nGlobalSequences;
uint32 nAnimations; uint32 ofsGlobalSequences;
uint32 ofsAnimations; uint32 nAnimations;
uint32 ofsAnimations;
uint32 nAnimationLookup; uint32 nAnimationLookup;
uint32 ofsAnimationLookup; uint32 ofsAnimationLookup;
uint32 nBones; uint32 nBones;
uint32 ofsBones; uint32 ofsBones;
uint32 nKeyBoneLookup; uint32 nKeyBoneLookup;
uint32 ofsKeyBoneLookup; uint32 ofsKeyBoneLookup;
uint32 nVertices; uint32 nVertices;
uint32 ofsVertices; uint32 ofsVertices;
uint32 nViews; uint32 nViews;
uint32 nColors; uint32 nColors;
uint32 ofsColors; uint32 ofsColors;
uint32 nTextures; uint32 nTextures;
uint32 ofsTextures; uint32 ofsTextures;
uint32 nTransparency; uint32 nTransparency;
uint32 ofsTransparency; uint32 ofsTransparency;
uint32 nTextureanimations; uint32 nTextureanimations;
uint32 ofsTextureanimations; uint32 ofsTextureanimations;
uint32 nTexReplace; uint32 nTexReplace;
uint32 ofsTexReplace; uint32 ofsTexReplace;
uint32 nRenderFlags; uint32 nRenderFlags;
uint32 ofsRenderFlags; uint32 ofsRenderFlags;
uint32 nBoneLookupTable; uint32 nBoneLookupTable;
uint32 ofsBoneLookupTable; uint32 ofsBoneLookupTable;
uint32 nTexLookup; uint32 nTexLookup;
uint32 ofsTexLookup; uint32 ofsTexLookup;
uint32 nTexUnits; uint32 nTexUnits;
uint32 ofsTexUnits; uint32 ofsTexUnits;
uint32 nTransLookup; uint32 nTransLookup;
uint32 ofsTransLookup; uint32 ofsTransLookup;
uint32 nTexAnimLookup; uint32 nTexAnimLookup;
uint32 ofsTexAnimLookup; uint32 ofsTexAnimLookup;
float floats[14]; float floats[14];
uint32 nBoundingTriangles; uint32 nBoundingTriangles;
uint32 ofsBoundingTriangles; uint32 ofsBoundingTriangles;
uint32 nBoundingVertices; uint32 nBoundingVertices;
uint32 ofsBoundingVertices; uint32 ofsBoundingVertices;
uint32 nBoundingNormals; uint32 nBoundingNormals;
uint32 ofsBoundingNormals; uint32 ofsBoundingNormals;
uint32 nAttachments; uint32 nAttachments;
uint32 ofsAttachments; uint32 ofsAttachments;
uint32 nAttachLookup; uint32 nAttachLookup;
uint32 ofsAttachLookup; uint32 ofsAttachLookup;
uint32 nAttachments_2; uint32 nAttachments_2;
uint32 ofsAttachments_2; uint32 ofsAttachments_2;
uint32 nLights; uint32 nLights;
uint32 ofsLights; uint32 ofsLights;
uint32 nCameras; uint32 nCameras;
uint32 ofsCameras; uint32 ofsCameras;
uint32 nCameraLookup; uint32 nCameraLookup;
uint32 ofsCameraLookup; uint32 ofsCameraLookup;
uint32 nRibbonEmitters; uint32 nRibbonEmitters;
uint32 ofsRibbonEmitters; uint32 ofsRibbonEmitters;
uint32 nParticleEmitters; uint32 nParticleEmitters;
uint32 ofsParticleEmitters; uint32 ofsParticleEmitters;
}; };
#pragma pack(pop) #pragma pack(pop)
#endif #endif
+42 -36
View File
@@ -3,24 +3,16 @@
#include "Stormlib.h" #include "Stormlib.h"
#define __STORMLIB_SELF__ #define __STORMLIB_SELF__
typedef std::vector<MPQArchive*> ArchiveSet; MPQArchiveSet gOpenArchives;
ArchiveSet gOpenArchives;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
MPQArchive::MPQArchive(const char* filename) MPQArchive::MPQArchive(const char* filename)
{ {
BOOL succ = SFileOpenArchive(filename, 0, 0,&hMPQ); BOOL succ = SFileOpenArchive(filename, 0, 0,&hMPQ);
if (succ) if (succ)
{
MPQArchive*ar = (MPQArchive*)(hMPQ);
printf("Opening %s\n", filename); printf("Opening %s\n", filename);
gOpenArchives.push_back(ar);
succ = true;
}
else else
{
printf("Error!!!Not open archive %s\n", filename); printf("Error!!!Not open archive %s\n", filename);
}
} }
void MPQArchive::close() void MPQArchive::close()
@@ -28,41 +20,57 @@ void MPQArchive::close()
SFileCloseArchive(hMPQ); SFileCloseArchive(hMPQ);
} }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx bool MPQArchiveSet::Open( std::vector<std::string> const& archiveNames )
{
for (size_t i=0; i < archiveNames.size(); ++i)
{
MPQArchive mpqarch(archiveNames[i].c_str());
if(mpqarch.isOpen())
archives.push_back(mpqarch);
}
return !archives.empty();
}
MPQArchiveSet::~MPQArchiveSet()
{
// close archives
for (ArchiveSet::iterator ar_itr = archives.begin(); ar_itr != archives.end(); ++ar_itr)
ar_itr->close();
}
MPQFile::MPQFile(const char* filename): MPQFile::MPQFile(const char* filename):
eof(false), eof(false),
buffer(0), buffer(0),
pointer(0), pointer(0),
size(0) size(0)
{ {
for(ArchiveSet::iterator i=gOpenArchives.begin(); i!=gOpenArchives.end();++i) for(ArchiveSet::const_iterator i=gOpenArchives.archives.begin(); i!=gOpenArchives.archives.end();++i)
{ {
HANDLE hFile = "";
hMPQ = i->hMPQ;
BOOL succ = SFileOpenFileEx(hMPQ,filename,0, &hFile);
if (succ)
{
DWORD s = SFileGetFileSize(hFile, 0);
if (!s)
{
eof = true;
buffer = 0;
return;
}
size = (size_t)s;
buffer = new char[s];
SFileReadFile(hFile, buffer, s, 0, 0);
SFileCloseFile(hFile);
HANDLE hFile = ""; eof = false;
MPQArchive*(hMPQ) = *i;
BOOL succ = SFileOpenFileEx(hMPQ,filename,0, &hFile);
if (succ)
{
DWORD s = SFileGetFileSize(hFile, 0);
if (!s)
{
eof = true;
buffer = 0;
return; return;
} }
size = (size_t)s;
buffer = new char[s];
SFileReadFile(hFile, buffer, s, 0, 0);
SFileCloseFile(hFile);
eof = false;
return;
}
} }
eof = true; eof = true;
buffer = 0; buffer = 0;
} }
MPQFile::~MPQFile() MPQFile::~MPQFile()
@@ -73,7 +81,7 @@ MPQFile::~MPQFile()
size_t MPQFile::read(void* dest, size_t bytes) size_t MPQFile::read(void* dest, size_t bytes)
{ {
if (eof) if (eof)
return 0; return 0;
size_t rpos = pointer + bytes; size_t rpos = pointer + bytes;
if (rpos > size) if (rpos > size)
@@ -109,7 +117,7 @@ void MPQFile::seekRelative(int offset)
void MPQFile::close() void MPQFile::close()
{ {
if (buffer) if (buffer)
delete[] buffer; delete[] buffer;
buffer = 0; buffer = 0;
eof = true; eof = true;
} }
@@ -133,5 +141,3 @@ char* MPQFile::getPointer()
{ {
return buffer + pointer; return buffer + pointer;
} }
+20 -10
View File
@@ -15,16 +15,30 @@ using namespace std;
typedef unsigned int uint32; typedef unsigned int uint32;
class MPQArchive class MPQArchive
{ {
public:
public: HANDLE hMPQ;
HANDLE hMPQ; MPQArchive(const char* filename);
MPQArchive(const char* filename); void close();
void close(); bool isOpen() const { return hMPQ != 0; }
}; };
typedef std::vector<MPQArchive> ArchiveSet;
class MPQArchiveSet
{
public:
MPQArchiveSet() {}
~MPQArchiveSet();
bool Open(std::vector<std::string> const& archiveNames);
ArchiveSet archives;
};
extern MPQArchiveSet gOpenArchives;
class MPQFile class MPQFile
{ {
HANDLE hFile; HANDLE hFile;
@@ -63,8 +77,4 @@ inline void flipcc(char *fcc)
fcc[2]=t; fcc[2]=t;
} }
#endif #endif
+4 -11
View File
@@ -4,9 +4,8 @@
#include <iostream> #include <iostream>
#include <cmath> #include <cmath>
class Vec3D
{
class Vec3D {
public: public:
float x,y,z; float x,y,z;
@@ -112,11 +111,11 @@ public:
{ {
return (float*)this; return (float*)this;
} }
}; };
class Vec2D { class Vec2D
{
public: public:
float x,y; float x,y;
@@ -213,10 +212,8 @@ public:
{ {
return (float*)this; return (float*)this;
} }
}; };
inline void rotate(float x0, float y0, float *x, float *y, float angle) inline void rotate(float x0, float y0, float *x, float *y, float angle)
{ {
float xa = *x - x0, ya = *y - y0; float xa = *x - x0, ya = *y - y0;
@@ -224,8 +221,4 @@ inline void rotate(float x0, float y0, float *x, float *y, float angle)
*y = xa*sinf(angle) + ya*cosf(angle) + y0; *y = xa*sinf(angle) + ya*cosf(angle) + y0;
} }
#endif #endif
@@ -44,7 +44,8 @@
typedef unsigned char uint8; typedef unsigned char uint8;
typedef unsigned short uint16; typedef unsigned short uint16;
typedef unsigned int uint32; typedef unsigned int uint32;
typedef struct{ typedef struct
{
char name[64]; char name[64];
unsigned int id; unsigned int id;
}map_id; }map_id;
@@ -86,9 +87,10 @@ static const char * GetPlainName(const char * szFileName)
szFileName = szTemp + 1; szFileName = szTemp + 1;
return szFileName; return szFileName;
} }
//------------------------------------------------------------------------------
static void ShowProcessedFile(const char * szFileName) static void ShowProcessedFile(const char * szFileName)
{ {
/* not truncate file names in output
char szLine[80]; char szLine[80];
size_t nLength = strlen(szFileName); size_t nLength = strlen(szFileName);
@@ -99,16 +101,14 @@ static void ShowProcessedFile(const char * szFileName)
nLength = sizeof(szLine)-1; nLength = sizeof(szLine)-1;
memcpy(szLine, szFileName, nLength); memcpy(szLine, szFileName, nLength);
printf("\r%s\n", szLine); printf("\r%s\n", szLine);
*/
printf("\r%s\n", szFileName);
} }
int ExtractWmo()
//----------------------------------------------------------------------------------------------------------------------------------------------------------------------
int ExtractWmo(const std::vector<std::string>& pArchiveNames)
{ {
char* szListFile = ""; char* szListFile = "";
char szLocalFile[MAX_PATH] = ""; char szLocalFile[MAX_PATH] = "";
HANDLE hMpq = "";
BOOL bResult = FALSE; BOOL bResult = FALSE;
//const char* ParsArchiveNames[] = {"patch-2.MPQ", "patch.MPQ", "common.MPQ", "expansion.MPQ"}; //const char* ParsArchiveNames[] = {"patch-2.MPQ", "patch.MPQ", "common.MPQ", "expansion.MPQ"};
@@ -116,21 +116,14 @@ int ExtractWmo(const std::vector<std::string>& pArchiveNames)
int nError = ERROR_SUCCESS; int nError = ERROR_SUCCESS;
if(szListFile == NULL || *szListFile == 0) if(szListFile == NULL || *szListFile == 0)
szListFile = NULL; szListFile = NULL;
//char tmp[1024];
//for (size_t i=0; i<4; i++) for (ArchiveSet::const_iterator ar_itr = gOpenArchives.archives.begin(); ar_itr != gOpenArchives.archives.end(); ++ar_itr)
for (size_t i=0; i<pArchiveNames.size(); i++)
{ {
//sprintf(tmp,"%s\\%s", input_path, ParsArchiveNames[i]);
//if(!SFileOpenArchive(tmp, 0, 0, &hMpq))
if(!SFileOpenArchive(pArchiveNames[i].c_str(), 0, 0, &hMpq))
printf("NOT open!!! %s\n",pArchiveNames[i].c_str());
// Copy files from archive // Copy files from archive
if(nError == ERROR_SUCCESS) if(nError == ERROR_SUCCESS)
{ {
SFILE_FIND_DATA wf; SFILE_FIND_DATA wf;
HANDLE hFind = SFileFindFirstFile(hMpq,"*.wmo*", &wf, szListFile); HANDLE hFind = SFileFindFirstFile(ar_itr->hMPQ,"*.wmo*", &wf, szListFile);
bResult = TRUE; bResult = TRUE;
while(hFind != NULL && bResult == TRUE) while(hFind != NULL && bResult == TRUE)
@@ -149,7 +142,7 @@ int ExtractWmo(const std::vector<std::string>& pArchiveNames)
{ {
char cpy[4]; char cpy[4];
strncpy((char*)cpy,rchr,4); strncpy((char*)cpy,rchr,4);
for (int i=0;i<4;i++) for (int i=0;i<4; ++i)
{ {
int m = cpy[i]; int m = cpy[i];
if(isdigit(m)) if(isdigit(m))
@@ -167,17 +160,17 @@ int ExtractWmo(const std::vector<std::string>& pArchiveNames)
bResult = SFileFindNextFile(hFind, &wf); bResult = SFileFindNextFile(hFind, &wf);
continue; continue;
} }
FILE *output=fopen(szLocalFile,"wb"); FILE *output=fopen(szLocalFile,"wb");
froot->ConvertToVMAPRootWmo(output); froot->ConvertToVMAPRootWmo(output);
int Wmo_nVertices = 0; int Wmo_nVertices = 0;
if(froot->nGroups !=0) if(froot->nGroups !=0)
{ {
for (int i=0; i<froot->nGroups; i++) for (int i=0; i<froot->nGroups; ++i)
{ {
char temp[512]; char temp[MAX_PATH];
strcpy(temp, wf.cFileName); strcpy(temp, wf.cFileName);
temp[strlen(wf.cFileName)-4] = 0; temp[strlen(wf.cFileName)-4] = 0;
char groupFileName[512]; char groupFileName[MAX_PATH];
sprintf(groupFileName,"%s_%03d.wmo",temp, i); sprintf(groupFileName,"%s_%03d.wmo",temp, i);
printf("%s\n",groupFileName); printf("%s\n",groupFileName);
//printf("GroupWmo!\n"); //printf("GroupWmo!\n");
@@ -196,7 +189,9 @@ int ExtractWmo(const std::vector<std::string>& pArchiveNames)
fwrite(&Wmo_nVertices,sizeof(int),1,output); fwrite(&Wmo_nVertices,sizeof(int),1,output);
fclose(output); fclose(output);
} }
} else { }
else
{
fclose(n); fclose(n);
} }
wf.dwFileFlags &= ~MPQ_FILE_HAS_EXTRA; wf.dwFileFlags &= ~MPQ_FILE_HAS_EXTRA;
@@ -210,39 +205,34 @@ int ExtractWmo(const std::vector<std::string>& pArchiveNames)
// Close the search handle // Close the search handle
if(hFind != NULL) if(hFind != NULL)
SFileFindClose(hFind); SFileFindClose(hFind);
} }
} }
// Close both archives
if(hMpq != NULL) if(nError == ERROR_SUCCESS)
//SFileCloseArchive(hMpq); printf("\nExtract wmo complete (No errors)\n");
if(nError == ERROR_SUCCESS)
printf("\nExtract wmo complete (No errors)\n");
return nError; return nError;
} }
void ExtractMapsFromMpq() void ExtractMapsFromMpq()
{ {
} }
//-----------------------------------------------------------------------------
void ParsMapFiles() void ParsMapFiles()
{ {
char fn[512]; char fn[512];
char id_filename[64]; char id_filename[64];
char id[10]; char id[10];
for (unsigned int i=0; i<map_count; i++) for (unsigned int i=0; i<map_count; ++i)
{ {
sprintf(id,"%03u",map_ids[i].id); sprintf(id,"%03u",map_ids[i].id);
sprintf(fn,"World\\Maps\\%s\\%s.wdt", map_ids[i].name, map_ids[i].name); sprintf(fn,"World\\Maps\\%s\\%s.wdt", map_ids[i].name, map_ids[i].name);
WDTFile WDT(fn,map_ids[i].name); WDTFile WDT(fn,map_ids[i].name);
if(WDT.init(id)) if(WDT.init(id))
{ {
for (int x=0; x<64; x++) for (int x=0; x<64; ++x)
{ {
for (int y=0; y<64; y++) for (int y=0; y<64; ++y)
{ {
if (ADTFile*ADT = WDT.GetMap(x,y)) if (ADTFile*ADT = WDT.GetMap(x,y))
{ {
@@ -250,7 +240,6 @@ void ParsMapFiles()
ADT->init(id_filename); ADT->init(id_filename);
delete ADT; delete ADT;
} }
} }
} }
} }
@@ -259,31 +248,28 @@ void ParsMapFiles()
#if 0 #if 0
void ParsMapFiles() void ParsMapFiles()
{ {
char fn[512]; char fn[512];
for (unsigned int i=0; i<map_count; i++) for (unsigned int i=0; i<map_count; ++i)
{ {
sprintf(fn,"World\\Maps\\%s\\%s.wdt", map_ids[i].name, map_ids[i].name); sprintf(fn,"World\\Maps\\%s\\%s.wdt", map_ids[i].name, map_ids[i].name);
WDTFile WDT(fn,map_ids[i].name); WDTFile WDT(fn,map_ids[i].name);
if(WDT.init()) if(WDT.init())
{ {
for (int x=0; x<64; x++) for (int x=0; x<64; ++x)
{ {
for (int y=0; y<64; y++) for (int y=0; y<64; ++y)
{ {
if (ADTFile*ADT = WDT.GetMap(x,y)) if (ADTFile*ADT = WDT.GetMap(x,y))
{ {
ADT->init(); ADT->init();
delete ADT; delete ADT;
} }
} }
} }
} }
} }
} }
#endif #endif
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
void getGamePath() void getGamePath()
{ {
@@ -307,8 +293,6 @@ void getGamePath()
#endif #endif
} }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
bool scan_patches(char* scanmatch, std::vector<std::string>& pArchiveNames) bool scan_patches(char* scanmatch, std::vector<std::string>& pArchiveNames)
{ {
int i; int i;
@@ -338,7 +322,7 @@ bool scan_patches(char* scanmatch, std::vector<std::string>& pArchiveNames)
} }
matches.reverse(); matches.reverse();
for (std::list<std::string>::iterator i = matches.begin(); i != matches.end(); i++) for (std::list<std::string>::iterator i = matches.begin(); i != matches.end(); ++i)
{ {
pArchiveNames.push_back(i->c_str()); pArchiveNames.push_back(i->c_str());
} }
@@ -348,11 +332,8 @@ bool scan_patches(char* scanmatch, std::vector<std::string>& pArchiveNames)
return(true); return(true);
} }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx bool fillArchiveNameVector(std::vector<std::string>& pArchiveNames)
{
bool fillArchiveNameVector(std::vector<std::string>& pArchiveNames) {
//srand((unsigned int)time(0));
if(!hasInputPathParam) if(!hasInputPathParam)
getGamePath(); getGamePath();
@@ -408,11 +389,12 @@ bool fillArchiveNameVector(std::vector<std::string>& pArchiveNames) {
// now, scan for the patch levels in the core dir // now, scan for the patch levels in the core dir
printf("Loading patch levels from data directory.\n"); printf("Loading patch levels from data directory.\n");
sprintf(path, "%spatch", input_path); sprintf(path, "%spatch", input_path);
if (!scan_patches(path, pArchiveNames)) return(false); if (!scan_patches(path, pArchiveNames))
return(false);
// now, scan for the patch levels in locale dirs // now, scan for the patch levels in locale dirs
printf("Loading patch levels from locale directories.\n"); printf("Loading patch levels from locale directories.\n");
for (std::vector<std::string>::iterator i = locales.begin(); i != locales.end(); i++) for (std::vector<std::string>::iterator i = locales.begin(); i != locales.end(); ++i)
{ {
printf("Locale: %s\n", i->c_str()); printf("Locale: %s\n", i->c_str());
sprintf(path, "%s%s\\patch-%s", input_path, i->c_str(), i->c_str()); sprintf(path, "%s%s\\patch-%s", input_path, i->c_str(), i->c_str());
@@ -433,7 +415,7 @@ bool fillArchiveNameVector(std::vector<std::string>& pArchiveNames) {
// open locale expansion and common files // open locale expansion and common files
printf("Opening data files from locale directories.\n"); printf("Opening data files from locale directories.\n");
for (std::vector<std::string>::iterator i = locales.begin(); i != locales.end(); i++) for (std::vector<std::string>::iterator i = locales.begin(); i != locales.end(); ++i)
{ {
printf("Locale: %s\n", i->c_str()); printf("Locale: %s\n", i->c_str());
sprintf(path, "%s%s\\lichking-locale-%s.mpq", input_path, i->c_str(), i->c_str()); sprintf(path, "%s%s\\lichking-locale-%s.mpq", input_path, i->c_str(), i->c_str());
@@ -446,8 +428,6 @@ bool fillArchiveNameVector(std::vector<std::string>& pArchiveNames) {
} }
return true; return true;
} }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// return false it normal processing can not proceed
bool processArgv(int argc, char ** argv, char*versionString) bool processArgv(int argc, char ** argv, char*versionString)
{ {
@@ -455,29 +435,43 @@ bool processArgv(int argc, char ** argv, char*versionString)
hasInputPathParam = false; hasInputPathParam = false;
bool preciseVectorData = false; bool preciseVectorData = false;
for(int i=1; i< argc; ++i) { for(int i=1; i< argc; ++i)
if(strcmp("-s",argv[i]) == 0) { {
if(strcmp("-s",argv[i]) == 0)
{
preciseVectorData = false; preciseVectorData = false;
} else if(strcmp("-d",argv[i]) == 0) { }
if((i+1)<argc) { else if(strcmp("-d",argv[i]) == 0)
{
if((i+1)<argc)
{
hasInputPathParam = true; hasInputPathParam = true;
strcpy(input_path, argv[i+1]); strcpy(input_path, argv[i+1]);
if (input_path[strlen(input_path) - 1] != '\\' || input_path[strlen(input_path) - 1] != '/') if (input_path[strlen(input_path) - 1] != '\\' || input_path[strlen(input_path) - 1] != '/')
strcat(input_path, "\\"); strcat(input_path, "\\");
++i; ++i;
} else { }
else
{
result = false; result = false;
} }
} else if(strcmp("-?",argv[1]) == 0) { }
else if(strcmp("-?",argv[1]) == 0)
{
result = false; result = false;
} else if(strcmp("-l",argv[i]) == 0) { }
else if(strcmp("-l",argv[i]) == 0)
{
preciseVectorData = true; preciseVectorData = true;
} else { }
else
{
result = false; result = false;
break; break;
} }
} }
if(!result) { if(!result)
{
printf("Extract %s.\n",versionString); printf("Extract %s.\n",versionString);
printf("%s [-?][-s][-l][-d <path>]\n", argv[0]); printf("%s [-?][-s][-l][-d <path>]\n", argv[0]);
printf(" -s : (default) small size (data size optimization), ~500MB less vmap data.\n"); printf(" -s : (default) small size (data size optimization), ~500MB less vmap data.\n");
@@ -490,7 +484,7 @@ bool processArgv(int argc, char ** argv, char*versionString)
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// Main // Main
// //
// The program must be run with two command line arguments // The program must be run with two command line arguments
// //
// Arg1 - The source MPQ name (for testing reading and file find) // Arg1 - The source MPQ name (for testing reading and file find)
@@ -529,28 +523,33 @@ int main(int argc, char ** argv)
if(nError == ERROR_ALREADY_EXISTS) if(nError == ERROR_ALREADY_EXISTS)
nError = ERROR_SUCCESS; nError = ERROR_SUCCESS;
} }
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
// patch goes first -> fake priority handling
std::vector<MPQArchive*> archives;
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // prepare archive name list
std::vector<std::string> archiveNames; std::vector<std::string> archiveNames;
fillArchiveNameVector(archiveNames); fillArchiveNameVector(archiveNames);
for (size_t i=0; i<archiveNames.size(); i++) { if(!gOpenArchives.Open(archiveNames))
archives.push_back(new MPQArchive(archiveNames[i].c_str())); {
printf("FATAL ERROR: None MPQ archive found by path '%s'. Use -d option with proper path.\n",input_path);
return 1;
} }
ExtractWmo(archiveNames);
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // extract data
ExtractWmo();
//xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
//map.dbc //map.dbc
if(nError == ERROR_SUCCESS) if(nError == ERROR_SUCCESS)
{ {
DBCFile * dbc = new DBCFile("DBFilesClient\\Map.dbc"); DBCFile * dbc = new DBCFile("DBFilesClient\\Map.dbc");
dbc->open(); if(!dbc->open())
{
delete dbc;
printf("FATAL ERROR: Map.dbc not found in data file.\n");
return 1;
}
map_count=dbc->getRecordCount (); map_count=dbc->getRecordCount ();
map_ids=new map_id[map_count]; map_ids=new map_id[map_count];
for(unsigned int x=0;x<map_count;x++) for(unsigned int x=0;x<map_count;++x)
{ {
map_ids[x].id=dbc->getRecord (x).getUInt(0); map_ids[x].id=dbc->getRecord (x).getUInt(0);
strcpy(map_ids[x].name,dbc->getRecord(x).getString(1)); strcpy(map_ids[x].name,dbc->getRecord(x).getString(1));
@@ -564,10 +563,11 @@ int main(int argc, char ** argv)
} }
clreol(); clreol();
if(nError != ERROR_SUCCESS) { if(nError != ERROR_SUCCESS)
{
printf("ERROR: Extract %s. Work NOT complete.\n Precise vector data=%d.\nPress any key.\n",versionString, preciseVectorData); printf("ERROR: Extract %s. Work NOT complete.\n Precise vector data=%d.\nPress any key.\n",versionString, preciseVectorData);
_getch(); _getch();
} }
printf("Extract %s. Work complete. No errors.",versionString); printf("Extract %s. Work complete. No errors.",versionString);
} }
@@ -3,7 +3,6 @@
#include "wdtfile.h" #include "wdtfile.h"
#include "adtfile.h" #include "adtfile.h"
char * wdtGetPlainName(char * FileName) char * wdtGetPlainName(char * FileName)
{ {
char * szTemp; char * szTemp;
@@ -20,17 +19,15 @@ WDTFile::WDTFile(char* file_name, char* file_name1):WDT(file_name)
bool WDTFile::init(char *map_id) bool WDTFile::init(char *map_id)
{ {
if (WDT.isEof()) if (WDT.isEof())
{ {
//printf("Can't find WDT file.\n"); //printf("Can't find WDT file.\n");
return false; return false;
} }
char fourcc[5]; char fourcc[5];
size_t size; size_t size;
const char dirname[] = "buildings\\dir"; const char dirname[] = "buildings\\dir";
FILE *dirfile; FILE *dirfile;
dirfile = fopen(dirname, "ab"); dirfile = fopen(dirname, "ab");
@@ -40,7 +37,6 @@ bool WDTFile::init(char *map_id)
return false; return false;
} }
while (!WDT.isEof()) while (!WDT.isEof())
{ {
WDT.read(fourcc,4); WDT.read(fourcc,4);
@@ -75,8 +71,7 @@ bool WDTFile::init(char *map_id)
delete[] buf; delete[] buf;
} }
} }
else else if (!strcmp(fourcc,"MODF"))
if (!strcmp(fourcc,"MODF"))
{ {
// global wmo instance data // global wmo instance data
if (size) if (size)
@@ -87,13 +82,13 @@ bool WDTFile::init(char *map_id)
fake_mapname = "65 65 "; fake_mapname = "65 65 ";
//gWMO_mapname = fake_mapname + filename; //gWMO_mapname = fake_mapname + filename;
gWMO_mapname = fake_mapname + std::string(map_id); gWMO_mapname = fake_mapname + std::string(map_id);
for (int i=0; i<gnWMO; i++) for (int i=0; i<gnWMO; ++i)
{ {
int id; int id;
WDT.read(&id, 4); WDT.read(&id, 4);
WMOInstance inst(WDT,gWmoInstansName[id].c_str(),gWMO_mapname.c_str(), dirfile); WMOInstance inst(WDT,gWmoInstansName[id].c_str(),gWMO_mapname.c_str(), dirfile);
} }
delete[] gWmoInstansName; delete[] gWmoInstansName;
} }
} }
WDT.seek((int)nextpos); WDT.seek((int)nextpos);
@@ -111,11 +106,11 @@ WDTFile::~WDTFile(void)
ADTFile* WDTFile::GetMap(int x, int z) ADTFile* WDTFile::GetMap(int x, int z)
{ {
if(!(x>=0 && z >= 0 && x<64 && z<64)) return NULL; if(!(x>=0 && z >= 0 && x<64 && z<64))
return NULL;
char name[512]; char name[512];
sprintf(name,"World\\Maps\\%s\\%s_%d_%d.adt", filename.c_str(), filename.c_str(), x, z); sprintf(name,"World\\Maps\\%s\\%s_%d_%d.adt", filename.c_str(), filename.c_str(), x, z);
return new ADTFile(name); return new ADTFile(name);
} }

Some files were not shown because too many files have changed in this diff Show More