Update NufxLib snapshot to v3.0.0d2

This integrates the latest NufxLib sources, and updates CiderPress
to work with the API changes.
This commit is contained in:
Andy McFadden 2015-01-04 11:29:51 -08:00
parent e7512f5f07
commit 84706d7ea4
57 changed files with 4317 additions and 3659 deletions

View File

@ -32,7 +32,7 @@ static const WCHAR kVersionExtra[] =
BOOL AboutDialog::OnInitDialog(void) BOOL AboutDialog::OnInitDialog(void)
{ {
NuError nerr; NuError nerr;
long major, minor, bug; int32_t major, minor, bug;
CString newVersion, tmpStr; CString newVersion, tmpStr;
CStatic* pStatic; CStatic* pStatic;
//CString versionFmt; //CString versionFmt;

View File

@ -359,7 +359,7 @@ bool DiskEntry::GetFeatureFlag(Feature feature) const
{ {
CString result(""); CString result("");
DIError dierr; DIError dierr;
long major, minor, bug; int32_t major, minor, bug;
LOGI("Initializing DiskImg library"); LOGI("Initializing DiskImg library");

View File

@ -996,7 +996,7 @@ GenericArchive::FileDetails::operator const NuFileDetails() const
fOrigNameA = origName; fOrigNameA = origName;
details.origName = fOrigNameA; details.origName = fOrigNameA;
fStorageNameA = storageName; fStorageNameA = storageName;
details.storageName = fStorageNameA; details.storageNameMOR = fStorageNameA;
//details.fileSysID = fileSysID; //details.fileSysID = fileSysID;
details.fileSysInfo = fileSysInfo; details.fileSysInfo = fileSysInfo;
details.access = access; details.access = access;

View File

@ -404,7 +404,7 @@ void NufxEntry::AnalyzeRecord(const NuRecord* pRecord)
{ {
NuError nerr; NuError nerr;
CString result(""); CString result("");
long major, minor, bug; int32_t major, minor, bug;
nerr = NuGetVersion(&major, &minor, &bug, NULL, NULL); nerr = NuGetVersion(&major, &minor, &bug, NULL, NULL);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
@ -501,15 +501,15 @@ NuResult NufxArchive::NufxErrorMsgHandler(NuArchive*, void* vErrorMessage)
oldName = newName = NULL; oldName = newName = NULL;
if (pProgress->operation == kNuOpAdd) { if (pProgress->operation == kNuOpAdd) {
oldName = pProgress->origPathname; oldName = pProgress->origPathnameUNI;
newName = pProgress->pathname; newName = pProgress->pathnameUNI;
if (pThis->fProgressAsRecompress) if (pThis->fProgressAsRecompress)
oldName = "-"; oldName = "-";
} else if (pProgress->operation == kNuOpTest) { } else if (pProgress->operation == kNuOpTest) {
oldName = pProgress->pathname; oldName = pProgress->pathnameUNI;
} else if (pProgress->operation == kNuOpExtract) { } else if (pProgress->operation == kNuOpExtract) {
if (pThis->fProgressAsRecompress) { if (pThis->fProgressAsRecompress) {
oldName = pProgress->origPathname; oldName = pProgress->origPathnameUNI;
newName = "-"; newName = "-";
} }
} }
@ -796,7 +796,7 @@ NuResult NufxArchive::ContentFunc(NuArchive* pArchive, void* vpRecord)
pNewEntry = new NufxEntry(pArchive); pNewEntry = new NufxEntry(pArchive);
CStringW filenameW(pRecord->filename); CStringW filenameW(pRecord->filenameMOR);
pNewEntry->SetPathName(filenameW); pNewEntry->SetPathName(filenameW);
pNewEntry->SetFssep(NuGetSepFromSysInfo(pRecord->recFileSysInfo)); pNewEntry->SetFssep(NuGetSepFromSysInfo(pRecord->recFileSysInfo));
pNewEntry->SetFileType(pRecord->recFileType); pNewEntry->SetFileType(pRecord->recFileType);
@ -942,7 +942,7 @@ bool NufxArchive::BulkAdd(ActionProgressDialog* pActionProgress,
} }
/* actually do the work */ /* actually do the work */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
if (nerr != kNuErrAborted) { if (nerr != kNuErrAborted) {
@ -1055,7 +1055,7 @@ bool NufxArchive::AddDisk(ActionProgressDialog* pActionProgress,
origNameA = fileName; // narrowing conversion origNameA = fileName; // narrowing conversion
storageNameA = pathProp.fStoredPathName; storageNameA = pathProp.fStoredPathName;
details.origName = origNameA; details.origName = origNameA;
details.storageName = storageNameA; details.storageNameMOR = storageNameA;
details.fileSysID = kNuFileSysUnknown; details.fileSysID = kNuFileSysUnknown;
details.fileSysInfo = PathProposal::kDefaultStoredFssep; details.fileSysInfo = PathProposal::kDefaultStoredFssep;
@ -1125,7 +1125,7 @@ bool NufxArchive::AddDisk(ActionProgressDialog* pActionProgress,
pSource = NULL; /* NufxLib owns it now */ pSource = NULL; /* NufxLib owns it now */
/* actually do the work */ /* actually do the work */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
if (nerr != kNuErrAborted) { if (nerr != kNuErrAborted) {
@ -1298,7 +1298,7 @@ NuResult NufxArchive::HandleReplaceExisting(const NuErrorStatus* pErrorStatus)
NuResult result = kNuOK; NuResult result = kNuOK;
ASSERT(pErrorStatus != NULL); ASSERT(pErrorStatus != NULL);
ASSERT(pErrorStatus->pathname != NULL); ASSERT(pErrorStatus->pathnameUNI != NULL);
ASSERT(pErrorStatus->canOverwrite); ASSERT(pErrorStatus->canOverwrite);
ASSERT(pErrorStatus->canSkip); ASSERT(pErrorStatus->canSkip);
@ -1307,13 +1307,14 @@ NuResult NufxArchive::HandleReplaceExisting(const NuErrorStatus* pErrorStatus)
/* no firm policy, ask the user */ /* no firm policy, ask the user */
ConfirmOverwriteDialog confOvwr; ConfirmOverwriteDialog confOvwr;
PathName path(pErrorStatus->pathname); PathName path(pErrorStatus->pathnameUNI);
confOvwr.fExistingFile = pErrorStatus->pRecord->filename; confOvwr.fExistingFile = pErrorStatus->pRecord->filenameMOR;
confOvwr.fExistingFileModWhen = confOvwr.fExistingFileModWhen =
DateTimeToSeconds(&pErrorStatus->pRecord->recModWhen); DateTimeToSeconds(&pErrorStatus->pRecord->recModWhen);
if (pErrorStatus->origPathname != NULL) { if (pErrorStatus->origPathname != NULL) {
confOvwr.fNewFileSource = pErrorStatus->origPathname; // TODO: use wchar_t instead for origPathname
confOvwr.fNewFileSource = (char*) pErrorStatus->origPathname;
PathName checkPath(confOvwr.fNewFileSource); PathName checkPath(confOvwr.fNewFileSource);
confOvwr.fNewFileModWhen = checkPath.GetModWhen(); confOvwr.fNewFileModWhen = checkPath.GetModWhen();
} else { } else {
@ -1354,7 +1355,7 @@ NuResult NufxArchive::HandleAddNotFound(const NuErrorStatus* pErrorStatus)
CString errMsg; CString errMsg;
errMsg.Format(L"Failed while adding '%hs': file no longer exists.", errMsg.Format(L"Failed while adding '%hs': file no longer exists.",
pErrorStatus->pathname); pErrorStatus->pathnameUNI);
ShowFailureMsg(fpMsgWnd, errMsg, IDS_FAILED); ShowFailureMsg(fpMsgWnd, errMsg, IDS_FAILED);
return kNuAbort; return kNuAbort;
@ -1450,7 +1451,7 @@ bool NufxArchive::DeleteSelection(CWnd* pMsgWnd, SelectionSet* pSelSet)
} }
/* actually do the delete */ /* actually do the delete */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
errMsg.Format(L"Unable to delete all files: %hs.", NuStrError(nerr)); errMsg.Format(L"Unable to delete all files: %hs.", NuStrError(nerr));
@ -1546,7 +1547,7 @@ bool NufxArchive::RenameSelection(CWnd* pMsgWnd, SelectionSet* pSelSet)
{ {
CWaitCursor waitc; CWaitCursor waitc;
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
errMsg.Format(L"Unable to rename all files: %hs.", errMsg.Format(L"Unable to rename all files: %hs.",
@ -1693,7 +1694,7 @@ bool NufxArchive::RecompressSelection(CWnd* pMsgWnd, SelectionSet* pSelSet,
/* if we're sitting on too much, push it out */ /* if we're sitting on too much, push it out */
if (sizeInMemory > kMaxSizeInMemory) { if (sizeInMemory > kMaxSizeInMemory) {
/* flush anything pending */ /* flush anything pending */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
if (nerr != kNuErrAborted) { if (nerr != kNuErrAborted) {
@ -1727,7 +1728,7 @@ bool NufxArchive::RecompressSelection(CWnd* pMsgWnd, SelectionSet* pSelSet,
/* flush anything pending */ /* flush anything pending */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
if (nerr != kNuErrAborted) { if (nerr != kNuErrAborted) {
@ -2185,7 +2186,7 @@ void NufxArchive::XferFinish(CWnd* pMsgWnd)
LOGI(" NufxArchive::XferFinish"); LOGI(" NufxArchive::XferFinish");
/* actually do the work */ /* actually do the work */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
if (nerr != kNuErrAborted) { if (nerr != kNuErrAborted) {
@ -2345,7 +2346,7 @@ bool NufxArchive::SetComment(CWnd* pMsgWnd, GenericEntry* pGenericEntry,
pSource = NULL; // nufxlib owns it now pSource = NULL; // nufxlib owns it now
/* flush changes */ /* flush changes */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
errMsg.Format(L"Unable to flush comment changes: %hs.", errMsg.Format(L"Unable to flush comment changes: %hs.",
@ -2387,7 +2388,7 @@ bool NufxArchive::DeleteComment(CWnd* pMsgWnd, GenericEntry* pGenericEntry)
} }
/* flush changes */ /* flush changes */
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
errMsg.Format(L"Unable to flush comment deletion: %hs.", errMsg.Format(L"Unable to flush comment deletion: %hs.",
@ -2447,7 +2448,7 @@ bool NufxArchive::SetProps(CWnd* pMsgWnd, GenericEntry* pEntry,
return false; return false;
} }
long statusFlags; uint32_t statusFlags;
nerr = NuFlush(fpArchive, &statusFlags); nerr = NuFlush(fpArchive, &statusFlags);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
LOGI("ERROR: NuFlush failed: %hs", NuStrError(nerr)); LOGI("ERROR: NuFlush failed: %hs", NuStrError(nerr));

View File

@ -198,7 +198,7 @@ public:
static DIError AppCleanup(void); static DIError AppCleanup(void);
// return the DiskImg version number // return the DiskImg version number
static void GetVersion(long* pMajor, long* pMinor, long* pBug); static void GetVersion(int32_t* pMajor, int32_t* pMinor, int32_t* pBug);
static bool GetAppInitCalled(void) { return fAppInitCalled; } static bool GetAppInitCalled(void) { return fAppInitCalled; }
static bool GetHasSPTI(void); static bool GetHasSPTI(void);

View File

@ -24,7 +24,7 @@ const char* DiskImgLib::kASPIDev = "ASPI:";
/*static*/ DIError Global::AppInit(void) /*static*/ DIError Global::AppInit(void)
{ {
NuError nerr; NuError nerr;
long major, minor, bug; int32_t major, minor, bug;
if (fAppInitCalled) { if (fAppInitCalled) {
LOGW("DiskImg AppInit already called"); LOGW("DiskImg AppInit already called");
@ -123,7 +123,8 @@ const char* DiskImgLib::kASPIDev = "ASPI:";
/* /*
* Return current library versions. * Return current library versions.
*/ */
/*static*/ void Global::GetVersion(long* pMajor, long* pMinor, long* pBug) /*static*/ void Global::GetVersion(int32_t* pMajor, int32_t* pMinor,
int32_t* pBug)
{ {
if (pMajor != NULL) if (pMajor != NULL)
*pMajor = kDiskImgVersionMajor; *pMajor = kDiskImgVersionMajor;

View File

@ -683,9 +683,9 @@ DIError WrapperNuFX::Flush(GenericFD* pWrapperGFD, GenericFD* pDataGFD,
memset(&fileDetails, 0, sizeof(fileDetails)); memset(&fileDetails, 0, sizeof(fileDetails));
fileDetails.threadID = kNuThreadIDDiskImage; fileDetails.threadID = kNuThreadIDDiskImage;
if (fStorageName != NULL) if (fStorageName != NULL)
fileDetails.storageName = fStorageName; fileDetails.storageNameMOR = fStorageName; // TODO
else else
fileDetails.storageName = "NEW.DISK"; fileDetails.storageNameMOR = "NEW.DISK";
fileDetails.fileSysID = kNuFileSysUnknown; fileDetails.fileSysID = kNuFileSysUnknown;
fileDetails.fileSysInfo = kDefaultStorageFssep; fileDetails.fileSysInfo = kDefaultStorageFssep;
fileDetails.storageType = 512; fileDetails.storageType = 512;
@ -738,7 +738,7 @@ DIError WrapperNuFX::Flush(GenericFD* pWrapperGFD, GenericFD* pDataGFD,
/* /*
* Flush changes (does the actual compression). * Flush changes (does the actual compression).
*/ */
long status; uint32_t status;
nerr = NuFlush(fpArchive, &status); nerr = NuFlush(fpArchive, &status);
if (nerr != kNuErrNone) { if (nerr != kNuErrNone) {
LOGI(" NuFX flush failed (nerr=%d, status=%ld)", nerr, status); LOGI(" NuFX flush failed (nerr=%d, status=%ld)", nerr, status);

View File

@ -195,7 +195,7 @@ void MainWindow::ScanFiles(void)
goto bail; goto bail;
} }
long major, minor, bug; int32_t major, minor, bug;
DiskImgLib::Global::GetVersion(&major, &minor, &bug); DiskImgLib::Global::GetVersion(&major, &minor, &bug);
fprintf(scanOpts.outfp, "MDC for Windows v%d.%d.%d (DiskImg library v%ld.%ld.%ld)\n", fprintf(scanOpts.outfp, "MDC for Windows v%d.%d.%d (DiskImg library v%ld.%ld.%ld)\n",
kAppMajorVersion, kAppMinorVersion, kAppBugVersion, kAppMajorVersion, kAppMinorVersion, kAppBugVersion,

1
nufxlib/.gitignore vendored
View File

@ -11,5 +11,6 @@ samples/imgconv
samples/launder samples/launder
samples/test-basic samples/test-basic
samples/test-extract samples/test-extract
samples/test-names
samples/test-simple samples/test-simple
samples/test-twirl samples/test-twirl

View File

@ -16,13 +16,13 @@
#endif #endif
/* master header identification */ /* master header identification */
static const uchar kNuMasterID[kNufileIDLen] = static const uint8_t kNuMasterID[kNufileIDLen] =
{ 0x4e, 0xf5, 0x46, 0xe9, 0x6c, 0xe5 }; { 0x4e, 0xf5, 0x46, 0xe9, 0x6c, 0xe5 };
/* other identification; can be no longer than kNufileIDLen */ /* other identification; can be no longer than kNufileIDLen */
static const uchar kNuBinary2ID[] = static const uint8_t kNuBinary2ID[] =
{ 0x0a, 0x47, 0x4c }; { 0x0a, 0x47, 0x4c };
static const uchar kNuSHKSEAID[] = static const uint8_t kNuSHKSEAID[] =
{ 0xa2, 0x2e, 0x00 }; { 0xa2, 0x2e, 0x00 };
/* /*
@ -53,19 +53,16 @@ static void Nu_CloseAndFree(NuArchive* pArchive);
/* /*
* Allocate and initialize a new NuArchive structure. * Allocate and initialize a new NuArchive structure.
*/ */
static NuError static NuError Nu_NuArchiveNew(NuArchive** ppArchive)
Nu_NuArchiveNew(NuArchive** ppArchive)
{ {
Assert(ppArchive != nil); Assert(ppArchive != NULL);
/* validate some assumptions we make throughout the code */ /* validate some assumptions we make throughout the code */
Assert(sizeof(int) >= 2); Assert(sizeof(int) >= 2);
Assert(sizeof(ushort) >= 2);
Assert(sizeof(ulong) >= 4);
Assert(sizeof(void*) >= sizeof(NuArchive*)); Assert(sizeof(void*) >= sizeof(NuArchive*));
*ppArchive = Nu_Calloc(nil, sizeof(**ppArchive)); *ppArchive = Nu_Calloc(NULL, sizeof(**ppArchive));
if (*ppArchive == nil) if (*ppArchive == NULL)
return kNuErrMalloc; return kNuErrMalloc;
(*ppArchive)->structMagic = kNuArchiveStructMagic; (*ppArchive)->structMagic = kNuArchiveStructMagic;
@ -107,10 +104,9 @@ Nu_NuArchiveNew(NuArchive** ppArchive)
/* /*
* Free up a NuArchive structure and its contents. * Free up a NuArchive structure and its contents.
*/ */
static NuError static NuError Nu_NuArchiveFree(NuArchive* pArchive)
Nu_NuArchiveFree(NuArchive* pArchive)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pArchive->structMagic == kNuArchiveStructMagic); Assert(pArchive->structMagic == kNuArchiveStructMagic);
(void) Nu_RecordSet_FreeAllRecords(pArchive, &pArchive->origRecordSet); (void) Nu_RecordSet_FreeAllRecords(pArchive, &pArchive->origRecordSet);
@ -118,15 +114,15 @@ Nu_NuArchiveFree(NuArchive* pArchive)
(void) Nu_RecordSet_FreeAllRecords(pArchive, &pArchive->copyRecordSet); (void) Nu_RecordSet_FreeAllRecords(pArchive, &pArchive->copyRecordSet);
(void) Nu_RecordSet_FreeAllRecords(pArchive, &pArchive->newRecordSet); (void) Nu_RecordSet_FreeAllRecords(pArchive, &pArchive->newRecordSet);
Nu_Free(nil, pArchive->archivePathname); Nu_Free(NULL, pArchive->archivePathnameUNI);
Nu_Free(nil, pArchive->tmpPathname); Nu_Free(NULL, pArchive->tmpPathnameUNI);
Nu_Free(nil, pArchive->compBuf); Nu_Free(NULL, pArchive->compBuf);
Nu_Free(nil, pArchive->lzwCompressState); Nu_Free(NULL, pArchive->lzwCompressState);
Nu_Free(nil, pArchive->lzwExpandState); Nu_Free(NULL, pArchive->lzwExpandState);
/* mark it as deceased to prevent further use, then free it */ /* mark it as deceased to prevent further use, then free it */
pArchive->structMagic = kNuArchiveStructMagic ^ 0xffffffff; pArchive->structMagic = kNuArchiveStructMagic ^ 0xffffffff;
Nu_Free(nil, pArchive); Nu_Free(NULL, pArchive);
return kNuErrNone; return kNuErrNone;
} }
@ -135,13 +131,12 @@ Nu_NuArchiveFree(NuArchive* pArchive)
/* /*
* Copy a NuMasterHeader struct. * Copy a NuMasterHeader struct.
*/ */
void void Nu_MasterHeaderCopy(NuArchive* pArchive, NuMasterHeader* pDstHeader,
Nu_MasterHeaderCopy(NuArchive* pArchive, NuMasterHeader* pDstHeader,
const NuMasterHeader* pSrcHeader) const NuMasterHeader* pSrcHeader)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pDstHeader != nil); Assert(pDstHeader != NULL);
Assert(pSrcHeader != nil); Assert(pSrcHeader != NULL);
*pDstHeader = *pSrcHeader; *pDstHeader = *pSrcHeader;
} }
@ -149,10 +144,10 @@ Nu_MasterHeaderCopy(NuArchive* pArchive, NuMasterHeader* pDstHeader,
/* /*
* Get a pointer to the archive master header (this is an API call). * Get a pointer to the archive master header (this is an API call).
*/ */
NuError NuError Nu_GetMasterHeader(NuArchive* pArchive,
Nu_GetMasterHeader(NuArchive* pArchive, const NuMasterHeader** ppMasterHeader) const NuMasterHeader** ppMasterHeader)
{ {
if (ppMasterHeader == nil) if (ppMasterHeader == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
*ppMasterHeader = &pArchive->masterHeader; *ppMasterHeader = &pArchive->masterHeader;
@ -164,16 +159,15 @@ Nu_GetMasterHeader(NuArchive* pArchive, const NuMasterHeader** ppMasterHeader)
/* /*
* Allocate the general-purpose compression buffer, if needed. * Allocate the general-purpose compression buffer, if needed.
*/ */
NuError NuError Nu_AllocCompressionBufferIFN(NuArchive* pArchive)
Nu_AllocCompressionBufferIFN(NuArchive* pArchive)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
if (pArchive->compBuf != nil) if (pArchive->compBuf != NULL)
return kNuErrNone; return kNuErrNone;
pArchive->compBuf = Nu_Malloc(pArchive, kNuGenCompBufSize); pArchive->compBuf = Nu_Malloc(pArchive, kNuGenCompBufSize);
if (pArchive->compBuf == nil) if (pArchive->compBuf == NULL)
return kNuErrMalloc; return kNuErrMalloc;
return kNuErrNone; return kNuErrNone;
@ -183,8 +177,7 @@ Nu_AllocCompressionBufferIFN(NuArchive* pArchive)
/* /*
* Return a unique value. * Return a unique value.
*/ */
NuRecordIdx NuRecordIdx Nu_GetNextRecordIdx(NuArchive* pArchive)
Nu_GetNextRecordIdx(NuArchive* pArchive)
{ {
return pArchive->nextRecordIdx++; return pArchive->nextRecordIdx++;
} }
@ -192,8 +185,7 @@ Nu_GetNextRecordIdx(NuArchive* pArchive)
/* /*
* Return a unique value. * Return a unique value.
*/ */
NuThreadIdx NuThreadIdx Nu_GetNextThreadIdx(NuArchive* pArchive)
Nu_GetNextThreadIdx(NuArchive* pArchive)
{ {
return pArchive->nextRecordIdx++; /* just use the record counter */ return pArchive->nextRecordIdx++; /* just use the record counter */
} }
@ -208,8 +200,7 @@ Nu_GetNextThreadIdx(NuArchive* pArchive)
/* /*
* Copy the wrapper from the archive file to the temp file. * Copy the wrapper from the archive file to the temp file.
*/ */
NuError NuError Nu_CopyWrapperToTemp(NuArchive* pArchive)
Nu_CopyWrapperToTemp(NuArchive* pArchive)
{ {
NuError err; NuError err;
@ -247,13 +238,12 @@ bail:
* guess some of the SEA weirdness stems from some far-sighted support * guess some of the SEA weirdness stems from some far-sighted support
* for multiple archives within a single SEA wrapper. * for multiple archives within a single SEA wrapper.
*/ */
NuError NuError Nu_UpdateWrapper(NuArchive* pArchive, FILE* fp)
Nu_UpdateWrapper(NuArchive* pArchive, FILE* fp)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
Boolean hasBinary2, hasSea; Boolean hasBinary2, hasSea;
uchar identBuf[kNufileIDLen]; uint8_t identBuf[kNufileIDLen];
ulong archiveLen, archiveLen512; uint32_t archiveLen, archiveLen512;
Assert(pArchive->newMasterHeader.isValid); /* need new crc and len */ Assert(pArchive->newMasterHeader.isValid); /* need new crc and len */
@ -306,20 +296,20 @@ Nu_UpdateWrapper(NuArchive* pArchive, FILE* fp)
err = Nu_FSeek(fp, kNuBNYFileSizeLo - kNufileIDLen, SEEK_CUR); err = Nu_FSeek(fp, kNuBNYFileSizeLo - kNufileIDLen, SEEK_CUR);
BailError(err); BailError(err);
Nu_WriteTwo(pArchive, fp, (ushort)(archiveLen512 & 0xffff)); Nu_WriteTwo(pArchive, fp, (uint16_t)(archiveLen512 & 0xffff));
err = Nu_FSeek(fp, kNuBNYFileSizeHi - (kNuBNYFileSizeLo+2), SEEK_CUR); err = Nu_FSeek(fp, kNuBNYFileSizeHi - (kNuBNYFileSizeLo+2), SEEK_CUR);
BailError(err); BailError(err);
Nu_WriteTwo(pArchive, fp, (ushort)(archiveLen512 >> 16)); Nu_WriteTwo(pArchive, fp, (uint16_t)(archiveLen512 >> 16));
err = Nu_FSeek(fp, kNuBNYEOFLo - (kNuBNYFileSizeHi+2), SEEK_CUR); err = Nu_FSeek(fp, kNuBNYEOFLo - (kNuBNYFileSizeHi+2), SEEK_CUR);
BailError(err); BailError(err);
Nu_WriteTwo(pArchive, fp, (ushort)(archiveLen & 0xffff)); Nu_WriteTwo(pArchive, fp, (uint16_t)(archiveLen & 0xffff));
Nu_WriteOne(pArchive, fp, (uchar)((archiveLen >> 16) & 0xff)); Nu_WriteOne(pArchive, fp, (uint8_t)((archiveLen >> 16) & 0xff));
err = Nu_FSeek(fp, kNuBNYEOFHi - (kNuBNYEOFLo+3), SEEK_CUR); err = Nu_FSeek(fp, kNuBNYEOFHi - (kNuBNYEOFLo+3), SEEK_CUR);
BailError(err); BailError(err);
Nu_WriteOne(pArchive, fp, (uchar)(archiveLen >> 24)); Nu_WriteOne(pArchive, fp, (uint8_t)(archiveLen >> 24));
err = Nu_FSeek(fp, kNuBNYDiskSpace - (kNuBNYEOFHi+1), SEEK_CUR); err = Nu_FSeek(fp, kNuBNYDiskSpace - (kNuBNYEOFHi+1), SEEK_CUR);
BailError(err); BailError(err);
@ -358,11 +348,11 @@ Nu_UpdateWrapper(NuArchive* pArchive, FILE* fp)
err = Nu_FSeek(fp, kNuSEALength1 - (kNuSEAFunkySize+4), SEEK_CUR); err = Nu_FSeek(fp, kNuSEALength1 - (kNuSEAFunkySize+4), SEEK_CUR);
BailError(err); BailError(err);
Nu_WriteTwo(pArchive, fp, (ushort)archiveLen); Nu_WriteTwo(pArchive, fp, (uint16_t)archiveLen);
err = Nu_FSeek(fp, kNuSEALength2 - (kNuSEALength1+2), SEEK_CUR); err = Nu_FSeek(fp, kNuSEALength2 - (kNuSEALength1+2), SEEK_CUR);
BailError(err); BailError(err);
Nu_WriteTwo(pArchive, fp, (ushort)archiveLen); Nu_WriteTwo(pArchive, fp, (uint16_t)archiveLen);
/* seek past end of SEA wrapper */ /* seek past end of SEA wrapper */
err = Nu_FSeek(fp, kNuSEAOffset - (kNuSEALength2+2), SEEK_CUR); err = Nu_FSeek(fp, kNuSEAOffset - (kNuSEALength2+2), SEEK_CUR);
@ -399,8 +389,7 @@ bail:
* require additional disk space to be used, assuming a filesystem block * require additional disk space to be used, assuming a filesystem block
* size of at least 128 bytes. * size of at least 128 bytes.
*/ */
NuError NuError Nu_AdjustWrapperPadding(NuArchive* pArchive, FILE* fp)
Nu_AdjustWrapperPadding(NuArchive* pArchive, FILE* fp)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
Boolean hasBinary2, hasSea; Boolean hasBinary2, hasSea;
@ -495,17 +484,16 @@ bail:
* *
* On exit, the stream will be positioned just past the master header. * On exit, the stream will be positioned just past the master header.
*/ */
static NuError static NuError Nu_ReadMasterHeader(NuArchive* pArchive)
Nu_ReadMasterHeader(NuArchive* pArchive)
{ {
NuError err; NuError err;
ushort crc; uint16_t crc;
FILE* fp; FILE* fp;
NuMasterHeader* pHeader; NuMasterHeader* pHeader;
Boolean isBinary2 = false; Boolean isBinary2 = false;
Boolean isSea = false; Boolean isSea = false;
Assert(pArchive != nil); Assert(pArchive != NULL);
fp = pArchive->archiveFp; /* saves typing */ fp = pArchive->archiveFp; /* saves typing */
pHeader = &pArchive->masterHeader; pHeader = &pArchive->masterHeader;
@ -640,7 +628,7 @@ retry:
/* compare the CRC */ /* compare the CRC */
if (!pArchive->valIgnoreCRC && crc != pHeader->mhMasterCRC) { if (!pArchive->valIgnoreCRC && crc != pHeader->mhMasterCRC) {
if (!Nu_ShouldIgnoreBadCRC(pArchive, nil, kNuErrBadMHCRC)) { if (!Nu_ShouldIgnoreBadCRC(pArchive, NULL, kNuErrBadMHCRC)) {
err = kNuErrBadMHCRC; err = kNuErrBadMHCRC;
Nu_ReportError(NU_BLOB, err, "Stored MH CRC=0x%04x, calc=0x%04x", Nu_ReportError(NU_BLOB, err, "Stored MH CRC=0x%04x, calc=0x%04x",
pHeader->mhMasterCRC, crc); pHeader->mhMasterCRC, crc);
@ -669,7 +657,7 @@ retry:
if (pHeader->mhMasterEOF == kNuMasterHeaderSize) { if (pHeader->mhMasterEOF == kNuMasterHeaderSize) {
err = kNuErrNoRecords; err = kNuErrNoRecords;
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Master EOF is %ld, archive is probably truncated", "Master EOF is %u, archive is probably truncated",
pHeader->mhMasterEOF); pHeader->mhMasterEOF);
goto bail; goto bail;
} }
@ -712,12 +700,11 @@ bail:
* Prepare the NuArchive and NuMasterHeader structures for use with a * Prepare the NuArchive and NuMasterHeader structures for use with a
* newly-created archive. * newly-created archive.
*/ */
static void static void Nu_InitNewArchive(NuArchive* pArchive)
Nu_InitNewArchive(NuArchive* pArchive)
{ {
NuMasterHeader* pHeader; NuMasterHeader* pHeader;
Assert(pArchive != nil); Assert(pArchive != NULL);
pHeader = &pArchive->masterHeader; pHeader = &pArchive->masterHeader;
@ -741,14 +728,13 @@ Nu_InitNewArchive(NuArchive* pArchive)
/* /*
* Open an archive in streaming read-only mode. * Open an archive in streaming read-only mode.
*/ */
NuError NuError Nu_StreamOpenRO(FILE* infp, NuArchive** ppArchive)
Nu_StreamOpenRO(FILE* infp, NuArchive** ppArchive)
{ {
NuError err; NuError err;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
Assert(infp != nil); Assert(infp != NULL);
Assert(ppArchive != nil); Assert(ppArchive != NULL);
err = Nu_NuArchiveNew(ppArchive); err = Nu_NuArchiveNew(ppArchive);
if (err != kNuErrNone) if (err != kNuErrNone)
@ -757,16 +743,16 @@ Nu_StreamOpenRO(FILE* infp, NuArchive** ppArchive)
pArchive->openMode = kNuOpenStreamingRO; pArchive->openMode = kNuOpenStreamingRO;
pArchive->archiveFp = infp; pArchive->archiveFp = infp;
pArchive->archivePathname = strdup("(stream)"); pArchive->archivePathnameUNI = strdup("(stream)");
err = Nu_ReadMasterHeader(pArchive); err = Nu_ReadMasterHeader(pArchive);
BailError(err); BailError(err);
bail: bail:
if (err != kNuErrNone) { if (err != kNuErrNone) {
if (pArchive != nil) if (pArchive != NULL)
(void) Nu_NuArchiveFree(pArchive); (void) Nu_NuArchiveFree(pArchive);
*ppArchive = nil; *ppArchive = NULL;
} }
return err; return err;
} }
@ -775,21 +761,24 @@ bail:
/* /*
* Open an archive in non-streaming read-only mode. * Open an archive in non-streaming read-only mode.
*/ */
NuError NuError Nu_OpenRO(const UNICHAR* archivePathnameUNI, NuArchive** ppArchive)
Nu_OpenRO(const char* archivePathname, NuArchive** ppArchive)
{ {
NuError err; NuError err;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
FILE* fp = nil; FILE* fp = NULL;
if (archivePathname == nil || !strlen(archivePathname) || ppArchive == nil) if (archivePathnameUNI == NULL || !strlen(archivePathnameUNI) ||
ppArchive == NULL)
{
return kNuErrInvalidArg; return kNuErrInvalidArg;
}
*ppArchive = nil; *ppArchive = NULL;
fp = fopen(archivePathname, kNuFileOpenReadOnly); fp = fopen(archivePathnameUNI, kNuFileOpenReadOnly);
if (fp == nil) { if (fp == NULL) {
Nu_ReportError(NU_BLOB, errno, "Unable to open '%s'", archivePathname); Nu_ReportError(NU_BLOB, errno, "Unable to open '%s'",
archivePathnameUNI);
err = kNuErrFileOpen; err = kNuErrFileOpen;
goto bail; goto bail;
} }
@ -801,19 +790,19 @@ Nu_OpenRO(const char* archivePathname, NuArchive** ppArchive)
pArchive->openMode = kNuOpenRO; pArchive->openMode = kNuOpenRO;
pArchive->archiveFp = fp; pArchive->archiveFp = fp;
fp = nil; fp = NULL;
pArchive->archivePathname = strdup(archivePathname); pArchive->archivePathnameUNI = strdup(archivePathnameUNI);
err = Nu_ReadMasterHeader(pArchive); err = Nu_ReadMasterHeader(pArchive);
BailError(err); BailError(err);
bail: bail:
if (err != kNuErrNone) { if (err != kNuErrNone) {
if (pArchive != nil) { if (pArchive != NULL) {
(void) Nu_CloseAndFree(pArchive); (void) Nu_CloseAndFree(pArchive);
*ppArchive = nil; *ppArchive = NULL;
} }
if (fp != nil) if (fp != NULL)
fclose(fp); fclose(fp);
} }
return err; return err;
@ -822,15 +811,15 @@ bail:
/* /*
* Open a temp file. If "fileName" contains six Xs ("XXXXXX"), it will * Open a temp file. If "fileName" contains six Xs ("XXXXXX"), it will
* be treated as a mktemp-style template, and modified before use. * be treated as a mktemp-style template, and modified before use (so
* pass a copy of the string in).
* *
* Thought for the day: consider using Win32 SetFileAttributes() to make * Thought for the day: consider using Win32 SetFileAttributes() to make
* temp files hidden. We will need to un-hide it before rolling it over. * temp files hidden. We will need to un-hide it before rolling it over.
*/ */
static NuError static NuError Nu_OpenTempFile(UNICHAR* fileNameUNI, FILE** pFp)
Nu_OpenTempFile(char* fileName, FILE** pFp)
{ {
NuArchive* pArchive = nil; /* dummy for NU_BLOB */ NuArchive* pArchive = NULL; /* dummy for NU_BLOB */
NuError err = kNuErrNone; NuError err = kNuErrNone;
int len; int len;
@ -843,25 +832,25 @@ Nu_OpenTempFile(char* fileName, FILE** pFp)
* to complain about mktemp, since it's generally a bad way to do * to complain about mktemp, since it's generally a bad way to do
* things. * things.
*/ */
len = strlen(fileName); len = strlen(fileNameUNI);
if (len > 6 && strcmp(fileName + len - 6, "XXXXXX") == 0) { if (len > 6 && strcmp(fileNameUNI + len - 6, "XXXXXX") == 0) {
#if defined(HAVE_MKSTEMP) && defined(HAVE_FDOPEN) #if defined(HAVE_MKSTEMP) && defined(HAVE_FDOPEN)
int fd; int fd;
DBUG(("+++ Using mkstemp\n")); DBUG(("+++ Using mkstemp\n"));
/* this modifies the template *and* opens the file */ /* this modifies the template *and* opens the file */
fd = mkstemp(fileName); fd = mkstemp(fileNameUNI);
if (fd < 0) { if (fd < 0) {
err = errno ? errno : kNuErrFileOpen; err = errno ? errno : kNuErrFileOpen;
Nu_ReportError(NU_BLOB, kNuErrNone, "mkstemp failed on '%s'", Nu_ReportError(NU_BLOB, kNuErrNone, "mkstemp failed on '%s'",
fileName); fileNameUNI);
goto bail; goto bail;
} }
DBUG(("--- Fd-opening temp file '%s'\n", fileName)); DBUG(("--- Fd-opening temp file '%s'\n", fileNameUNI));
*pFp = fdopen(fd, kNuFileOpenReadWriteCreat); *pFp = fdopen(fd, kNuFileOpenReadWriteCreat);
if (*pFp == nil) { if (*pFp == NULL) {
close(fd); close(fd);
err = errno ? errno : kNuErrFileOpen; err = errno ? errno : kNuErrFileOpen;
goto bail; goto bail;
@ -874,10 +863,10 @@ Nu_OpenTempFile(char* fileName, FILE** pFp)
char* result; char* result;
DBUG(("+++ Using mktemp\n")); DBUG(("+++ Using mktemp\n"));
result = mktemp(fileName); result = mktemp(fileNameUNI);
if (result == nil) { if (result == NULL) {
Nu_ReportError(NU_BLOB, kNuErrNone, "mktemp failed on '%s'", Nu_ReportError(NU_BLOB, kNuErrNone, "mktemp failed on '%s'",
fileName); fileNameUNI);
err = kNuErrInternal; err = kNuErrInternal;
goto bail; goto bail;
} }
@ -886,34 +875,33 @@ Nu_OpenTempFile(char* fileName, FILE** pFp)
#endif #endif
} }
DBUG(("--- Opening temp file '%s'\n", fileName)); DBUG(("--- Opening temp file '%s'\n", fileNameUNI));
#if defined(HAVE_FDOPEN) #if defined(HAVE_FDOPEN)
{ {
int fd; int fd;
fd = open(fileName, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600); fd = open(fileNameUNI, O_RDWR|O_CREAT|O_EXCL|O_BINARY, 0600);
if (fd < 0) { if (fd < 0) {
err = errno ? errno : kNuErrFileOpen; err = errno ? errno : kNuErrFileOpen;
goto bail; goto bail;
} }
*pFp = fdopen(fd, kNuFileOpenReadWriteCreat); *pFp = fdopen(fd, kNuFileOpenReadWriteCreat);
if (*pFp == nil) { if (*pFp == NULL) {
close(fd); close(fd);
err = errno ? errno : kNuErrFileOpen; err = errno ? errno : kNuErrFileOpen;
goto bail; goto bail;
} }
} }
#else #else
/* (not sure how portable "access" is... I think it's POSIX) */ if (access(fileNameUNI, F_OK) == 0) {
if (access(fileName, F_OK) == 0) {
err = kNuErrFileExists; err = kNuErrFileExists;
goto bail; goto bail;
} }
*pFp = fopen(fileName, kNuFileOpenReadWriteCreat); *pFp = fopen(fileNameUNI, kNuFileOpenReadWriteCreat);
if (*pFp == nil) { if (*pFp == NULL) {
err = errno ? errno : kNuErrFileOpen; err = errno ? errno : kNuErrFileOpen;
goto bail; goto bail;
} }
@ -928,26 +916,25 @@ bail:
* Open an archive in read-write mode, optionally creating it if it doesn't * Open an archive in read-write mode, optionally creating it if it doesn't
* exist. * exist.
*/ */
NuError NuError Nu_OpenRW(const UNICHAR* archivePathnameUNI,
Nu_OpenRW(const char* archivePathname, const char* tmpPathname, ulong flags, const UNICHAR* tmpPathnameUNI, uint32_t flags, NuArchive** ppArchive)
NuArchive** ppArchive)
{ {
NuError err; NuError err;
FILE* fp = nil; FILE* fp = NULL;
FILE* tmpFp = nil; FILE* tmpFp = NULL;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
char* tmpPathDup = nil; char* tmpPathDup = NULL;
Boolean archiveExists; Boolean archiveExists;
Boolean newlyCreated; Boolean newlyCreated;
if (archivePathname == nil || !strlen(archivePathname) || if (archivePathnameUNI == NULL || !strlen(archivePathnameUNI) ||
tmpPathname == nil || !strlen(tmpPathname) || ppArchive == nil || tmpPathnameUNI == NULL || !strlen(tmpPathnameUNI) ||
(flags & ~(kNuOpenCreat|kNuOpenExcl)) != 0) ppArchive == NULL || (flags & ~(kNuOpenCreat|kNuOpenExcl)) != 0)
{ {
return kNuErrInvalidArg; return kNuErrInvalidArg;
} }
archiveExists = (access(archivePathname, F_OK) == 0); archiveExists = (access(archivePathnameUNI, F_OK) == 0);
/* /*
* Open or create archive file. * Open or create archive file.
@ -955,27 +942,30 @@ Nu_OpenRW(const char* archivePathname, const char* tmpPathname, ulong flags,
if (archiveExists) { if (archiveExists) {
if ((flags & kNuOpenCreat) && (flags & kNuOpenExcl)) { if ((flags & kNuOpenCreat) && (flags & kNuOpenExcl)) {
err = kNuErrFileExists; err = kNuErrFileExists;
Nu_ReportError(NU_BLOB, err, "File '%s' exists", archivePathname); Nu_ReportError(NU_BLOB, err, "File '%s' exists",
archivePathnameUNI);
goto bail; goto bail;
} }
fp = fopen(archivePathname, kNuFileOpenReadWrite); fp = fopen(archivePathnameUNI, kNuFileOpenReadWrite);
newlyCreated = false; newlyCreated = false;
} else { } else {
if (!(flags & kNuOpenCreat)) { if (!(flags & kNuOpenCreat)) {
err = kNuErrFileNotFound; err = kNuErrFileNotFound;
Nu_ReportError(NU_BLOB, err, "File '%s' not found",archivePathname); Nu_ReportError(NU_BLOB, err, "File '%s' not found",
archivePathnameUNI);
goto bail; goto bail;
} }
fp = fopen(archivePathname, kNuFileOpenReadWriteCreat); fp = fopen(archivePathnameUNI, kNuFileOpenReadWriteCreat);
newlyCreated = true; newlyCreated = true;
} }
if (fp == nil) { if (fp == NULL) {
if (errno == EACCES) if (errno == EACCES)
err = kNuErrFileAccessDenied; err = kNuErrFileAccessDenied;
else else
err = kNuErrFileOpen; err = kNuErrFileOpen;
Nu_ReportError(NU_BLOB, errno, "Unable to open '%s'", archivePathname); Nu_ReportError(NU_BLOB, errno, "Unable to open '%s'",
archivePathnameUNI);
goto bail; goto bail;
} }
@ -985,7 +975,7 @@ Nu_OpenRW(const char* archivePathname, const char* tmpPathname, ulong flags,
if (archiveExists && !newlyCreated) { if (archiveExists && !newlyCreated) {
long length; long length;
err = Nu_GetFileLength(nil, fp, &length); err = Nu_GetFileLength(NULL, fp, &length);
BailError(err); BailError(err);
if (!length) { if (!length) {
@ -1003,12 +993,12 @@ Nu_OpenRW(const char* archivePathname, const char* tmpPathname, ulong flags,
* So, create a temp file whether we think we need one or not. Won't * So, create a temp file whether we think we need one or not. Won't
* do any harm, and might save us some troubles later. * do any harm, and might save us some troubles later.
*/ */
tmpPathDup = strdup(tmpPathname); tmpPathDup = strdup(tmpPathnameUNI);
BailNil(tmpPathDup); BailNil(tmpPathDup);
err = Nu_OpenTempFile(tmpPathDup, &tmpFp); err = Nu_OpenTempFile(tmpPathDup, &tmpFp);
if (err != kNuErrNone) { if (err != kNuErrNone) {
Nu_ReportError(NU_BLOB, err, "Failed opening temp file '%s'", Nu_ReportError(NU_BLOB, err, "Failed opening temp file '%s'",
tmpPathname); tmpPathnameUNI);
goto bail; goto bail;
} }
@ -1019,13 +1009,13 @@ Nu_OpenRW(const char* archivePathname, const char* tmpPathname, ulong flags,
pArchive->openMode = kNuOpenRW; pArchive->openMode = kNuOpenRW;
pArchive->newlyCreated = newlyCreated; pArchive->newlyCreated = newlyCreated;
pArchive->archivePathname = strdup(archivePathname); pArchive->archivePathnameUNI = strdup(archivePathnameUNI);
pArchive->archiveFp = fp; pArchive->archiveFp = fp;
fp = nil; fp = NULL;
pArchive->tmpFp = tmpFp; pArchive->tmpFp = tmpFp;
tmpFp = nil; tmpFp = NULL;
pArchive->tmpPathname = tmpPathDup; pArchive->tmpPathnameUNI = tmpPathDup;
tmpPathDup = nil; tmpPathDup = NULL;
if (archiveExists && !newlyCreated) { if (archiveExists && !newlyCreated) {
err = Nu_ReadMasterHeader(pArchive); err = Nu_ReadMasterHeader(pArchive);
@ -1036,15 +1026,15 @@ Nu_OpenRW(const char* archivePathname, const char* tmpPathname, ulong flags,
bail: bail:
if (err != kNuErrNone) { if (err != kNuErrNone) {
if (pArchive != nil) { if (pArchive != NULL) {
(void) Nu_CloseAndFree(pArchive); (void) Nu_CloseAndFree(pArchive);
*ppArchive = nil; *ppArchive = NULL;
} }
if (fp != nil) if (fp != NULL)
fclose(fp); fclose(fp);
if (tmpFp != nil) if (tmpFp != NULL)
fclose(tmpFp); fclose(tmpFp);
if (tmpPathDup != nil) if (tmpPathDup != NULL)
Nu_Free(pArchive, tmpPathDup); Nu_Free(pArchive, tmpPathDup);
} }
return err; return err;
@ -1060,17 +1050,16 @@ bail:
/* /*
* Write the NuFX master header at the current offset. * Write the NuFX master header at the current offset.
*/ */
NuError NuError Nu_WriteMasterHeader(NuArchive* pArchive, FILE* fp,
Nu_WriteMasterHeader(NuArchive* pArchive, FILE* fp,
NuMasterHeader* pHeader) NuMasterHeader* pHeader)
{ {
NuError err; NuError err;
long crcOffset; long crcOffset;
ushort crc; uint16_t crc;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pHeader != nil); Assert(pHeader != NULL);
Assert(pHeader->isValid); Assert(pHeader->isValid);
Assert(pHeader->mhMasterVersion == kNuOurMHVersion); Assert(pHeader->mhMasterVersion == kNuOurMHVersion);
@ -1122,23 +1111,22 @@ bail:
* If it's a brand-new archive, and we didn't add anything to it, then we * If it's a brand-new archive, and we didn't add anything to it, then we
* want to remove the stub archive file. * want to remove the stub archive file.
*/ */
static void static void Nu_CloseAndFree(NuArchive* pArchive)
Nu_CloseAndFree(NuArchive* pArchive)
{ {
if (pArchive->archiveFp != nil) { if (pArchive->archiveFp != NULL) {
DBUG(("--- Closing archive\n")); DBUG(("--- Closing archive\n"));
fclose(pArchive->archiveFp); fclose(pArchive->archiveFp);
pArchive->archiveFp = nil; pArchive->archiveFp = NULL;
} }
if (pArchive->tmpFp != nil) { if (pArchive->tmpFp != NULL) {
DBUG(("--- Closing and removing temp file\n")); DBUG(("--- Closing and removing temp file\n"));
fclose(pArchive->tmpFp); fclose(pArchive->tmpFp);
pArchive->tmpFp = nil; pArchive->tmpFp = NULL;
Assert(pArchive->tmpPathname != nil); Assert(pArchive->tmpPathnameUNI != NULL);
if (remove(pArchive->tmpPathname) != 0) { if (remove(pArchive->tmpPathnameUNI) != 0) {
Nu_ReportError(NU_BLOB, errno, "Unable to remove temp file '%s'", Nu_ReportError(NU_BLOB, errno, "Unable to remove temp file '%s'",
pArchive->tmpPathname); pArchive->tmpPathnameUNI);
/* keep going */ /* keep going */
} }
} }
@ -1146,9 +1134,9 @@ Nu_CloseAndFree(NuArchive* pArchive)
if (pArchive->newlyCreated && Nu_RecordSet_IsEmpty(&pArchive->origRecordSet)) if (pArchive->newlyCreated && Nu_RecordSet_IsEmpty(&pArchive->origRecordSet))
{ {
DBUG(("--- Newly-created archive unmodified; removing it\n")); DBUG(("--- Newly-created archive unmodified; removing it\n"));
if (remove(pArchive->archivePathname) != 0) { if (remove(pArchive->archivePathnameUNI) != 0) {
Nu_ReportError(NU_BLOB, errno, "Unable to remove archive file '%s'", Nu_ReportError(NU_BLOB, errno, "Unable to remove archive file '%s'",
pArchive->archivePathname); pArchive->archivePathnameUNI);
} }
} }
@ -1158,13 +1146,12 @@ Nu_CloseAndFree(NuArchive* pArchive)
/* /*
* Flush pending changes to the archive, then close it. * Flush pending changes to the archive, then close it.
*/ */
NuError NuError Nu_Close(NuArchive* pArchive)
Nu_Close(NuArchive* pArchive)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
long flushStatus; uint32_t flushStatus;
Assert(pArchive != nil); Assert(pArchive != NULL);
if (!Nu_IsReadOnly(pArchive)) if (!Nu_IsReadOnly(pArchive))
err = Nu_Flush(pArchive, &flushStatus); err = Nu_Flush(pArchive, &flushStatus);
@ -1190,29 +1177,28 @@ Nu_Close(NuArchive* pArchive)
/* /*
* Delete the archive file, which should already have been closed. * Delete the archive file, which should already have been closed.
*/ */
NuError NuError Nu_DeleteArchiveFile(NuArchive* pArchive)
Nu_DeleteArchiveFile(NuArchive* pArchive)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pArchive->archiveFp == nil); Assert(pArchive->archiveFp == NULL);
Assert(pArchive->archivePathname != nil); Assert(pArchive->archivePathnameUNI != NULL);
return Nu_DeleteFile(pArchive->archivePathname); return Nu_DeleteFile(pArchive->archivePathnameUNI);
} }
/* /*
* Rename the temp file on top of the original archive. The temp file * Rename the temp file on top of the original archive. The temp file
* should be closed, and the archive file should be deleted. * should be closed, and the archive file should be deleted.
*/ */
NuError NuError Nu_RenameTempToArchive(NuArchive* pArchive)
Nu_RenameTempToArchive(NuArchive* pArchive)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pArchive->archiveFp == nil); Assert(pArchive->archiveFp == NULL);
Assert(pArchive->tmpFp == nil); Assert(pArchive->tmpFp == NULL);
Assert(pArchive->archivePathname != nil); Assert(pArchive->archivePathnameUNI != NULL);
Assert(pArchive->tmpPathname != nil); Assert(pArchive->tmpPathnameUNI != NULL);
return Nu_RenameFile(pArchive->tmpPathname, pArchive->archivePathname); return Nu_RenameFile(pArchive->tmpPathnameUNI,
pArchive->archivePathnameUNI);
} }

View File

@ -26,45 +26,41 @@
/* /*
* Read one byte, optionally computing a CRC. * Read one byte, optionally computing a CRC.
*/ */
uchar uint8_t Nu_ReadOneC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc)
Nu_ReadOneC(NuArchive* pArchive, FILE* fp, ushort* pCrc)
{ {
int ic; int ic;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
return (uchar) ic; return (uint8_t) ic;
} }
uchar uint8_t Nu_ReadOne(NuArchive* pArchive, FILE* fp)
Nu_ReadOne(NuArchive* pArchive, FILE* fp)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
return Nu_ReadOneC(pArchive, fp, &dummyCrc); return Nu_ReadOneC(pArchive, fp, &dummyCrc);
} }
/* /*
* Write one byte, optionally computing a CRC. * Write one byte, optionally computing a CRC.
*/ */
void void Nu_WriteOneC(NuArchive* pArchive, FILE* fp, uint8_t val, uint16_t* pCrc)
Nu_WriteOneC(NuArchive* pArchive, FILE* fp, uchar val, ushort* pCrc)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
putc(val, fp); putc(val, fp);
} }
void void Nu_WriteOne(NuArchive* pArchive, FILE* fp, uint8_t val)
Nu_WriteOne(NuArchive* pArchive, FILE* fp, uchar val)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
Nu_WriteOneC(pArchive, fp, val, &dummyCrc); Nu_WriteOneC(pArchive, fp, val, &dummyCrc);
} }
@ -72,27 +68,25 @@ Nu_WriteOne(NuArchive* pArchive, FILE* fp, uchar val)
/* /*
* Read two little-endian bytes, optionally computing a CRC. * Read two little-endian bytes, optionally computing a CRC.
*/ */
ushort uint16_t Nu_ReadTwoC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc)
Nu_ReadTwoC(NuArchive* pArchive, FILE* fp, ushort* pCrc)
{ {
int ic1, ic2; int ic1, ic2;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
ic1 = getc(fp); ic1 = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic1, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic1, *pCrc);
ic2 = getc(fp); ic2 = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic2, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic2, *pCrc);
return ic1 | ic2 << 8; return ic1 | ic2 << 8;
} }
ushort uint16_t Nu_ReadTwo(NuArchive* pArchive, FILE* fp)
Nu_ReadTwo(NuArchive* pArchive, FILE* fp)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
return Nu_ReadTwoC(pArchive, fp, &dummyCrc); return Nu_ReadTwoC(pArchive, fp, &dummyCrc);
} }
@ -100,28 +94,26 @@ Nu_ReadTwo(NuArchive* pArchive, FILE* fp)
/* /*
* Write two little-endian bytes, optionally computing a CRC. * Write two little-endian bytes, optionally computing a CRC.
*/ */
void void Nu_WriteTwoC(NuArchive* pArchive, FILE* fp, uint16_t val, uint16_t* pCrc)
Nu_WriteTwoC(NuArchive* pArchive, FILE* fp, ushort val, ushort* pCrc)
{ {
int ic1, ic2; int ic1, ic2;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
ic1 = val & 0xff; ic1 = val & 0xff;
*pCrc = Nu_UpdateCRC16((uchar)ic1, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic1, *pCrc);
ic2 = val >> 8; ic2 = val >> 8;
*pCrc = Nu_UpdateCRC16((uchar)ic2, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic2, *pCrc);
putc(ic1, fp); putc(ic1, fp);
putc(ic2, fp); putc(ic2, fp);
} }
void void Nu_WriteTwo(NuArchive* pArchive, FILE* fp, uint16_t val)
Nu_WriteTwo(NuArchive* pArchive, FILE* fp, ushort val)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
Nu_WriteTwoC(pArchive, fp, val, &dummyCrc); Nu_WriteTwoC(pArchive, fp, val, &dummyCrc);
} }
@ -129,31 +121,29 @@ Nu_WriteTwo(NuArchive* pArchive, FILE* fp, ushort val)
/* /*
* Read four little-endian bytes, optionally computing a CRC. * Read four little-endian bytes, optionally computing a CRC.
*/ */
ulong uint32_t Nu_ReadFourC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc)
Nu_ReadFourC(NuArchive* pArchive, FILE* fp, ushort* pCrc)
{ {
int ic1, ic2, ic3, ic4; int ic1, ic2, ic3, ic4;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
ic1 = getc(fp); ic1 = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic1, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic1, *pCrc);
ic2 = getc(fp); ic2 = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic2, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic2, *pCrc);
ic3 = getc(fp); ic3 = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic3, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic3, *pCrc);
ic4 = getc(fp); ic4 = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic4, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic4, *pCrc);
return ic1 | ic2 << 8 | (ulong)ic3 << 16 | (ulong)ic4 << 24; return ic1 | ic2 << 8 | (uint32_t)ic3 << 16 | (uint32_t)ic4 << 24;
} }
ulong uint32_t Nu_ReadFour(NuArchive* pArchive, FILE* fp)
Nu_ReadFour(NuArchive* pArchive, FILE* fp)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
return Nu_ReadFourC(pArchive, fp, &dummyCrc); return Nu_ReadFourC(pArchive, fp, &dummyCrc);
} }
@ -161,23 +151,22 @@ Nu_ReadFour(NuArchive* pArchive, FILE* fp)
/* /*
* Write four little-endian bytes, optionally computing a CRC. * Write four little-endian bytes, optionally computing a CRC.
*/ */
void void Nu_WriteFourC(NuArchive* pArchive, FILE* fp, uint32_t val, uint16_t* pCrc)
Nu_WriteFourC(NuArchive* pArchive, FILE* fp, ulong val, ushort* pCrc)
{ {
int ic1, ic2, ic3, ic4; int ic1, ic2, ic3, ic4;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
ic1 = val & 0xff; ic1 = val & 0xff;
*pCrc = Nu_UpdateCRC16((uchar)ic1, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic1, *pCrc);
ic2 = (val >> 8) & 0xff; ic2 = (val >> 8) & 0xff;
*pCrc = Nu_UpdateCRC16((uchar)ic2, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic2, *pCrc);
ic3 = (val >> 16) & 0xff; ic3 = (val >> 16) & 0xff;
*pCrc = Nu_UpdateCRC16((uchar)ic3, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic3, *pCrc);
ic4 = val >> 24; ic4 = val >> 24;
*pCrc = Nu_UpdateCRC16((uchar)ic4, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic4, *pCrc);
putc(ic1, fp); putc(ic1, fp);
putc(ic2, fp); putc(ic2, fp);
@ -185,10 +174,9 @@ Nu_WriteFourC(NuArchive* pArchive, FILE* fp, ulong val, ushort* pCrc)
putc(ic4, fp); putc(ic4, fp);
} }
void void Nu_WriteFour(NuArchive* pArchive, FILE* fp, uint32_t val)
Nu_WriteFour(NuArchive* pArchive, FILE* fp, ulong val)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
Nu_WriteFourC(pArchive, fp, val, &dummyCrc); Nu_WriteFourC(pArchive, fp, val, &dummyCrc);
} }
@ -200,48 +188,46 @@ Nu_WriteFour(NuArchive* pArchive, FILE* fp, ulong val)
* and GS/ShrinkIt. It's easy enough to deal with, and I figure the less * and GS/ShrinkIt. It's easy enough to deal with, and I figure the less
* messing-with, the better. * messing-with, the better.
*/ */
NuDateTime NuDateTime Nu_ReadDateTimeC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc)
Nu_ReadDateTimeC(NuArchive* pArchive, FILE* fp, ushort* pCrc)
{ {
NuDateTime temp; NuDateTime temp;
int ic; int ic;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.second = ic; temp.second = ic;
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.minute = ic; temp.minute = ic;
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.hour = ic; temp.hour = ic;
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.year = ic; temp.year = ic;
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.day = ic; temp.day = ic;
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.month = ic; temp.month = ic;
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.extra = ic; temp.extra = ic;
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
temp.weekDay = ic; temp.weekDay = ic;
return temp; return temp;
} }
NuDateTime NuDateTime Nu_ReadDateTime(NuArchive* pArchive, FILE* fp, uint16_t* pCrc)
Nu_ReadDateTime(NuArchive* pArchive, FILE* fp, ushort* pCrc)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
return Nu_ReadDateTimeC(pArchive, fp, &dummyCrc); return Nu_ReadDateTimeC(pArchive, fp, &dummyCrc);
} }
@ -249,46 +235,44 @@ Nu_ReadDateTime(NuArchive* pArchive, FILE* fp, ushort* pCrc)
/* /*
* Write an 8-byte NuFX Date/Time structure. * Write an 8-byte NuFX Date/Time structure.
*/ */
void void Nu_WriteDateTimeC(NuArchive* pArchive, FILE* fp, NuDateTime dateTime,
Nu_WriteDateTimeC(NuArchive* pArchive, FILE* fp, NuDateTime dateTime, uint16_t* pCrc)
ushort* pCrc)
{ {
int ic; int ic;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
ic = dateTime.second; ic = dateTime.second;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
ic = dateTime.minute; ic = dateTime.minute;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
ic = dateTime.hour; ic = dateTime.hour;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
ic = dateTime.year; ic = dateTime.year;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
ic = dateTime.day; ic = dateTime.day;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
ic = dateTime.month; ic = dateTime.month;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
ic = dateTime.extra; ic = dateTime.extra;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
ic = dateTime.weekDay; ic = dateTime.weekDay;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
} }
void void Nu_WriteDateTime(NuArchive* pArchive, FILE* fp, NuDateTime dateTime)
Nu_WriteDateTime(NuArchive* pArchive, FILE* fp, NuDateTime dateTime)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
Nu_WriteDateTimeC(pArchive, fp, dateTime, &dummyCrc); Nu_WriteDateTimeC(pArchive, fp, dateTime, &dummyCrc);
} }
@ -296,30 +280,28 @@ Nu_WriteDateTime(NuArchive* pArchive, FILE* fp, NuDateTime dateTime)
/* /*
* Read N bytes from the stream, optionally computing a CRC. * Read N bytes from the stream, optionally computing a CRC.
*/ */
void void Nu_ReadBytesC(NuArchive* pArchive, FILE* fp, void* vbuffer, long count,
Nu_ReadBytesC(NuArchive* pArchive, FILE* fp, void* vbuffer, long count, uint16_t* pCrc)
ushort* pCrc)
{ {
uchar* buffer = vbuffer; uint8_t* buffer = vbuffer;
int ic; int ic;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
Assert(buffer != nil); Assert(buffer != NULL);
Assert(count > 0); Assert(count > 0);
while (count--) { while (count--) {
ic = getc(fp); ic = getc(fp);
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
*buffer++ = ic; *buffer++ = ic;
} }
} }
void void Nu_ReadBytes(NuArchive* pArchive, FILE* fp, void* vbuffer, long count)
Nu_ReadBytes(NuArchive* pArchive, FILE* fp, void* vbuffer, long count)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
Nu_ReadBytesC(pArchive, fp, vbuffer, count, &dummyCrc); Nu_ReadBytesC(pArchive, fp, vbuffer, count, &dummyCrc);
} }
@ -327,30 +309,29 @@ Nu_ReadBytes(NuArchive* pArchive, FILE* fp, void* vbuffer, long count)
/* /*
* Write N bytes to the stream, optionally computing a CRC. * Write N bytes to the stream, optionally computing a CRC.
*/ */
void void Nu_WriteBytesC(NuArchive* pArchive, FILE* fp, const void* vbuffer,
Nu_WriteBytesC(NuArchive* pArchive, FILE* fp, const void* vbuffer, long count, long count, uint16_t* pCrc)
ushort* pCrc)
{ {
const uchar* buffer = vbuffer; const uint8_t* buffer = vbuffer;
int ic; int ic;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
Assert(buffer != nil); Assert(buffer != NULL);
Assert(count > 0); Assert(count > 0);
while (count--) { while (count--) {
ic = *buffer++; ic = *buffer++;
*pCrc = Nu_UpdateCRC16((uchar)ic, *pCrc); *pCrc = Nu_UpdateCRC16((uint8_t)ic, *pCrc);
putc(ic, fp); putc(ic, fp);
} }
} }
void void Nu_WriteBytes(NuArchive* pArchive, FILE* fp, const void* vbuffer,
Nu_WriteBytes(NuArchive* pArchive, FILE* fp, const void* vbuffer, long count) long count)
{ {
ushort dummyCrc CLEAN_INIT; uint16_t dummyCrc CLEAN_INIT;
Nu_WriteBytesC(pArchive, fp, vbuffer, count, &dummyCrc); Nu_WriteBytesC(pArchive, fp, vbuffer, count, &dummyCrc);
} }
@ -365,8 +346,7 @@ Nu_WriteBytes(NuArchive* pArchive, FILE* fp, const void* vbuffer, long count)
* Determine whether the stream completed the last set of operations * Determine whether the stream completed the last set of operations
* successfully. * successfully.
*/ */
NuError NuError Nu_HeaderIOFailed(NuArchive* pArchive, FILE* fp)
Nu_HeaderIOFailed(NuArchive* pArchive, FILE* fp)
{ {
if (feof(fp) || ferror(fp)) if (feof(fp) || ferror(fp))
return kNuErrFile; return kNuErrFile;
@ -381,8 +361,7 @@ Nu_HeaderIOFailed(NuArchive* pArchive, FILE* fp)
* *
* The values for "ptrname" are the same as for fseek(). * The values for "ptrname" are the same as for fseek().
*/ */
NuError NuError Nu_SeekArchive(NuArchive* pArchive, FILE* fp, long offset, int ptrname)
Nu_SeekArchive(NuArchive* pArchive, FILE* fp, long offset, int ptrname)
{ {
if (Nu_IsStreaming(pArchive)) { if (Nu_IsStreaming(pArchive)) {
Assert(ptrname == SEEK_CUR); Assert(ptrname == SEEK_CUR);
@ -408,10 +387,9 @@ Nu_SeekArchive(NuArchive* pArchive, FILE* fp, long offset, int ptrname)
* *
* Note that rewind(3S) resets the error indication, but this doesn't. * Note that rewind(3S) resets the error indication, but this doesn't.
*/ */
NuError NuError Nu_RewindArchive(NuArchive* pArchive)
Nu_RewindArchive(NuArchive* pArchive)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(!Nu_IsStreaming(pArchive)); Assert(!Nu_IsStreaming(pArchive));
if (Nu_SeekArchive(pArchive, pArchive->archiveFp, if (Nu_SeekArchive(pArchive, pArchive->archiveFp,

View File

@ -25,13 +25,11 @@
/* /*
* Alloc and free functions provided to libbz2. * Alloc and free functions provided to libbz2.
*/ */
static void* static void* Nu_bzalloc(void* opaque, int items, int size)
Nu_bzalloc(void* opaque, int items, int size)
{ {
return Nu_Malloc(opaque, items * size); return Nu_Malloc(opaque, items * size);
} }
static void static void Nu_bzfree(void* opaque, void* address)
Nu_bzfree(void* opaque, void* address)
{ {
Nu_Free(opaque, address); Nu_Free(opaque, address);
} }
@ -46,21 +44,20 @@ Nu_bzfree(void* opaque, void* address)
/* /*
* Compress "srcLen" bytes from "pStraw" to "fp". * Compress "srcLen" bytes from "pStraw" to "fp".
*/ */
NuError NuError Nu_CompressBzip2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressBzip2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc)
ulong srcLen, ulong* pDstLen, ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
bz_stream bzstream; bz_stream bzstream;
int bzerr; int bzerr;
uchar* outbuf = nil; uint8_t* outbuf = NULL;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(srcLen > 0); Assert(srcLen > 0);
Assert(pDstLen != nil); Assert(pDstLen != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
if (err != kNuErrNone) if (err != kNuErrNone)
@ -76,7 +73,7 @@ Nu_CompressBzip2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
bzstream.bzalloc = Nu_bzalloc; bzstream.bzalloc = Nu_bzalloc;
bzstream.bzfree = Nu_bzfree; bzstream.bzfree = Nu_bzfree;
bzstream.opaque = pArchive; bzstream.opaque = pArchive;
bzstream.next_in = nil; bzstream.next_in = NULL;
bzstream.avail_in = 0; bzstream.avail_in = 0;
bzstream.next_out = outbuf; bzstream.next_out = outbuf;
bzstream.avail_out = kNuGenCompBufSize; bzstream.avail_out = kNuGenCompBufSize;
@ -98,7 +95,7 @@ Nu_CompressBzip2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
* Loop while we have data. * Loop while we have data.
*/ */
do { do {
ulong getSize; uint32_t getSize;
int action; int action;
/* should be able to read a full buffer every time */ /* should be able to read a full buffer every time */
@ -139,8 +136,8 @@ Nu_CompressBzip2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
(bzerr == BZ_STREAM_END && bzstream.avail_out != kNuGenCompBufSize)) (bzerr == BZ_STREAM_END && bzstream.avail_out != kNuGenCompBufSize))
{ {
DBUG(("+++ writing %d bytes\n", DBUG(("+++ writing %d bytes\n",
(uchar*)bzstream.next_out - outbuf)); (uint8_t*)bzstream.next_out - outbuf));
err = Nu_FWrite(fp, outbuf, (uchar*)bzstream.next_out - outbuf); err = Nu_FWrite(fp, outbuf, (uint8_t*)bzstream.next_out - outbuf);
if (err != kNuErrNone) { if (err != kNuErrNone) {
Nu_ReportError(NU_BLOB, err, "fwrite failed in bzip2"); Nu_ReportError(NU_BLOB, err, "fwrite failed in bzip2");
goto bz_bail; goto bz_bail;
@ -158,8 +155,8 @@ bz_bail:
BZ2_bzCompressEnd(&bzstream); /* free up any allocated structures */ BZ2_bzCompressEnd(&bzstream); /* free up any allocated structures */
bail: bail:
if (outbuf != nil) if (outbuf != NULL)
free(outbuf); Nu_Free(NULL, outbuf);
return err; return err;
} }
@ -173,20 +170,19 @@ bail:
/* /*
* Expand from "infp" to "pFunnel". * Expand from "infp" to "pFunnel".
*/ */
NuError NuError Nu_ExpandBzip2(NuArchive* pArchive, const NuRecord* pRecord,
Nu_ExpandBzip2(NuArchive* pArchive, const NuRecord* pRecord, const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc)
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
bz_stream bzstream; bz_stream bzstream;
int bzerr; int bzerr;
ulong compRemaining; uint32_t compRemaining;
uchar* outbuf; uint8_t* outbuf;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(infp != nil); Assert(infp != NULL);
Assert(pFunnel != nil); Assert(pFunnel != NULL);
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
if (err != kNuErrNone) if (err != kNuErrNone)
@ -204,7 +200,7 @@ Nu_ExpandBzip2(NuArchive* pArchive, const NuRecord* pRecord,
bzstream.bzalloc = Nu_bzalloc; bzstream.bzalloc = Nu_bzalloc;
bzstream.bzfree = Nu_bzfree; bzstream.bzfree = Nu_bzfree;
bzstream.opaque = pArchive; bzstream.opaque = pArchive;
bzstream.next_in = nil; bzstream.next_in = NULL;
bzstream.avail_in = 0; bzstream.avail_in = 0;
bzstream.next_out = outbuf; bzstream.next_out = outbuf;
bzstream.avail_out = kNuGenCompBufSize; bzstream.avail_out = kNuGenCompBufSize;
@ -226,7 +222,7 @@ Nu_ExpandBzip2(NuArchive* pArchive, const NuRecord* pRecord,
* Loop while we have data. * Loop while we have data.
*/ */
do { do {
ulong getSize; uint32_t getSize;
/* read as much as we can */ /* read as much as we can */
if (bzstream.avail_in == 0) { if (bzstream.avail_in == 0) {
@ -258,17 +254,18 @@ Nu_ExpandBzip2(NuArchive* pArchive, const NuRecord* pRecord,
/* write every time there's anything (buffer will usually be full) */ /* write every time there's anything (buffer will usually be full) */
if (bzstream.avail_out != kNuGenCompBufSize) { if (bzstream.avail_out != kNuGenCompBufSize) {
DBUG(("+++ writing %d bytes\n",(uchar*)bzstream.next_out - outbuf)); DBUG(("+++ writing %d bytes\n",
(uint8_t*) bzstream.next_out - outbuf));
err = Nu_FunnelWrite(pArchive, pFunnel, outbuf, err = Nu_FunnelWrite(pArchive, pFunnel, outbuf,
(uchar*)bzstream.next_out - outbuf); (uint8_t*)bzstream.next_out - outbuf);
if (err != kNuErrNone) { if (err != kNuErrNone) {
Nu_ReportError(NU_BLOB, err, "write failed in bzip2"); Nu_ReportError(NU_BLOB, err, "write failed in bzip2");
goto bz_bail; goto bz_bail;
} }
if (pCrc != nil) if (pCrc != NULL)
*pCrc = Nu_CalcCRC16(*pCrc, outbuf, *pCrc = Nu_CalcCRC16(*pCrc, outbuf,
(uchar*) bzstream.next_out - outbuf); (uint8_t*) bzstream.next_out - outbuf);
bzstream.next_out = outbuf; bzstream.next_out = outbuf;
bzstream.avail_out = kNuGenCompBufSize; bzstream.avail_out = kNuGenCompBufSize;
@ -291,8 +288,8 @@ bz_bail:
BZ2_bzDecompressEnd(&bzstream); /* free up any allocated structures */ BZ2_bzDecompressEnd(&bzstream); /* free up any allocated structures */
bail: bail:
if (outbuf != nil) if (outbuf != NULL)
free(outbuf); Nu_Free(NULL, outbuf);
return err; return err;
} }

View File

@ -1,3 +1,14 @@
2015/01/03 fadden
- Mac OS X: replace Carbon FinderInfo calls with BSD xattr.
- Mac OS X: fix resource fork naming.
- Mac OS X: disable use of native resource forks.
2015/01/02 fadden
- Distinguish Unicode and Mac OS Roman strings.
2014/12/22 fadden
- Source code cleanup.
2014/10/30 ***** v2.2.2 shipped ***** 2014/10/30 ***** v2.2.2 shipped *****
2014/10/28 fadden 2014/10/28 fadden

553
nufxlib/Charset.c Normal file
View File

@ -0,0 +1,553 @@
/*
* NuFX archive manipulation library
* Copyright (C) 2014 by Andy McFadden, All Rights Reserved.
* This is free software; you can redistribute it and/or modify it under the
* terms of the BSD License, see the file COPYING-LIB.
*
* Miscellaneous NufxLib utility functions.
*/
#include "NufxLibPriv.h"
/*
* Convert Mac OS Roman to Unicode. Mapping comes from:
*
* http://www.unicode.org/Public/MAPPINGS/VENDORS/APPLE/ROMAN.TXT
*
* We use the "Control Pictures" block for the control characters
* (0x00-0x1f, 0x7f --> 0x2400-0x241f, 0x2421). This is a bit nicer
* than embedding control characters in filenames.
*/
static const uint16_t gMORToUnicode[256] = {
/*0x00*/ 0x2400, // [control] NULL
/*0x01*/ 0x2401, // [control] START OF HEADING
/*0x02*/ 0x2402, // [control] START OF TEXT
/*0x03*/ 0x2403, // [control] END OF TEXT
/*0x04*/ 0x2404, // [control] END OF TRANSMISSION
/*0x05*/ 0x2405, // [control] ENQUIRY
/*0x06*/ 0x2406, // [control] ACKNOWLEDGE
/*0x07*/ 0x2407, // [control] BELL
/*0x08*/ 0x2408, // [control] BACKSPACE
/*0x09*/ 0x2409, // [control] HORIZONTAL TABULATION
/*0x0a*/ 0x240a, // [control] LINE FEED
/*0x0b*/ 0x240b, // [control] VERTICAL TABULATION
/*0x0c*/ 0x240c, // [control] FORM FEED
/*0x0d*/ 0x240d, // [control] CARRIAGE RETURN
/*0x0e*/ 0x240e, // [control] SHIFT OUT
/*0x0f*/ 0x240f, // [control] SHIFT IN
/*0x10*/ 0x2410, // [control] DATA LINK ESCAPE
/*0x11*/ 0x2411, // [control] DEVICE CONTROL ONE
/*0x12*/ 0x2412, // [control] DEVICE CONTROL TWO
/*0x13*/ 0x2413, // [control] DEVICE CONTROL THREE
/*0x14*/ 0x2414, // [control] DEVICE CONTROL FOUR
/*0x15*/ 0x2415, // [control] NEGATIVE ACKNOWLEDGE
/*0x16*/ 0x2416, // [control] SYNCHRONOUS IDLE
/*0x17*/ 0x2417, // [control] END OF TRANSMISSION BLOCK
/*0x18*/ 0x2418, // [control] CANCEL
/*0x19*/ 0x2419, // [control] END OF MEDIUM
/*0x1a*/ 0x241a, // [control] SUBSTITUTE
/*0x1b*/ 0x241b, // [control] ESCAPE
/*0x1c*/ 0x241c, // [control] FILE SEPARATOR
/*0x1d*/ 0x241d, // [control] GROUP SEPARATOR
/*0x1e*/ 0x241e, // [control] RECORD SEPARATOR
/*0x1f*/ 0x241f, // [control] UNIT SEPARATOR
/*0x20*/ 0x0020, // SPACE
/*0x21*/ 0x0021, // EXCLAMATION MARK
/*0x22*/ 0x0022, // QUOTATION MARK
/*0x23*/ 0x0023, // NUMBER SIGN
/*0x24*/ 0x0024, // DOLLAR SIGN
/*0x25*/ 0x0025, // PERCENT SIGN
/*0x26*/ 0x0026, // AMPERSAND
/*0x27*/ 0x0027, // APOSTROPHE
/*0x28*/ 0x0028, // LEFT PARENTHESIS
/*0x29*/ 0x0029, // RIGHT PARENTHESIS
/*0x2A*/ 0x002A, // ASTERISK
/*0x2B*/ 0x002B, // PLUS SIGN
/*0x2C*/ 0x002C, // COMMA
/*0x2D*/ 0x002D, // HYPHEN-MINUS
/*0x2E*/ 0x002E, // FULL STOP
/*0x2F*/ 0x002F, // SOLIDUS
/*0x30*/ 0x0030, // DIGIT ZERO
/*0x31*/ 0x0031, // DIGIT ONE
/*0x32*/ 0x0032, // DIGIT TWO
/*0x33*/ 0x0033, // DIGIT THREE
/*0x34*/ 0x0034, // DIGIT FOUR
/*0x35*/ 0x0035, // DIGIT FIVE
/*0x36*/ 0x0036, // DIGIT SIX
/*0x37*/ 0x0037, // DIGIT SEVEN
/*0x38*/ 0x0038, // DIGIT EIGHT
/*0x39*/ 0x0039, // DIGIT NINE
/*0x3A*/ 0x003A, // COLON
/*0x3B*/ 0x003B, // SEMICOLON
/*0x3C*/ 0x003C, // LESS-THAN SIGN
/*0x3D*/ 0x003D, // EQUALS SIGN
/*0x3E*/ 0x003E, // GREATER-THAN SIGN
/*0x3F*/ 0x003F, // QUESTION MARK
/*0x40*/ 0x0040, // COMMERCIAL AT
/*0x41*/ 0x0041, // LATIN CAPITAL LETTER A
/*0x42*/ 0x0042, // LATIN CAPITAL LETTER B
/*0x43*/ 0x0043, // LATIN CAPITAL LETTER C
/*0x44*/ 0x0044, // LATIN CAPITAL LETTER D
/*0x45*/ 0x0045, // LATIN CAPITAL LETTER E
/*0x46*/ 0x0046, // LATIN CAPITAL LETTER F
/*0x47*/ 0x0047, // LATIN CAPITAL LETTER G
/*0x48*/ 0x0048, // LATIN CAPITAL LETTER H
/*0x49*/ 0x0049, // LATIN CAPITAL LETTER I
/*0x4A*/ 0x004A, // LATIN CAPITAL LETTER J
/*0x4B*/ 0x004B, // LATIN CAPITAL LETTER K
/*0x4C*/ 0x004C, // LATIN CAPITAL LETTER L
/*0x4D*/ 0x004D, // LATIN CAPITAL LETTER M
/*0x4E*/ 0x004E, // LATIN CAPITAL LETTER N
/*0x4F*/ 0x004F, // LATIN CAPITAL LETTER O
/*0x50*/ 0x0050, // LATIN CAPITAL LETTER P
/*0x51*/ 0x0051, // LATIN CAPITAL LETTER Q
/*0x52*/ 0x0052, // LATIN CAPITAL LETTER R
/*0x53*/ 0x0053, // LATIN CAPITAL LETTER S
/*0x54*/ 0x0054, // LATIN CAPITAL LETTER T
/*0x55*/ 0x0055, // LATIN CAPITAL LETTER U
/*0x56*/ 0x0056, // LATIN CAPITAL LETTER V
/*0x57*/ 0x0057, // LATIN CAPITAL LETTER W
/*0x58*/ 0x0058, // LATIN CAPITAL LETTER X
/*0x59*/ 0x0059, // LATIN CAPITAL LETTER Y
/*0x5A*/ 0x005A, // LATIN CAPITAL LETTER Z
/*0x5B*/ 0x005B, // LEFT SQUARE BRACKET
/*0x5C*/ 0x005C, // REVERSE SOLIDUS
/*0x5D*/ 0x005D, // RIGHT SQUARE BRACKET
/*0x5E*/ 0x005E, // CIRCUMFLEX ACCENT
/*0x5F*/ 0x005F, // LOW LINE
/*0x60*/ 0x0060, // GRAVE ACCENT
/*0x61*/ 0x0061, // LATIN SMALL LETTER A
/*0x62*/ 0x0062, // LATIN SMALL LETTER B
/*0x63*/ 0x0063, // LATIN SMALL LETTER C
/*0x64*/ 0x0064, // LATIN SMALL LETTER D
/*0x65*/ 0x0065, // LATIN SMALL LETTER E
/*0x66*/ 0x0066, // LATIN SMALL LETTER F
/*0x67*/ 0x0067, // LATIN SMALL LETTER G
/*0x68*/ 0x0068, // LATIN SMALL LETTER H
/*0x69*/ 0x0069, // LATIN SMALL LETTER I
/*0x6A*/ 0x006A, // LATIN SMALL LETTER J
/*0x6B*/ 0x006B, // LATIN SMALL LETTER K
/*0x6C*/ 0x006C, // LATIN SMALL LETTER L
/*0x6D*/ 0x006D, // LATIN SMALL LETTER M
/*0x6E*/ 0x006E, // LATIN SMALL LETTER N
/*0x6F*/ 0x006F, // LATIN SMALL LETTER O
/*0x70*/ 0x0070, // LATIN SMALL LETTER P
/*0x71*/ 0x0071, // LATIN SMALL LETTER Q
/*0x72*/ 0x0072, // LATIN SMALL LETTER R
/*0x73*/ 0x0073, // LATIN SMALL LETTER S
/*0x74*/ 0x0074, // LATIN SMALL LETTER T
/*0x75*/ 0x0075, // LATIN SMALL LETTER U
/*0x76*/ 0x0076, // LATIN SMALL LETTER V
/*0x77*/ 0x0077, // LATIN SMALL LETTER W
/*0x78*/ 0x0078, // LATIN SMALL LETTER X
/*0x79*/ 0x0079, // LATIN SMALL LETTER Y
/*0x7A*/ 0x007A, // LATIN SMALL LETTER Z
/*0x7B*/ 0x007B, // LEFT CURLY BRACKET
/*0x7C*/ 0x007C, // VERTICAL LINE
/*0x7D*/ 0x007D, // RIGHT CURLY BRACKET
/*0x7E*/ 0x007E, // TILDE
/*0x7f*/ 0x2421, // [control] DELETE
/*0x80*/ 0x00C4, // LATIN CAPITAL LETTER A WITH DIAERESIS
/*0x81*/ 0x00C5, // LATIN CAPITAL LETTER A WITH RING ABOVE
/*0x82*/ 0x00C7, // LATIN CAPITAL LETTER C WITH CEDILLA
/*0x83*/ 0x00C9, // LATIN CAPITAL LETTER E WITH ACUTE
/*0x84*/ 0x00D1, // LATIN CAPITAL LETTER N WITH TILDE
/*0x85*/ 0x00D6, // LATIN CAPITAL LETTER O WITH DIAERESIS
/*0x86*/ 0x00DC, // LATIN CAPITAL LETTER U WITH DIAERESIS
/*0x87*/ 0x00E1, // LATIN SMALL LETTER A WITH ACUTE
/*0x88*/ 0x00E0, // LATIN SMALL LETTER A WITH GRAVE
/*0x89*/ 0x00E2, // LATIN SMALL LETTER A WITH CIRCUMFLEX
/*0x8A*/ 0x00E4, // LATIN SMALL LETTER A WITH DIAERESIS
/*0x8B*/ 0x00E3, // LATIN SMALL LETTER A WITH TILDE
/*0x8C*/ 0x00E5, // LATIN SMALL LETTER A WITH RING ABOVE
/*0x8D*/ 0x00E7, // LATIN SMALL LETTER C WITH CEDILLA
/*0x8E*/ 0x00E9, // LATIN SMALL LETTER E WITH ACUTE
/*0x8F*/ 0x00E8, // LATIN SMALL LETTER E WITH GRAVE
/*0x90*/ 0x00EA, // LATIN SMALL LETTER E WITH CIRCUMFLEX
/*0x91*/ 0x00EB, // LATIN SMALL LETTER E WITH DIAERESIS
/*0x92*/ 0x00ED, // LATIN SMALL LETTER I WITH ACUTE
/*0x93*/ 0x00EC, // LATIN SMALL LETTER I WITH GRAVE
/*0x94*/ 0x00EE, // LATIN SMALL LETTER I WITH CIRCUMFLEX
/*0x95*/ 0x00EF, // LATIN SMALL LETTER I WITH DIAERESIS
/*0x96*/ 0x00F1, // LATIN SMALL LETTER N WITH TILDE
/*0x97*/ 0x00F3, // LATIN SMALL LETTER O WITH ACUTE
/*0x98*/ 0x00F2, // LATIN SMALL LETTER O WITH GRAVE
/*0x99*/ 0x00F4, // LATIN SMALL LETTER O WITH CIRCUMFLEX
/*0x9A*/ 0x00F6, // LATIN SMALL LETTER O WITH DIAERESIS
/*0x9B*/ 0x00F5, // LATIN SMALL LETTER O WITH TILDE
/*0x9C*/ 0x00FA, // LATIN SMALL LETTER U WITH ACUTE
/*0x9D*/ 0x00F9, // LATIN SMALL LETTER U WITH GRAVE
/*0x9E*/ 0x00FB, // LATIN SMALL LETTER U WITH CIRCUMFLEX
/*0x9F*/ 0x00FC, // LATIN SMALL LETTER U WITH DIAERESIS
/*0xA0*/ 0x2020, // DAGGER
/*0xA1*/ 0x00B0, // DEGREE SIGN
/*0xA2*/ 0x00A2, // CENT SIGN
/*0xA3*/ 0x00A3, // POUND SIGN
/*0xA4*/ 0x00A7, // SECTION SIGN
/*0xA5*/ 0x2022, // BULLET
/*0xA6*/ 0x00B6, // PILCROW SIGN
/*0xA7*/ 0x00DF, // LATIN SMALL LETTER SHARP S
/*0xA8*/ 0x00AE, // REGISTERED SIGN
/*0xA9*/ 0x00A9, // COPYRIGHT SIGN
/*0xAA*/ 0x2122, // TRADE MARK SIGN
/*0xAB*/ 0x00B4, // ACUTE ACCENT
/*0xAC*/ 0x00A8, // DIAERESIS
/*0xAD*/ 0x2260, // NOT EQUAL TO
/*0xAE*/ 0x00C6, // LATIN CAPITAL LETTER AE
/*0xAF*/ 0x00D8, // LATIN CAPITAL LETTER O WITH STROKE
/*0xB0*/ 0x221E, // INFINITY
/*0xB1*/ 0x00B1, // PLUS-MINUS SIGN
/*0xB2*/ 0x2264, // LESS-THAN OR EQUAL TO
/*0xB3*/ 0x2265, // GREATER-THAN OR EQUAL TO
/*0xB4*/ 0x00A5, // YEN SIGN
/*0xB5*/ 0x00B5, // MICRO SIGN
/*0xB6*/ 0x2202, // PARTIAL DIFFERENTIAL
/*0xB7*/ 0x2211, // N-ARY SUMMATION
/*0xB8*/ 0x220F, // N-ARY PRODUCT
/*0xB9*/ 0x03C0, // GREEK SMALL LETTER PI
/*0xBA*/ 0x222B, // INTEGRAL
/*0xBB*/ 0x00AA, // FEMININE ORDINAL INDICATOR
/*0xBC*/ 0x00BA, // MASCULINE ORDINAL INDICATOR
/*0xBD*/ 0x03A9, // GREEK CAPITAL LETTER OMEGA
/*0xBE*/ 0x00E6, // LATIN SMALL LETTER AE
/*0xBF*/ 0x00F8, // LATIN SMALL LETTER O WITH STROKE
/*0xC0*/ 0x00BF, // INVERTED QUESTION MARK
/*0xC1*/ 0x00A1, // INVERTED EXCLAMATION MARK
/*0xC2*/ 0x00AC, // NOT SIGN
/*0xC3*/ 0x221A, // SQUARE ROOT
/*0xC4*/ 0x0192, // LATIN SMALL LETTER F WITH HOOK
/*0xC5*/ 0x2248, // ALMOST EQUAL TO
/*0xC6*/ 0x2206, // INCREMENT
/*0xC7*/ 0x00AB, // LEFT-POINTING DOUBLE ANGLE QUOTATION MARK
/*0xC8*/ 0x00BB, // RIGHT-POINTING DOUBLE ANGLE QUOTATION MARK
/*0xC9*/ 0x2026, // HORIZONTAL ELLIPSIS
/*0xCA*/ 0x00A0, // NO-BREAK SPACE
/*0xCB*/ 0x00C0, // LATIN CAPITAL LETTER A WITH GRAVE
/*0xCC*/ 0x00C3, // LATIN CAPITAL LETTER A WITH TILDE
/*0xCD*/ 0x00D5, // LATIN CAPITAL LETTER O WITH TILDE
/*0xCE*/ 0x0152, // LATIN CAPITAL LIGATURE OE
/*0xCF*/ 0x0153, // LATIN SMALL LIGATURE OE
/*0xD0*/ 0x2013, // EN DASH
/*0xD1*/ 0x2014, // EM DASH
/*0xD2*/ 0x201C, // LEFT DOUBLE QUOTATION MARK
/*0xD3*/ 0x201D, // RIGHT DOUBLE QUOTATION MARK
/*0xD4*/ 0x2018, // LEFT SINGLE QUOTATION MARK
/*0xD5*/ 0x2019, // RIGHT SINGLE QUOTATION MARK
/*0xD6*/ 0x00F7, // DIVISION SIGN
/*0xD7*/ 0x25CA, // LOZENGE
/*0xD8*/ 0x00FF, // LATIN SMALL LETTER Y WITH DIAERESIS
/*0xD9*/ 0x0178, // LATIN CAPITAL LETTER Y WITH DIAERESIS
/*0xDA*/ 0x2044, // FRACTION SLASH
/*0xDB*/ 0x00A4, // CURRENCY SIGN (was EURO SIGN)
/*0xDC*/ 0x2039, // SINGLE LEFT-POINTING ANGLE QUOTATION MARK
/*0xDD*/ 0x203A, // SINGLE RIGHT-POINTING ANGLE QUOTATION MARK
/*0xDE*/ 0xFB01, // LATIN SMALL LIGATURE FI
/*0xDF*/ 0xFB02, // LATIN SMALL LIGATURE FL
/*0xE0*/ 0x2021, // DOUBLE DAGGER
/*0xE1*/ 0x00B7, // MIDDLE DOT
/*0xE2*/ 0x201A, // SINGLE LOW-9 QUOTATION MARK
/*0xE3*/ 0x201E, // DOUBLE LOW-9 QUOTATION MARK
/*0xE4*/ 0x2030, // PER MILLE SIGN
/*0xE5*/ 0x00C2, // LATIN CAPITAL LETTER A WITH CIRCUMFLEX
/*0xE6*/ 0x00CA, // LATIN CAPITAL LETTER E WITH CIRCUMFLEX
/*0xE7*/ 0x00C1, // LATIN CAPITAL LETTER A WITH ACUTE
/*0xE8*/ 0x00CB, // LATIN CAPITAL LETTER E WITH DIAERESIS
/*0xE9*/ 0x00C8, // LATIN CAPITAL LETTER E WITH GRAVE
/*0xEA*/ 0x00CD, // LATIN CAPITAL LETTER I WITH ACUTE
/*0xEB*/ 0x00CE, // LATIN CAPITAL LETTER I WITH CIRCUMFLEX
/*0xEC*/ 0x00CF, // LATIN CAPITAL LETTER I WITH DIAERESIS
/*0xED*/ 0x00CC, // LATIN CAPITAL LETTER I WITH GRAVE
/*0xEE*/ 0x00D3, // LATIN CAPITAL LETTER O WITH ACUTE
/*0xEF*/ 0x00D4, // LATIN CAPITAL LETTER O WITH CIRCUMFLEX
/*0xF0*/ 0xF8FF, // Apple logo
/*0xF1*/ 0x00D2, // LATIN CAPITAL LETTER O WITH GRAVE
/*0xF2*/ 0x00DA, // LATIN CAPITAL LETTER U WITH ACUTE
/*0xF3*/ 0x00DB, // LATIN CAPITAL LETTER U WITH CIRCUMFLEX
/*0xF4*/ 0x00D9, // LATIN CAPITAL LETTER U WITH GRAVE
/*0xF5*/ 0x0131, // LATIN SMALL LETTER DOTLESS I
/*0xF6*/ 0x02C6, // MODIFIER LETTER CIRCUMFLEX ACCENT
/*0xF7*/ 0x02DC, // SMALL TILDE
/*0xF8*/ 0x00AF, // MACRON
/*0xF9*/ 0x02D8, // BREVE
/*0xFA*/ 0x02D9, // DOT ABOVE
/*0xFB*/ 0x02DA, // RING ABOVE
/*0xFC*/ 0x00B8, // CEDILLA
/*0xFD*/ 0x02DD, // DOUBLE ACUTE ACCENT
/*0xFE*/ 0x02DB, // OGONEK
/*0xFF*/ 0x02C7 // CARON
};
/*
* Static table, populated on first use. Provides the inverse map.
*
* An entry with 0x00 indicates no conversion. That's incorrect for
* the entry for '\0', but since we're operating on null-terminated
* strings that's never valid anyway. (It's possible for a filename
* to contain 0x2400, but that would translate to 0x00, which we don't
* allow; so it makes more sense to treat it as illegal.)
*/
static uint8_t gUnicodeToMOR[65536] = { 0xff /*indicates not initialized*/ };
static void Nu_GenerateUnicodeToMOR(void)
{
memset(gUnicodeToMOR, 0, sizeof(gUnicodeToMOR));
int i;
for (i = 0; i < 256; i++) {
int codePoint = gMORToUnicode[i];
Assert(codePoint >= 0 && codePoint < 65536);
gUnicodeToMOR[codePoint] = i;
}
}
/*
* Converts stringMOR to Unicode, storing the output in bufUNI until it's
* full. Null termination is guaranteed. If the buffer size is zero or
* bufUNI is NULL, no string data is returned.
*
* Returns the number of bytes required to represent stringMOR in Unicode.
*/
size_t Nu_ConvertMORToUNI(const char* stringMOR, UNICHAR* bufUNI,
size_t bufSize)
{
Assert(stringMOR != 0);
#ifdef _WIN32
/* place-holder if we're not using UTF-16 yet */
Assert(sizeof(UNICHAR) == 1);
size_t morLen = strlen(stringMOR) + 1;
if (bufUNI != NULL && bufSize != 0) {
size_t copyLen = morLen < bufSize ? morLen : bufSize;
memcpy(bufUNI, stringMOR, copyLen);
bufUNI[bufSize-1] = '\0';
}
return morLen;
#else
/*
* Convert Mac OS Roman to UTF-8. We only output full code points,
* so if only the first byte of a UTF-8 sequence will fit we just
* stop early.
*/
size_t uniLen = 0;
Boolean doOutput = (bufUNI != NULL);
while (*stringMOR != '\0') {
// ASCII values just "convert" to themselves in this table
uint16_t us = gMORToUnicode[(uint8_t)*stringMOR];
if (us < 0x80) {
// single byte, no conversion
if (uniLen+1 >= bufSize) {
doOutput = false;
}
if (doOutput) {
bufUNI[uniLen] = (char) us;
}
uniLen++;
} else if (us < 0x7ff) {
// two bytes
if (uniLen+2 >= bufSize) {
doOutput = false;
}
if (doOutput) {
bufUNI[uniLen] = (us >> 6) | 0xc0;
bufUNI[uniLen+1] = (us & 0x3f) | 0x80;
}
uniLen += 2;
} else {
// three bytes
if (uniLen+3 >= bufSize) {
doOutput = false;
}
if (doOutput) {
bufUNI[uniLen] = (us >> 12) | 0xe0;
bufUNI[uniLen+1] = ((us >> 6) & 0x3f) | 0x80;
bufUNI[uniLen+2] = (us & 0x3f) | 0x80;
}
uniLen += 3;
}
stringMOR++;
}
// null-terminate
if (doOutput && uniLen < bufSize) {
bufUNI[uniLen] = '\0';
}
uniLen++;
return uniLen;
#endif
}
/*
* Decode a single Unicode code point from a UTF-8 string. This will
* consume 1 to 4 bytes. If an error is detected, only one byte is
* consumed, and the code point value will be 0xDCnn (invalid).
*
* cf. http://en.wikipedia.org/wiki/UTF-8#Sample_code
*/
static uint32_t Nu_DecodeUTF8(const char** pStr)
{
const uint8_t* str = (const uint8_t*) *pStr;
uint32_t codePoint;
uint32_t uc1, uc2, uc3, uc4;
uc1 = *str++;
if (uc1 < 0x80) {
// single byte
codePoint = uc1;
} else if (uc1 < 0xc2) {
// illegal: continuation or overlong 2-byte sequence
goto fail;
} else if (uc1 < 0xe0) {
// 2-byte sequence
uc2 = *str++;
if ((uc2 & 0xc0) != 0x80) {
goto fail; // not a continuation
}
codePoint = (uc1 << 6) + uc2 - 0x3080;
} else if (uc1 < 0xf0) {
// 3-byte sequence */
uc2 = *str++;
if ((uc2 & 0xc0) != 0x80) {
goto fail; // not a continuation
}
if (uc1 == 0xe0 && uc2 < 0xa0) {
goto fail; // overlong
}
uc3 = *str++;
if ((uc3 & 0xc0) != 0x80) {
goto fail; // not a continuation
}
codePoint = (uc1 << 12) + (uc2 << 6) + uc3 - 0xE2080;
} else if (uc1 < 0xf5) {
uc2 = *str++;
if ((uc2 & 0xc0) != 0x80) {
goto fail; // not a continuation
}
if (uc1 == 0xf0 && uc2 < 0x90) {
goto fail; // overlong
}
if (uc1 == 0xf4 && uc2 >= 0x90) {
goto fail; // U+10FFFF
}
uc3 = *str++;
if ((uc3 & 0xc0) != 0x80) {
goto fail; // not a continuation
}
uc4 = *str++;
if ((uc4 & 0xc0) != 0x80) {
goto fail; // not a continuation
}
codePoint = (uc1 << 18) + (uc2 << 12) + (uc3 << 6) + uc4 - 0x3C82080;
} else {
// illegal: > U+10FFFF
goto fail;
}
*pStr = (const UNICHAR*) str;
return codePoint;
fail:
(*pStr)++; // advance one char only
return 0xdc00 | uc1;
}
/*
* Converts stringUNI to Mac OS Roman, storing the output in bufMOR
* until it's full. Null termination is guaranteed. If the buffer
* size is zero or bufMOR is NULL, no string data is returned.
*
* Returns the number of bytes required to represent stringUNI in MOR.
*/
size_t Nu_ConvertUNIToMOR(const UNICHAR* stringUNI, char* bufMOR,
size_t bufSize)
{
Assert(stringUNI != 0);
#ifdef _WIN32
/*
* Place-holder if we're not using UTF-16 yet. This doesn't pass
* tests that check for behavior with non-MOR Unicode values.
*/
Assert(sizeof(UNICHAR) == 1);
size_t uniLen = strlen(stringUNI) + 1;
if (bufMOR != NULL && bufSize != 0) {
size_t copyLen = uniLen < bufSize ? uniLen : bufSize;
memcpy(bufMOR, stringUNI, copyLen);
bufMOR[bufSize-1] = '\0';
}
return uniLen;
#else
/*
* Convert UTF-8 to Mac OS Roman. If the code point doesn't have
* a valid conversion (either because it's not in the table, or the
* UTF-8 code is damaged) we just insert an ASCII '?'.
*/
if (gUnicodeToMOR[0] == 0xff) {
Nu_GenerateUnicodeToMOR();
Assert(gUnicodeToMOR[0] != 0xff);
}
uint32_t codePoint;
size_t morLen = 0;
Boolean doOutput = (bufMOR != NULL);
while (*stringUNI != '\0') {
codePoint = Nu_DecodeUTF8(&stringUNI);
char mc;
if (codePoint < 0x80) {
mc = (char) codePoint;
} else if (codePoint < 0xffff) {
// UTF-8 errors come back as 0xDCnn, which has no mapping in table
mc = gUnicodeToMOR[codePoint];
if (mc == 0x00) {
mc = '?';
}
} else {
// non-BMP code point
mc = '?';
}
if (morLen+1 >= bufSize) {
doOutput = false;
}
if (doOutput) {
bufMOR[morLen] = mc;
}
morLen++;
}
// null-terminate
if (doOutput && morLen < bufSize) {
bufMOR[morLen] = '\0';
}
morLen++;
return morLen;
#endif
}
/*
* Utility function that wraps NuConvertMORToUTF8, allocating a new
* buffer to hold the converted string. The caller must free the result.
*
* Returns NULL if stringMOR is NULL or the conversion fails.
*/
UNICHAR* Nu_CopyMORToUNI(const char* stringMOR)
{
size_t uniLen;
UNICHAR* uniBuf;
if (stringMOR == NULL) {
return NULL;
}
uniLen = Nu_ConvertMORToUNI(stringMOR, NULL, 0);
if (uniLen == (size_t) -1) {
return NULL;
}
uniBuf = (UNICHAR*) Nu_Malloc(NULL, uniLen);
Nu_ConvertMORToUNI(stringMOR, uniBuf, uniLen);
return uniBuf;
}

View File

@ -15,17 +15,16 @@
/* /*
* "Compress" an uncompressed thread. * "Compress" an uncompressed thread.
*/ */
static NuError static NuError Nu_CompressUncompressed(NuArchive* pArchive, NuStraw* pStraw,
Nu_CompressUncompressed(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t *pCrc)
FILE* fp, ulong srcLen, ulong* pDstLen, ushort *pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
/*uchar* buffer = nil;*/ /*uint8_t* buffer = NULL;*/
ulong count, getsize; uint32_t count, getsize;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(srcLen > 0); Assert(srcLen > 0);
*pDstLen = srcLen; /* get this over with */ *pDstLen = srcLen; /* get this over with */
@ -33,7 +32,7 @@ Nu_CompressUncompressed(NuArchive* pArchive, NuStraw* pStraw,
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
BailError(err); BailError(err);
if (pCrc != nil) if (pCrc != NULL)
*pCrc = kNuInitialThreadCRC; *pCrc = kNuInitialThreadCRC;
count = srcLen; count = srcLen;
@ -42,7 +41,7 @@ Nu_CompressUncompressed(NuArchive* pArchive, NuStraw* pStraw,
err = Nu_StrawRead(pArchive, pStraw, pArchive->compBuf, getsize); err = Nu_StrawRead(pArchive, pStraw, pArchive->compBuf, getsize);
BailError(err); BailError(err);
if (pCrc != nil) if (pCrc != NULL)
*pCrc = Nu_CalcCRC16(*pCrc, pArchive->compBuf, getsize); *pCrc = Nu_CalcCRC16(*pCrc, pArchive->compBuf, getsize);
err = Nu_FWrite(fp, pArchive->compBuf, getsize); err = Nu_FWrite(fp, pArchive->compBuf, getsize);
BailError(err); BailError(err);
@ -87,24 +86,23 @@ bail:
* On exit, the output file will be positioned after the last byte of the * On exit, the output file will be positioned after the last byte of the
* output. (For a pre-sized buffer, this may not be the desired result.) * output. (For a pre-sized buffer, this may not be the desired result.)
*/ */
NuError NuError Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
NuThreadID threadID, NuThreadFormat sourceFormat, NuThreadID threadID, NuThreadFormat sourceFormat,
NuThreadFormat targetFormat, NuProgressData* pProgressData, FILE* dstFp, NuThreadFormat targetFormat, NuProgressData* pProgressData, FILE* dstFp,
NuThread* pThread) NuThread* pThread)
{ {
NuError err; NuError err;
long origOffset; long origOffset;
NuStraw* pStraw = nil; NuStraw* pStraw = NULL;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
ulong srcLen = 0, dstLen = 0; uint32_t srcLen = 0, dstLen = 0;
ushort threadCrc; uint16_t threadCrc;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pDataSource != nil); Assert(pDataSource != NULL);
/* okay if pProgressData is nil */ /* okay if pProgressData is NULL */
Assert(dstFp != nil); Assert(dstFp != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
/* remember file offset, so we can back up if compression fails */ /* remember file offset, so we can back up if compression fails */
err = Nu_FTell(dstFp, &origOffset); err = Nu_FTell(dstFp, &origOffset);
@ -116,7 +114,7 @@ Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
pThread->thThreadClass = NuThreadIDGetClass(threadID); pThread->thThreadClass = NuThreadIDGetClass(threadID);
pThread->thThreadKind = NuThreadIDGetKind(threadID); pThread->thThreadKind = NuThreadIDGetKind(threadID);
pThread->actualThreadEOF = (ulong)-1; pThread->actualThreadEOF = (uint32_t)-1;
/* nuThreadIdx and fileOffset should already be set */ /* nuThreadIdx and fileOffset should already be set */
/* /*
@ -168,7 +166,7 @@ Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
if (pArchive->valMimicSHK && srcLen < kNuSHKLZWThreshold) if (pArchive->valMimicSHK && srcLen < kNuSHKLZWThreshold)
targetFormat = kNuThreadFormatUncompressed; targetFormat = kNuThreadFormatUncompressed;
if (pProgressData != nil) { if (pProgressData != NULL) {
if (targetFormat != kNuThreadFormatUncompressed) if (targetFormat != kNuThreadFormatUncompressed)
Nu_StrawSetProgressState(pStraw, kNuProgressCompressing); Nu_StrawSetProgressState(pStraw, kNuProgressCompressing);
else else
@ -245,7 +243,7 @@ Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
BailError(err); BailError(err);
err = Nu_StrawRewind(pArchive, pStraw); err = Nu_StrawRewind(pArchive, pStraw);
BailError(err); BailError(err);
if (pProgressData != nil) if (pProgressData != NULL)
Nu_StrawSetProgressState(pStraw, kNuProgressStoring); Nu_StrawSetProgressState(pStraw, kNuProgressStoring);
err = Nu_ProgressDataCompressPrep(pArchive, pStraw, err = Nu_ProgressDataCompressPrep(pArchive, pStraw,
kNuThreadFormatUncompressed, srcLen); kNuThreadFormatUncompressed, srcLen);
@ -262,7 +260,7 @@ Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
* computed a CRC on the entire file (i.e. didn't stop early * computed a CRC on the entire file (i.e. didn't stop early
* when it noticed the output was larger than the input). If * when it noticed the output was larger than the input). If
* this is always the case, then we can change "&threadCrc" * this is always the case, then we can change "&threadCrc"
* a few lines back to "nil" and avoid re-computing the CRC. * a few lines back to "NULL" and avoid re-computing the CRC.
* If this is not always the case, remove this assert. * If this is not always the case, remove this assert.
*/ */
Assert(threadCrc == pThread->thThreadCRC); Assert(threadCrc == pThread->thThreadCRC);
@ -276,14 +274,14 @@ Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
/* /*
* Copy the already-compressed input. * Copy the already-compressed input.
*/ */
if (pProgressData != nil) if (pProgressData != NULL)
Nu_StrawSetProgressState(pStraw, kNuProgressCopying); Nu_StrawSetProgressState(pStraw, kNuProgressCopying);
err = Nu_ProgressDataCompressPrep(pArchive, pStraw, err = Nu_ProgressDataCompressPrep(pArchive, pStraw,
kNuThreadFormatUncompressed, srcLen); kNuThreadFormatUncompressed, srcLen);
BailError(err); BailError(err);
err = Nu_CompressUncompressed(pArchive, pStraw, dstFp, srcLen, err = Nu_CompressUncompressed(pArchive, pStraw, dstFp, srcLen,
&dstLen, nil); &dstLen, NULL);
BailError(err); BailError(err);
pThread->thThreadEOF = Nu_DataSourceGetOtherLen(pDataSource); pThread->thThreadEOF = Nu_DataSourceGetOtherLen(pDataSource);
@ -298,7 +296,7 @@ done:
srcLen, dstLen, pThread->actualThreadEOF)); srcLen, dstLen, pThread->actualThreadEOF));
/* make sure we send a final "success" progress message at 100% */ /* make sure we send a final "success" progress message at 100% */
if (pProgressData != nil) { if (pProgressData != NULL) {
(void) Nu_StrawSetProgressState(pStraw, kNuProgressDone); (void) Nu_StrawSetProgressState(pStraw, kNuProgressDone);
err = Nu_StrawSendProgressUpdate(pArchive, pStraw); err = Nu_StrawSendProgressUpdate(pArchive, pStraw);
BailError(err); BailError(err);
@ -322,14 +320,13 @@ bail:
* will copy the data, and then continue writing zeros to fill out the rest * will copy the data, and then continue writing zeros to fill out the rest
* of the pre-sized buffer. * of the pre-sized buffer.
*/ */
NuError NuError Nu_CopyPresizedToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
Nu_CopyPresizedToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
NuThreadID threadID, FILE* dstFp, NuThread* pThread, char** ppSavedCopy) NuThreadID threadID, FILE* dstFp, NuThread* pThread, char** ppSavedCopy)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuStraw* pStraw = nil; NuStraw* pStraw = NULL;
ulong srcLen, bufferLen; uint32_t srcLen, bufferLen;
ulong count, getsize; uint32_t count, getsize;
srcLen = Nu_DataSourceGetDataLen(pDataSource); srcLen = Nu_DataSourceGetDataLen(pDataSource);
bufferLen = Nu_DataSourceGetOtherLen(pDataSource); bufferLen = Nu_DataSourceGetOtherLen(pDataSource);
@ -355,7 +352,7 @@ Nu_CopyPresizedToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
* is a convenient way to deal with the dataSource, even though we * is a convenient way to deal with the dataSource, even though we
* don't have a progress updater. * don't have a progress updater.
*/ */
err = Nu_StrawNew(pArchive, pDataSource, nil, &pStraw); err = Nu_StrawNew(pArchive, pDataSource, NULL, &pStraw);
BailError(err); BailError(err);
count = srcLen; count = srcLen;
@ -370,7 +367,7 @@ Nu_CopyPresizedToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
err = Nu_FWrite(dstFp, pArchive->compBuf, getsize); err = Nu_FWrite(dstFp, pArchive->compBuf, getsize);
BailError(err); BailError(err);
if (ppSavedCopy != nil && *ppSavedCopy == nil) { if (ppSavedCopy != NULL && *ppSavedCopy == NULL) {
/* /*
* Grab a copy of the filename for our own use. This assumes * Grab a copy of the filename for our own use. This assumes
* that the filename fits in kNuGenCompBufSize, which is a * that the filename fits in kNuGenCompBufSize, which is a

View File

@ -7,7 +7,6 @@
* Compute 16-bit CRCs. Depending on the hardware, the table version * Compute 16-bit CRCs. Depending on the hardware, the table version
* might be slower than the loop computation. * might be slower than the loop computation.
*/ */
#define __Crc16_c__ 1
#include "NufxLibPriv.h" #include "NufxLibPriv.h"
#define CRC_TAB #define CRC_TAB
@ -30,7 +29,7 @@
/* crctab calculated by Mark G. Mendel, Network Systems Corporation */ /* crctab calculated by Mark G. Mendel, Network Systems Corporation */
const ushort gNuCrc16Table[256] = { const uint16_t gNuCrc16Table[256] = {
0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7, 0x0000, 0x1021, 0x2042, 0x3063, 0x4084, 0x50a5, 0x60c6, 0x70e7,
0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef, 0x8108, 0x9129, 0xa14a, 0xb16b, 0xc18c, 0xd1ad, 0xe1ce, 0xf1ef,
0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6, 0x1231, 0x0210, 0x3273, 0x2252, 0x52b5, 0x4294, 0x72f7, 0x62d6,
@ -83,13 +82,11 @@ const ushort gNuCrc16Table[256] = {
* Depending on CPU architecture, one may be dramatically faster than * Depending on CPU architecture, one may be dramatically faster than
* the other. * the other.
*/ */
ushort uint16_t Nu_CalcCRC16(uint16_t seed, const uint8_t* ptr, int count)
Nu_CalcCRC16(ushort seed, const uchar* ptr, int count)
{ {
ushort CRC = seed; uint16_t CRC = seed;
#ifndef CRC_TAB #ifndef CRC_TAB
int x; int x;
Assert(sizeof(ushort) == 2); /* I think this is assumed */
#endif #endif
do { do {

View File

@ -65,8 +65,7 @@ static const char* gFileSysIDs[] = {
* *
* Returns "buffer" for the benefit of printf() calls. * Returns "buffer" for the benefit of printf() calls.
*/ */
static char* static char* Nu_DebugDumpDate(const NuDateTime* pDateTime, char* buffer)
Nu_DebugDumpDate(const NuDateTime* pDateTime, char* buffer)
{ {
char* cp; char* cp;
@ -118,8 +117,7 @@ bail:
* *
* The result will be 2x the size of the original, +1 for a null byte. * The result will be 2x the size of the original, +1 for a null byte.
*/ */
static void static void ConvertToHexStr(const uint8_t* inBuf, int inLen, char* outBuf)
ConvertToHexStr(const uchar* inBuf, int inLen, char* outBuf)
{ {
while (inLen--) { while (inLen--) {
*outBuf++ = HexConv((*inBuf >> 4) & 0x0f); *outBuf++ = HexConv((*inBuf >> 4) & 0x0f);
@ -133,14 +131,13 @@ ConvertToHexStr(const uchar* inBuf, int inLen, char* outBuf)
/* /*
* Dump everything we know about pThread. * Dump everything we know about pThread.
*/ */
void void Nu_DebugDumpThread(const NuThread* pThread)
Nu_DebugDumpThread(const NuThread* pThread)
{ {
static const char* kInd = " "; static const char* kInd = " ";
NuThreadID threadID; NuThreadID threadID;
const char* descr; const char* descr;
Assert(pThread != nil); Assert(pThread != NULL);
printf("%sThreadClass: 0x%04x (%s)\n", kInd, printf("%sThreadClass: 0x%04x (%s)\n", kInd,
pThread->thThreadClass, pThread->thThreadClass,
@ -164,9 +161,9 @@ Nu_DebugDumpThread(const NuThread* pThread)
printf("%sThreadKind: 0x%04x (%s)\n", kInd, printf("%sThreadKind: 0x%04x (%s)\n", kInd,
pThread->thThreadKind, descr); pThread->thThreadKind, descr);
printf("%sThreadCRC: 0x%04x ThreadEOF: %lu CompThreadEOF: %lu\n", kInd, printf("%sThreadCRC: 0x%04x ThreadEOF: %u CompThreadEOF: %u\n", kInd,
pThread->thThreadCRC, pThread->thThreadEOF, pThread->thCompThreadEOF); pThread->thThreadCRC, pThread->thThreadEOF, pThread->thCompThreadEOF);
printf("%s*File data offset: %ld actualThreadEOF: %ld\n", kInd, printf("%s*File data offset: %ld actualThreadEOF: %d\n", kInd,
pThread->fileOffset, pThread->actualThreadEOF); pThread->fileOffset, pThread->actualThreadEOF);
} }
@ -177,8 +174,7 @@ Nu_DebugDumpThread(const NuThread* pThread)
* set. Pass in the "orig" copy in "pRecord", and optionally pass in the * set. Pass in the "orig" copy in "pRecord", and optionally pass in the
* "copy" set in "pXrefRecord" to glean data from both. * "copy" set in "pXrefRecord" to glean data from both.
*/ */
static void static void Nu_DebugDumpRecord(NuArchive* pArchive, const NuRecord* pRecord,
Nu_DebugDumpRecord(NuArchive* pArchive, const NuRecord* pRecord,
const NuRecord* pXrefRecord, Boolean isDeleted) const NuRecord* pXrefRecord, Boolean isDeleted)
{ {
NuError err; /* dummy */ NuError err; /* dummy */
@ -186,22 +182,24 @@ Nu_DebugDumpRecord(NuArchive* pArchive, const NuRecord* pRecord,
char dateBuf[kNuDateOutputLen]; char dateBuf[kNuDateOutputLen];
const NuThreadMod* pThreadMod; const NuThreadMod* pThreadMod;
const NuThread* pThread; const NuThread* pThread;
ulong idx; uint32_t idx;
Assert(pRecord != nil); Assert(pRecord != NULL);
/*printf("PTR: pRecord=0x%08lx pXrefRecord=0x%08lx\n", (long) pRecord, /*printf("PTR: pRecord=0x%08lx pXrefRecord=0x%08lx\n", (long) pRecord,
(long) pXrefRecord);*/ (long) pXrefRecord);*/
printf("%s%s%sFilename: '%s' (idx=%lu)\n", kInd, UNICHAR* filenameUNI = Nu_CopyMORToUNI(pRecord->filenameMOR);
printf("%s%s%sFilename: '%s' (idx=%u)\n", kInd,
isDeleted ? "[DEL] " : "", isDeleted ? "[DEL] " : "",
pXrefRecord != nil && pXrefRecord->pThreadMods != nil ? "[MOD] " : "", pXrefRecord != NULL && pXrefRecord->pThreadMods != NULL ? "[MOD] " : "",
pRecord->filename == nil ? "<not specified>" : pRecord->filename, filenameUNI == NULL ? "<not specified>" : filenameUNI,
pRecord->recordIdx); pRecord->recordIdx);
free(filenameUNI);
printf("%sHeaderID: '%.4s' VersionNumber: 0x%04x HeaderCRC: 0x%04x\n", printf("%sHeaderID: '%.4s' VersionNumber: 0x%04x HeaderCRC: 0x%04x\n",
kInd, kInd,
pRecord->recNufxID, pRecord->recVersionNumber, pRecord->recHeaderCRC); pRecord->recNufxID, pRecord->recVersionNumber, pRecord->recHeaderCRC);
printf("%sAttribCount: %u TotalThreads: %lu\n", kInd, printf("%sAttribCount: %u TotalThreads: %u\n", kInd,
pRecord->recAttribCount, pRecord->recTotalThreads); pRecord->recAttribCount, pRecord->recTotalThreads);
printf("%sFileSysID: %u (%s) FileSysInfo: 0x%04x ('%c')\n", kInd, printf("%sFileSysID: %u (%s) FileSysInfo: 0x%04x ('%c')\n", kInd,
pRecord->recFileSysID, pRecord->recFileSysID,
@ -209,7 +207,7 @@ Nu_DebugDumpRecord(NuArchive* pArchive, const NuRecord* pRecord,
pRecord->recFileSysInfo, pRecord->recFileSysInfo,
NuGetSepFromSysInfo(pRecord->recFileSysInfo)); NuGetSepFromSysInfo(pRecord->recFileSysInfo));
/* do something fancy for ProDOS? */ /* do something fancy for ProDOS? */
printf("%sFileType: 0x%08lx ExtraType: 0x%08lx Access: 0x%08lx\n", kInd, printf("%sFileType: 0x%08x ExtraType: 0x%08x Access: 0x%08x\n", kInd,
pRecord->recFileType, pRecord->recExtraType, pRecord->recAccess); pRecord->recFileType, pRecord->recExtraType, pRecord->recAccess);
printf("%sCreateWhen: %s\n", kInd, printf("%sCreateWhen: %s\n", kInd,
Nu_DebugDumpDate(&pRecord->recCreateWhen, dateBuf)); Nu_DebugDumpDate(&pRecord->recCreateWhen, dateBuf));
@ -223,13 +221,13 @@ Nu_DebugDumpRecord(NuArchive* pArchive, const NuRecord* pRecord,
if (pRecord->recOptionSize) { if (pRecord->recOptionSize) {
char* outBuf = Nu_Malloc(pArchive, pRecord->recOptionSize * 2 +1); char* outBuf = Nu_Malloc(pArchive, pRecord->recOptionSize * 2 +1);
BailAlloc(outBuf); BailAlloc(outBuf);
Assert(pRecord->recOptionList != nil); Assert(pRecord->recOptionList != NULL);
ConvertToHexStr(pRecord->recOptionList, pRecord->recOptionSize, outBuf); ConvertToHexStr(pRecord->recOptionList, pRecord->recOptionSize, outBuf);
printf("%sOptionList: [%s]\n", kInd, outBuf); printf("%sOptionList: [%s]\n", kInd, outBuf);
Nu_Free(pArchive, outBuf); Nu_Free(pArchive, outBuf);
} }
printf("%s*ExtraCount: %ld RecFileOffset: %ld RecHeaderLength: %ld\n", printf("%s*ExtraCount: %d RecFileOffset: %ld RecHeaderLength: %d\n",
kInd, kInd,
pRecord->extraCount, pRecord->fileOffset, pRecord->recHeaderLength); pRecord->extraCount, pRecord->fileOffset, pRecord->recHeaderLength);
@ -238,34 +236,34 @@ Nu_DebugDumpRecord(NuArchive* pArchive, const NuRecord* pRecord,
isFake = (idx >= pRecord->recTotalThreads - pRecord->fakeThreads); isFake = (idx >= pRecord->recTotalThreads - pRecord->fakeThreads);
pThread = Nu_GetThread(pRecord, idx); pThread = Nu_GetThread(pRecord, idx);
Assert(pThread != nil); Assert(pThread != NULL);
printf("%s--Thread #%lu (idx=%lu)%s\n", kInd, idx, pThread->threadIdx, printf("%s--Thread #%u (idx=%u)%s\n", kInd, idx, pThread->threadIdx,
isFake ? " [FAKE]" : ""); isFake ? " [FAKE]" : "");
Nu_DebugDumpThread(pThread); Nu_DebugDumpThread(pThread);
} }
if (pXrefRecord != nil) if (pXrefRecord != NULL)
pThreadMod = pXrefRecord->pThreadMods; pThreadMod = pXrefRecord->pThreadMods;
else else
pThreadMod = pRecord->pThreadMods; /* probably empty */ pThreadMod = pRecord->pThreadMods; /* probably empty */
if (pThreadMod != nil) if (pThreadMod != NULL)
printf("%s*ThreadMods -----\n", kInd); printf("%s*ThreadMods -----\n", kInd);
while (pThreadMod != nil) { while (pThreadMod != NULL) {
switch (pThreadMod->entry.kind) { switch (pThreadMod->entry.kind) {
case kNuThreadModAdd: case kNuThreadModAdd:
printf("%s *-ThreadMod ADD 0x%08lx 0x%04x (sourceType=%d)\n", kInd, printf("%s *-ThreadMod ADD 0x%08x 0x%04x (sourceType=%d)\n", kInd,
pThreadMod->entry.add.threadID, pThreadMod->entry.add.threadID,
pThreadMod->entry.add.threadFormat, pThreadMod->entry.add.threadFormat,
Nu_DataSourceGetType(pThreadMod->entry.add.pDataSource)); Nu_DataSourceGetType(pThreadMod->entry.add.pDataSource));
break; break;
case kNuThreadModUpdate: case kNuThreadModUpdate:
printf("%s *-ThreadMod UPDATE %6ld\n", kInd, printf("%s *-ThreadMod UPDATE %6d\n", kInd,
pThreadMod->entry.update.threadIdx); pThreadMod->entry.update.threadIdx);
break; break;
case kNuThreadModDelete: case kNuThreadModDelete:
printf("%s *-ThreadMod DELETE %6ld\n", kInd, printf("%s *-ThreadMod DELETE %6d\n", kInd,
pThreadMod->entry.delete.threadIdx); pThreadMod->entry.delete.threadIdx);
break; break;
case kNuThreadModUnknown: case kNuThreadModUnknown:
@ -280,7 +278,7 @@ Nu_DebugDumpRecord(NuArchive* pArchive, const NuRecord* pRecord,
/*printf("%s*TotalLength: %ld TotalCompLength: %ld\n", /*printf("%s*TotalLength: %ld TotalCompLength: %ld\n",
kInd, pRecord->totalLength, pRecord->totalCompLength);*/ kInd, pRecord->totalLength, pRecord->totalCompLength);*/
printf("%s*TotalCompLength: %ld\n", kInd, pRecord->totalCompLength); printf("%s*TotalCompLength: %u\n", kInd, pRecord->totalCompLength);
printf("\n"); printf("\n");
bail: bail:
@ -290,9 +288,8 @@ bail:
/* /*
* Dump the records in a RecordSet. * Dump the records in a RecordSet.
*/ */
static void static void Nu_DebugDumpRecordSet(NuArchive* pArchive,
Nu_DebugDumpRecordSet(NuArchive* pArchive, const NuRecordSet* pRecordSet, const NuRecordSet* pRecordSet, const NuRecordSet* pXrefSet)
const NuRecordSet* pXrefSet)
{ {
const NuRecord* pRecord; const NuRecord* pRecord;
const NuRecord* pXrefRecord; const NuRecord* pXrefRecord;
@ -300,8 +297,8 @@ Nu_DebugDumpRecordSet(NuArchive* pArchive, const NuRecordSet* pRecordSet,
long count; long count;
doXref = false; doXref = false;
pXrefRecord = nil; pXrefRecord = NULL;
if (pXrefSet != nil && Nu_RecordSet_GetLoaded(pXrefSet)) { if (pXrefSet != NULL && Nu_RecordSet_GetLoaded(pXrefSet)) {
pXrefRecord = Nu_RecordSet_GetListHead(pXrefSet); pXrefRecord = Nu_RecordSet_GetListHead(pXrefSet);
doXref = true; doXref = true;
} }
@ -309,18 +306,18 @@ Nu_DebugDumpRecordSet(NuArchive* pArchive, const NuRecordSet* pRecordSet,
/* dump every record, if we've loaded them */ /* dump every record, if we've loaded them */
count = Nu_RecordSet_GetNumRecords(pRecordSet); count = Nu_RecordSet_GetNumRecords(pRecordSet);
pRecord = Nu_RecordSet_GetListHead(pRecordSet); pRecord = Nu_RecordSet_GetListHead(pRecordSet);
if (pRecord != nil) { if (pRecord != NULL) {
Assert(count != 0); Assert(count != 0);
while (count--) { while (count--) {
Assert(pRecord != nil); Assert(pRecord != NULL);
if (pXrefRecord != nil && if (pXrefRecord != NULL &&
pRecord->recordIdx == pXrefRecord->recordIdx) pRecord->recordIdx == pXrefRecord->recordIdx)
{ {
Nu_DebugDumpRecord(pArchive, pRecord, pXrefRecord, false); Nu_DebugDumpRecord(pArchive, pRecord, pXrefRecord, false);
pXrefRecord = pXrefRecord->pNext; pXrefRecord = pXrefRecord->pNext;
} else { } else {
Nu_DebugDumpRecord(pArchive, pRecord, nil, doXref); Nu_DebugDumpRecord(pArchive, pRecord, NULL, doXref);
} }
pRecord = pRecord->pNext; pRecord = pRecord->pNext;
} }
@ -332,22 +329,21 @@ Nu_DebugDumpRecordSet(NuArchive* pArchive, const NuRecordSet* pRecordSet,
/* /*
* Dump the master header block. * Dump the master header block.
*/ */
static void static void Nu_DebugDumpMH(const NuMasterHeader* pMasterHeader)
Nu_DebugDumpMH(const NuMasterHeader* pMasterHeader)
{ {
static const char* kInd = " "; static const char* kInd = " ";
char dateBuf1[kNuDateOutputLen]; char dateBuf1[kNuDateOutputLen];
Assert(pMasterHeader != nil); Assert(pMasterHeader != NULL);
printf("%sNufileID: '%.6s' MasterCRC: 0x%04x TotalRecords: %lu\n", kInd, printf("%sNufileID: '%.6s' MasterCRC: 0x%04x TotalRecords: %u\n", kInd,
pMasterHeader->mhNufileID, pMasterHeader->mhMasterCRC, pMasterHeader->mhNufileID, pMasterHeader->mhMasterCRC,
pMasterHeader->mhTotalRecords); pMasterHeader->mhTotalRecords);
printf("%sArchiveCreateWhen: %s\n", kInd, printf("%sArchiveCreateWhen: %s\n", kInd,
Nu_DebugDumpDate(&pMasterHeader->mhArchiveCreateWhen, dateBuf1)); Nu_DebugDumpDate(&pMasterHeader->mhArchiveCreateWhen, dateBuf1));
printf("%sArchiveModWhen: %s\n", kInd, printf("%sArchiveModWhen: %s\n", kInd,
Nu_DebugDumpDate(&pMasterHeader->mhArchiveModWhen, dateBuf1)); Nu_DebugDumpDate(&pMasterHeader->mhArchiveModWhen, dateBuf1));
printf("%sMasterVersion: %u MasterEOF: %lu\n", kInd, printf("%sMasterVersion: %u MasterEOF: %u\n", kInd,
pMasterHeader->mhMasterVersion, pMasterHeader->mhMasterEOF); pMasterHeader->mhMasterVersion, pMasterHeader->mhMasterEOF);
} }
@ -359,20 +355,19 @@ Nu_DebugDumpMH(const NuMasterHeader* pMasterHeader)
* the archive, then this won't be very interesting. This will never * the archive, then this won't be very interesting. This will never
* show any records for streaming-mode archives. * show any records for streaming-mode archives.
*/ */
void void Nu_DebugDumpAll(NuArchive* pArchive)
Nu_DebugDumpAll(NuArchive* pArchive)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
printf("*Archive pathname: '%s'\n", pArchive->archivePathname); printf("*Archive pathname: '%s'\n", pArchive->archivePathnameUNI);
printf("*Archive type: %d\n", pArchive->archiveType); printf("*Archive type: %d\n", pArchive->archiveType);
printf("*Header offset: %ld (junk offset=%ld)\n", printf("*Header offset: %ld (junk offset=%ld)\n",
pArchive->headerOffset, pArchive->junkOffset); pArchive->headerOffset, pArchive->junkOffset);
printf("*Num records: %ld orig, %ld copy, %ld new\n", printf("*Num records: %u orig, %u copy, %u new\n",
Nu_RecordSet_GetNumRecords(&pArchive->origRecordSet), Nu_RecordSet_GetNumRecords(&pArchive->origRecordSet),
Nu_RecordSet_GetNumRecords(&pArchive->copyRecordSet), Nu_RecordSet_GetNumRecords(&pArchive->copyRecordSet),
Nu_RecordSet_GetNumRecords(&pArchive->newRecordSet)); Nu_RecordSet_GetNumRecords(&pArchive->newRecordSet));
printf("*NuRecordIdx seed: %lu NuRecordIdx next: %lu\n", printf("*NuRecordIdx seed: %u NuRecordIdx next: %u\n",
pArchive->recordIdxSeed, pArchive->nextRecordIdx); pArchive->recordIdxSeed, pArchive->nextRecordIdx);
/* master header */ /* master header */
@ -382,7 +377,7 @@ Nu_DebugDumpAll(NuArchive* pArchive)
Nu_DebugDumpRecordSet(pArchive, &pArchive->origRecordSet, Nu_DebugDumpRecordSet(pArchive, &pArchive->origRecordSet,
&pArchive->copyRecordSet); &pArchive->copyRecordSet);
printf(" *NEW record set:\n"); printf(" *NEW record set:\n");
Nu_DebugDumpRecordSet(pArchive, &pArchive->newRecordSet, nil); Nu_DebugDumpRecordSet(pArchive, &pArchive->newRecordSet, NULL);
if (!Nu_RecordSet_GetLoaded(&pArchive->origRecordSet) && if (!Nu_RecordSet_GetLoaded(&pArchive->origRecordSet) &&
!Nu_RecordSet_GetLoaded(&pArchive->newRecordSet)) !Nu_RecordSet_GetLoaded(&pArchive->newRecordSet))

File diff suppressed because it is too large Load Diff

View File

@ -25,13 +25,11 @@
/* /*
* Alloc and free functions provided to zlib. * Alloc and free functions provided to zlib.
*/ */
static voidpf static voidpf Nu_zalloc(voidpf opaque, uInt items, uInt size)
Nu_zalloc(voidpf opaque, uInt items, uInt size)
{ {
return Nu_Malloc(opaque, items * size); return Nu_Malloc(opaque, items * size);
} }
static void static void Nu_zfree(voidpf opaque, voidpf address)
Nu_zfree(voidpf opaque, voidpf address)
{ {
Nu_Free(opaque, address); Nu_Free(opaque, address);
} }
@ -46,21 +44,20 @@ Nu_zfree(voidpf opaque, voidpf address)
/* /*
* Compress "srcLen" bytes from "pStraw" to "fp". * Compress "srcLen" bytes from "pStraw" to "fp".
*/ */
NuError NuError Nu_CompressDeflate(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressDeflate(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc)
ulong srcLen, ulong* pDstLen, ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
z_stream zstream; z_stream zstream;
int zerr; int zerr;
Bytef* outbuf = nil; Bytef* outbuf = NULL;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(srcLen > 0); Assert(srcLen > 0);
Assert(pDstLen != nil); Assert(pDstLen != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
if (err != kNuErrNone) if (err != kNuErrNone)
@ -76,7 +73,7 @@ Nu_CompressDeflate(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
zstream.zalloc = Nu_zalloc; zstream.zalloc = Nu_zalloc;
zstream.zfree = Nu_zfree; zstream.zfree = Nu_zfree;
zstream.opaque = pArchive; zstream.opaque = pArchive;
zstream.next_in = nil; zstream.next_in = NULL;
zstream.avail_in = 0; zstream.avail_in = 0;
zstream.next_out = outbuf; zstream.next_out = outbuf;
zstream.avail_out = kNuGenCompBufSize; zstream.avail_out = kNuGenCompBufSize;
@ -100,7 +97,7 @@ Nu_CompressDeflate(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
* Loop while we have data. * Loop while we have data.
*/ */
do { do {
ulong getSize; uint32_t getSize;
int flush; int flush;
/* should be able to read a full buffer every time */ /* should be able to read a full buffer every time */
@ -159,7 +156,7 @@ z_bail:
deflateEnd(&zstream); /* free up any allocated structures */ deflateEnd(&zstream); /* free up any allocated structures */
bail: bail:
if (outbuf != nil) if (outbuf != NULL)
free(outbuf); free(outbuf);
return err; return err;
} }
@ -174,20 +171,19 @@ bail:
/* /*
* Expand from "infp" to "pFunnel". * Expand from "infp" to "pFunnel".
*/ */
NuError NuError Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord,
Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord, const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc)
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
z_stream zstream; z_stream zstream;
int zerr; int zerr;
ulong compRemaining; uint32_t compRemaining;
Bytef* outbuf; Bytef* outbuf;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(infp != nil); Assert(infp != NULL);
Assert(pFunnel != nil); Assert(pFunnel != NULL);
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
if (err != kNuErrNone) if (err != kNuErrNone)
@ -205,7 +201,7 @@ Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord,
zstream.zalloc = Nu_zalloc; zstream.zalloc = Nu_zalloc;
zstream.zfree = Nu_zfree; zstream.zfree = Nu_zfree;
zstream.opaque = pArchive; zstream.opaque = pArchive;
zstream.next_in = nil; zstream.next_in = NULL;
zstream.avail_in = 0; zstream.avail_in = 0;
zstream.next_out = outbuf; zstream.next_out = outbuf;
zstream.avail_out = kNuGenCompBufSize; zstream.avail_out = kNuGenCompBufSize;
@ -229,7 +225,7 @@ Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord,
* Loop while we have data. * Loop while we have data.
*/ */
do { do {
ulong getSize; uint32_t getSize;
/* read as much as we can */ /* read as much as we can */
if (zstream.avail_in == 0) { if (zstream.avail_in == 0) {
@ -269,7 +265,7 @@ Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord,
goto z_bail; goto z_bail;
} }
if (pCrc != nil) if (pCrc != NULL)
*pCrc = Nu_CalcCRC16(*pCrc, outbuf, zstream.next_out - outbuf); *pCrc = Nu_CalcCRC16(*pCrc, outbuf, zstream.next_out - outbuf);
zstream.next_out = outbuf; zstream.next_out = outbuf;
@ -282,7 +278,7 @@ Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord,
if (zstream.total_out != pThread->actualThreadEOF) { if (zstream.total_out != pThread->actualThreadEOF) {
err = kNuErrBadData; err = kNuErrBadData;
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"size mismatch on inflated file (%ld vs %ld)", "size mismatch on inflated file (%ld vs %u)",
zstream.total_out, pThread->actualThreadEOF); zstream.total_out, pThread->actualThreadEOF);
goto z_bail; goto z_bail;
} }
@ -291,7 +287,7 @@ z_bail:
inflateEnd(&zstream); /* free up any allocated structures */ inflateEnd(&zstream); /* free up any allocated structures */
bail: bail:
if (outbuf != nil) if (outbuf != NULL)
free(outbuf); free(outbuf);
return err; return err;
} }

View File

@ -24,8 +24,7 @@
* it does not follow all sorts of crazy semaphore semantics. If you * it does not follow all sorts of crazy semaphore semantics. If you
* have the need, go ahead and fix it. * have the need, go ahead and fix it.
*/ */
static inline void static inline void Nu_SetBusy(NuArchive* pArchive)
Nu_SetBusy(NuArchive* pArchive)
{ {
pArchive->busy = true; pArchive->busy = true;
} }
@ -33,8 +32,7 @@ Nu_SetBusy(NuArchive* pArchive)
/* /*
* Clear the busy flag. * Clear the busy flag.
*/ */
static inline void static inline void Nu_ClearBusy(NuArchive* pArchive)
Nu_ClearBusy(NuArchive* pArchive)
{ {
pArchive->busy = false; pArchive->busy = false;
} }
@ -45,13 +43,11 @@ Nu_ClearBusy(NuArchive* pArchive)
* can be made during callback functions when the archive isn't fully * can be made during callback functions when the archive isn't fully
* consistent. * consistent.
*/ */
static NuError static NuError Nu_PartiallyValidateNuArchive(const NuArchive* pArchive)
Nu_PartiallyValidateNuArchive(const NuArchive* pArchive)
{ {
if (pArchive == nil) if (pArchive == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
pArchive = pArchive;
if (pArchive->structMagic != kNuArchiveStructMagic) if (pArchive->structMagic != kNuArchiveStructMagic)
return kNuErrBadStruct; return kNuErrBadStruct;
@ -61,8 +57,7 @@ Nu_PartiallyValidateNuArchive(const NuArchive* pArchive)
/* /*
* Validate the NuArchive* argument passed in to us. * Validate the NuArchive* argument passed in to us.
*/ */
static NuError static NuError Nu_ValidateNuArchive(const NuArchive* pArchive)
Nu_ValidateNuArchive(const NuArchive* pArchive)
{ {
NuError err; NuError err;
@ -77,19 +72,19 @@ Nu_ValidateNuArchive(const NuArchive* pArchive)
/* make sure the TOC state is consistent */ /* make sure the TOC state is consistent */
if (pArchive->haveToc) { if (pArchive->haveToc) {
if (pArchive->masterHeader.mhTotalRecords != 0) if (pArchive->masterHeader.mhTotalRecords != 0)
Assert(Nu_RecordSet_GetListHead(&pArchive->origRecordSet) != nil); Assert(Nu_RecordSet_GetListHead(&pArchive->origRecordSet) != NULL);
Assert(Nu_RecordSet_GetNumRecords(&pArchive->origRecordSet) == Assert(Nu_RecordSet_GetNumRecords(&pArchive->origRecordSet) ==
pArchive->masterHeader.mhTotalRecords); pArchive->masterHeader.mhTotalRecords);
} else { } else {
Assert(Nu_RecordSet_GetListHead(&pArchive->origRecordSet) == nil); Assert(Nu_RecordSet_GetListHead(&pArchive->origRecordSet) == NULL);
} }
/* make sure we have open files to work with */ /* make sure we have open files to work with */
Assert(pArchive->archivePathname == nil || pArchive->archiveFp != nil); Assert(pArchive->archivePathnameUNI == NULL || pArchive->archiveFp != NULL);
if (pArchive->archivePathname != nil && pArchive->archiveFp == nil) if (pArchive->archivePathnameUNI != NULL && pArchive->archiveFp == NULL)
return kNuErrInternal; return kNuErrInternal;
Assert(pArchive->tmpPathname == nil || pArchive->tmpFp != nil); Assert(pArchive->tmpPathnameUNI == NULL || pArchive->tmpFp != NULL);
if (pArchive->tmpPathname != nil && pArchive->tmpFp == nil) if (pArchive->tmpPathnameUNI != NULL && pArchive->tmpFp == NULL)
return kNuErrInternal; return kNuErrInternal;
/* further validations */ /* further validations */
@ -104,12 +99,11 @@ Nu_ValidateNuArchive(const NuArchive* pArchive)
* =========================================================================== * ===========================================================================
*/ */
NUFXLIB_API NuError NUFXLIB_API NuError NuStreamOpenRO(FILE* infp, NuArchive** ppArchive)
NuStreamOpenRO(FILE* infp, NuArchive** ppArchive)
{ {
NuError err; NuError err;
if (infp == nil || ppArchive == nil) if (infp == NULL || ppArchive == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
err = Nu_StreamOpenRO(infp, (NuArchive**) ppArchive); err = Nu_StreamOpenRO(infp, (NuArchive**) ppArchive);
@ -117,8 +111,7 @@ NuStreamOpenRO(FILE* infp, NuArchive** ppArchive)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuContents(NuArchive* pArchive, NuCallback contentFunc)
NuContents(NuArchive* pArchive, NuCallback contentFunc)
{ {
NuError err; NuError err;
@ -134,8 +127,7 @@ NuContents(NuArchive* pArchive, NuCallback contentFunc)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuExtract(NuArchive* pArchive)
NuExtract(NuArchive* pArchive)
{ {
NuError err; NuError err;
@ -151,8 +143,7 @@ NuExtract(NuArchive* pArchive)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuTest(NuArchive* pArchive)
NuTest(NuArchive* pArchive)
{ {
NuError err; NuError err;
@ -168,8 +159,7 @@ NuTest(NuArchive* pArchive)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuTestRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
NuTestRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
{ {
NuError err; NuError err;
@ -189,18 +179,17 @@ NuTestRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
* =========================================================================== * ===========================================================================
*/ */
NUFXLIB_API NuError NUFXLIB_API NuError NuOpenRO(const UNICHAR* archivePathnameUNI,
NuOpenRO(const char* filename, NuArchive** ppArchive) NuArchive** ppArchive)
{ {
NuError err; NuError err;
err = Nu_OpenRO(filename, (NuArchive**) ppArchive); err = Nu_OpenRO(archivePathnameUNI, (NuArchive**) ppArchive);
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuExtractRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
NuExtractRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
{ {
NuError err; NuError err;
@ -213,8 +202,7 @@ NuExtractRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
NuExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
NuDataSink* pDataSink) NuDataSink* pDataSink)
{ {
NuError err; NuError err;
@ -228,8 +216,7 @@ NuExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetRecord(NuArchive* pArchive, NuRecordIdx recordIdx,
NuGetRecord(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecord** ppRecord) const NuRecord** ppRecord)
{ {
NuError err; NuError err;
@ -243,23 +230,21 @@ NuGetRecord(NuArchive* pArchive, NuRecordIdx recordIdx,
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetRecordIdxByName(NuArchive* pArchive,
NuGetRecordIdxByName(NuArchive* pArchive, const char* name, const char* nameMOR, NuRecordIdx* pRecordIdx)
NuRecordIdx* pRecordIdx)
{ {
NuError err; NuError err;
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
Nu_SetBusy(pArchive); Nu_SetBusy(pArchive);
err = Nu_GetRecordIdxByName(pArchive, name, pRecordIdx); err = Nu_GetRecordIdxByName(pArchive, nameMOR, pRecordIdx);
Nu_ClearBusy(pArchive); Nu_ClearBusy(pArchive);
} }
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetRecordIdxByPosition(NuArchive* pArchive, uint32_t position,
NuGetRecordIdxByPosition(NuArchive* pArchive, unsigned long position,
NuRecordIdx* pRecordIdx) NuRecordIdx* pRecordIdx)
{ {
NuError err; NuError err;
@ -280,20 +265,18 @@ NuGetRecordIdxByPosition(NuArchive* pArchive, unsigned long position,
* =========================================================================== * ===========================================================================
*/ */
NUFXLIB_API NuError NUFXLIB_API NuError NuOpenRW(const UNICHAR* archivePathnameUNI,
NuOpenRW(const char* archivePathname, const char* tmpPathname, const UNICHAR* tmpPathnameUNI, uint32_t flags, NuArchive** ppArchive)
unsigned long flags, NuArchive** ppArchive)
{ {
NuError err; NuError err;
err = Nu_OpenRW(archivePathname, tmpPathname, flags, err = Nu_OpenRW(archivePathnameUNI, tmpPathnameUNI, flags,
(NuArchive**) ppArchive); (NuArchive**) ppArchive);
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuFlush(NuArchive* pArchive, uint32_t* pStatusFlags)
NuFlush(NuArchive* pArchive, long* pStatusFlags)
{ {
NuError err; NuError err;
@ -306,8 +289,7 @@ NuFlush(NuArchive* pArchive, long* pStatusFlags)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuAbort(NuArchive* pArchive)
NuAbort(NuArchive* pArchive)
{ {
NuError err; NuError err;
@ -320,24 +302,22 @@ NuAbort(NuArchive* pArchive)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuAddRecord(NuArchive* pArchive,
NuAddRecord(NuArchive* pArchive, const NuFileDetails* pFileDetails, const NuFileDetails* pFileDetails, NuRecordIdx* pRecordIdx)
NuRecordIdx* pRecordIdx)
{ {
NuError err; NuError err;
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
Nu_SetBusy(pArchive); Nu_SetBusy(pArchive);
err = Nu_AddRecord(pArchive, pFileDetails, pRecordIdx, nil); err = Nu_AddRecord(pArchive, pFileDetails, pRecordIdx, NULL);
Nu_ClearBusy(pArchive); Nu_ClearBusy(pArchive);
} }
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuAddThread(NuArchive* pArchive, NuRecordIdx recordIdx,
NuAddThread(NuArchive* pArchive, NuRecordIdx recordIdx, NuThreadID threadID, NuThreadID threadID, NuDataSource* pDataSource, NuThreadIdx* pThreadIdx)
NuDataSource* pDataSource, NuThreadIdx* pThreadIdx)
{ {
NuError err; NuError err;
@ -351,8 +331,7 @@ NuAddThread(NuArchive* pArchive, NuRecordIdx recordIdx, NuThreadID threadID,
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuAddFile(NuArchive* pArchive, const UNICHAR* pathnameUNI,
NuAddFile(NuArchive* pArchive, const char* pathname,
const NuFileDetails* pFileDetails, short isFromRsrcFork, const NuFileDetails* pFileDetails, short isFromRsrcFork,
NuRecordIdx* pRecordIdx) NuRecordIdx* pRecordIdx)
{ {
@ -360,7 +339,7 @@ NuAddFile(NuArchive* pArchive, const char* pathname,
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
Nu_SetBusy(pArchive); Nu_SetBusy(pArchive);
err = Nu_AddFile(pArchive, pathname, pFileDetails, err = Nu_AddFile(pArchive, pathnameUNI, pFileDetails,
(Boolean)(isFromRsrcFork != 0), pRecordIdx); (Boolean)(isFromRsrcFork != 0), pRecordIdx);
Nu_ClearBusy(pArchive); Nu_ClearBusy(pArchive);
} }
@ -368,15 +347,14 @@ NuAddFile(NuArchive* pArchive, const char* pathname,
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuRename(NuArchive* pArchive, NuRecordIdx recordIdx,
NuRename(NuArchive* pArchive, NuRecordIdx recordIdx, const char* pathname, const char* pathnameMOR, char fssep)
char fssep)
{ {
NuError err; NuError err;
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
Nu_SetBusy(pArchive); Nu_SetBusy(pArchive);
err = Nu_Rename(pArchive, recordIdx, pathname, fssep); err = Nu_Rename(pArchive, recordIdx, pathnameMOR, fssep);
Nu_ClearBusy(pArchive); Nu_ClearBusy(pArchive);
} }
@ -384,8 +362,7 @@ NuRename(NuArchive* pArchive, NuRecordIdx recordIdx, const char* pathname,
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuSetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx,
NuSetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecordAttr* pRecordAttr) const NuRecordAttr* pRecordAttr)
{ {
NuError err; NuError err;
@ -399,9 +376,8 @@ NuSetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx,
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuUpdatePresizedThread(NuArchive* pArchive,
NuUpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx, NuThreadIdx threadIdx, NuDataSource* pDataSource, int32_t* pMaxLen)
NuDataSource* pDataSource, long* pMaxLen)
{ {
NuError err; NuError err;
@ -415,8 +391,7 @@ NuUpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx,
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuDelete(NuArchive* pArchive)
NuDelete(NuArchive* pArchive)
{ {
NuError err; NuError err;
@ -429,8 +404,7 @@ NuDelete(NuArchive* pArchive)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuDeleteRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
NuDeleteRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
{ {
NuError err; NuError err;
@ -443,8 +417,7 @@ NuDeleteRecord(NuArchive* pArchive, NuRecordIdx recordIdx)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuDeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx)
NuDeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx)
{ {
NuError err; NuError err;
@ -464,8 +437,7 @@ NuDeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx)
* =========================================================================== * ===========================================================================
*/ */
NUFXLIB_API NuError NUFXLIB_API NuError NuClose(NuArchive* pArchive)
NuClose(NuArchive* pArchive)
{ {
NuError err; NuError err;
@ -480,8 +452,8 @@ NuClose(NuArchive* pArchive)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetMasterHeader(NuArchive* pArchive,
NuGetMasterHeader(NuArchive* pArchive, const NuMasterHeader** ppMasterHeader) const NuMasterHeader** ppMasterHeader)
{ {
NuError err; NuError err;
@ -491,12 +463,11 @@ NuGetMasterHeader(NuArchive* pArchive, const NuMasterHeader** ppMasterHeader)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetExtraData(NuArchive* pArchive, void** ppData)
NuGetExtraData(NuArchive* pArchive, void** ppData)
{ {
NuError err; NuError err;
if (ppData == nil) if (ppData == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
if ((err = Nu_PartiallyValidateNuArchive(pArchive)) == kNuErrNone) if ((err = Nu_PartiallyValidateNuArchive(pArchive)) == kNuErrNone)
*ppData = pArchive->extraData; *ppData = pArchive->extraData;
@ -504,8 +475,7 @@ NuGetExtraData(NuArchive* pArchive, void** ppData)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuSetExtraData(NuArchive* pArchive, void* pData)
NuSetExtraData(NuArchive* pArchive, void* pData)
{ {
NuError err; NuError err;
@ -515,8 +485,8 @@ NuSetExtraData(NuArchive* pArchive, void* pData)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetValue(NuArchive* pArchive, NuValueID ident,
NuGetValue(NuArchive* pArchive, NuValueID ident, NuValue* pValue) NuValue* pValue)
{ {
NuError err; NuError err;
@ -526,8 +496,8 @@ NuGetValue(NuArchive* pArchive, NuValueID ident, NuValue* pValue)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuSetValue(NuArchive* pArchive, NuValueID ident,
NuSetValue(NuArchive* pArchive, NuValueID ident, NuValue value) NuValue value)
{ {
NuError err; NuError err;
@ -537,8 +507,8 @@ NuSetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetAttr(NuArchive* pArchive, NuAttrID ident,
NuGetAttr(NuArchive* pArchive, NuAttrID ident, NuAttr* pAttr) NuAttr* pAttr)
{ {
NuError err; NuError err;
@ -548,8 +518,7 @@ NuGetAttr(NuArchive* pArchive, NuAttrID ident, NuAttr* pAttr)
return err; return err;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuDebugDumpArchive(NuArchive* pArchive)
NuDebugDumpArchive(NuArchive* pArchive)
{ {
#if defined(DEBUG_MSGS) #if defined(DEBUG_MSGS)
/* skip validation checks for this one */ /* skip validation checks for this one */
@ -568,82 +537,75 @@ NuDebugDumpArchive(NuArchive* pArchive)
* =========================================================================== * ===========================================================================
*/ */
NUFXLIB_API NuError NUFXLIB_API NuError NuCreateDataSourceForFile(NuThreadFormat threadFormat,
NuCreateDataSourceForFile(NuThreadFormat threadFormat, uint32_t otherLen, const UNICHAR* pathnameUNI, short isFromRsrcFork,
unsigned long otherLen, const char* pathname, short isFromRsrcFork,
NuDataSource** ppDataSource) NuDataSource** ppDataSource)
{ {
return Nu_DataSourceFile_New(threadFormat, otherLen, return Nu_DataSourceFile_New(threadFormat, otherLen,
pathname, (Boolean)(isFromRsrcFork != 0), ppDataSource); pathnameUNI, (Boolean)(isFromRsrcFork != 0), ppDataSource);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuCreateDataSourceForFP(NuThreadFormat threadFormat,
NuCreateDataSourceForFP(NuThreadFormat threadFormat, uint32_t otherLen, FILE* fp, long offset, long length,
unsigned long otherLen, FILE* fp, long offset, long length,
NuCallback fcloseFunc, NuDataSource** ppDataSource) NuCallback fcloseFunc, NuDataSource** ppDataSource)
{ {
return Nu_DataSourceFP_New(threadFormat, otherLen, return Nu_DataSourceFP_New(threadFormat, otherLen,
fp, offset, length, fcloseFunc, ppDataSource); fp, offset, length, fcloseFunc, ppDataSource);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuCreateDataSourceForBuffer(NuThreadFormat threadFormat,
NuCreateDataSourceForBuffer(NuThreadFormat threadFormat, uint32_t otherLen, const uint8_t* buffer, long offset,
unsigned long otherLen, const unsigned char* buffer, long offset,
long length, NuCallback freeFunc, NuDataSource** ppDataSource) long length, NuCallback freeFunc, NuDataSource** ppDataSource)
{ {
return Nu_DataSourceBuffer_New(threadFormat, otherLen, return Nu_DataSourceBuffer_New(threadFormat, otherLen,
buffer, offset, length, freeFunc, ppDataSource); buffer, offset, length, freeFunc, ppDataSource);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuFreeDataSource(NuDataSource* pDataSource)
NuFreeDataSource(NuDataSource* pDataSource)
{ {
return Nu_DataSourceFree(pDataSource); return Nu_DataSourceFree(pDataSource);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuDataSourceSetRawCrc(NuDataSource* pDataSource,
NuDataSourceSetRawCrc(NuDataSource* pDataSource, unsigned short crc) uint16_t crc)
{ {
if (pDataSource == nil) if (pDataSource == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
Nu_DataSourceSetRawCrc(pDataSource, crc); Nu_DataSourceSetRawCrc(pDataSource, crc);
return kNuErrNone; return kNuErrNone;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuCreateDataSinkForFile(short doExpand, NuValue convertEOL,
NuCreateDataSinkForFile(short doExpand, NuValue convertEOL, const UNICHAR* pathnameUNI, UNICHAR fssep, NuDataSink** ppDataSink)
const char* pathname, char fssep, NuDataSink** ppDataSink)
{ {
return Nu_DataSinkFile_New((Boolean)(doExpand != 0), convertEOL, pathname, return Nu_DataSinkFile_New((Boolean)(doExpand != 0), convertEOL,
fssep, ppDataSink); pathnameUNI, fssep, ppDataSink);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuCreateDataSinkForFP(short doExpand, NuValue convertEOL,
NuCreateDataSinkForFP(short doExpand, NuValue convertEOL, FILE* fp, FILE* fp, NuDataSink** ppDataSink)
NuDataSink** ppDataSink)
{ {
return Nu_DataSinkFP_New((Boolean)(doExpand != 0), convertEOL, fp, return Nu_DataSinkFP_New((Boolean)(doExpand != 0), convertEOL, fp,
ppDataSink); ppDataSink);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuCreateDataSinkForBuffer(short doExpand,
NuCreateDataSinkForBuffer(short doExpand, NuValue convertEOL, NuValue convertEOL, uint8_t* buffer, uint32_t bufLen,
unsigned char* buffer, unsigned long bufLen, NuDataSink** ppDataSink) NuDataSink** ppDataSink)
{ {
return Nu_DataSinkBuffer_New((Boolean)(doExpand != 0), convertEOL, buffer, return Nu_DataSinkBuffer_New((Boolean)(doExpand != 0), convertEOL, buffer,
bufLen, ppDataSink); bufLen, ppDataSink);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuFreeDataSink(NuDataSink* pDataSink)
NuFreeDataSink(NuDataSink* pDataSink)
{ {
return Nu_DataSinkFree(pDataSink); return Nu_DataSinkFree(pDataSink);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuDataSinkGetOutCount(NuDataSink* pDataSink,
NuDataSinkGetOutCount(NuDataSink* pDataSink, ulong* pOutCount) uint32_t* pOutCount)
{ {
if (pDataSink == nil || pOutCount == nil) if (pDataSink == NULL || pOutCount == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
*pOutCount = Nu_DataSinkGetOutCount(pDataSink); *pOutCount = Nu_DataSinkGetOutCount(pDataSink);
@ -657,22 +619,19 @@ NuDataSinkGetOutCount(NuDataSink* pDataSink, ulong* pOutCount)
* =========================================================================== * ===========================================================================
*/ */
NUFXLIB_API const char* NUFXLIB_API const char* NuStrError(NuError err)
NuStrError(NuError err)
{ {
return Nu_StrError(err); return Nu_StrError(err);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuGetVersion(int32_t* pMajorVersion, int32_t* pMinorVersion,
NuGetVersion(long* pMajorVersion, long* pMinorVersion, long* pBugVersion, int32_t* pBugVersion, const char** ppBuildDate, const char** ppBuildFlags)
const char** ppBuildDate, const char** ppBuildFlags)
{ {
return Nu_GetVersion(pMajorVersion, pMinorVersion, pBugVersion, return Nu_GetVersion(pMajorVersion, pMinorVersion, pBugVersion,
ppBuildDate, ppBuildFlags); ppBuildDate, ppBuildFlags);
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuTestFeature(NuFeature feature)
NuTestFeature(NuFeature feature)
{ {
NuError err = kNuErrUnsupFeature; NuError err = kNuErrUnsupFeature;
@ -710,8 +669,8 @@ NuTestFeature(NuFeature feature)
return err; return err;
} }
NUFXLIB_API void NUFXLIB_API void NuRecordCopyAttr(NuRecordAttr* pRecordAttr,
NuRecordCopyAttr(NuRecordAttr* pRecordAttr, const NuRecord* pRecord) const NuRecord* pRecord)
{ {
pRecordAttr->fileSysID = pRecord->recFileSysID; pRecordAttr->fileSysID = pRecord->recFileSysID;
/*pRecordAttr->fileSysInfo = pRecord->recFileSysInfo;*/ /*pRecordAttr->fileSysInfo = pRecord->recFileSysInfo;*/
@ -723,16 +682,16 @@ NuRecordCopyAttr(NuRecordAttr* pRecordAttr, const NuRecord* pRecord)
pRecordAttr->archiveWhen = pRecord->recArchiveWhen; pRecordAttr->archiveWhen = pRecord->recArchiveWhen;
} }
NUFXLIB_API NuError NUFXLIB_API NuError NuRecordCopyThreads(const NuRecord* pNuRecord,
NuRecordCopyThreads(const NuRecord* pNuRecord, NuThread** ppThreads) NuThread** ppThreads)
{ {
if (pNuRecord == nil || ppThreads == nil) if (pNuRecord == NULL || ppThreads == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
Assert(pNuRecord->pThreads != nil); Assert(pNuRecord->pThreads != NULL);
*ppThreads = Nu_Malloc(nil, pNuRecord->recTotalThreads * sizeof(NuThread)); *ppThreads = Nu_Malloc(NULL, pNuRecord->recTotalThreads * sizeof(NuThread));
if (*ppThreads == nil) if (*ppThreads == NULL)
return kNuErrMalloc; return kNuErrMalloc;
memcpy(*ppThreads, pNuRecord->pThreads, memcpy(*ppThreads, pNuRecord->pThreads,
@ -741,29 +700,39 @@ NuRecordCopyThreads(const NuRecord* pNuRecord, NuThread** ppThreads)
return kNuErrNone; return kNuErrNone;
} }
NUFXLIB_API unsigned long NUFXLIB_API uint32_t NuRecordGetNumThreads(const NuRecord* pNuRecord)
NuRecordGetNumThreads(const NuRecord* pNuRecord)
{ {
if (pNuRecord == nil) if (pNuRecord == NULL)
return -1; return -1;
return pNuRecord->recTotalThreads; return pNuRecord->recTotalThreads;
} }
NUFXLIB_API const NuThread* NUFXLIB_API const NuThread* NuThreadGetByIdx(const NuThread* pNuThread,
NuThreadGetByIdx(const NuThread* pNuThread, long idx) int32_t idx)
{ {
if (pNuThread == nil) if (pNuThread == NULL)
return nil; return NULL;
return &pNuThread[idx]; /* can't range-check here */ return &pNuThread[idx]; /* can't range-check here */
} }
NUFXLIB_API short NUFXLIB_API short NuIsPresizedThreadID(NuThreadID threadID)
NuIsPresizedThreadID(NuThreadID threadID)
{ {
return Nu_IsPresizedThreadID(threadID); return Nu_IsPresizedThreadID(threadID);
} }
NUFXLIB_API size_t NuConvertMORToUNI(const char* stringMOR,
UNICHAR* bufUNI, size_t bufSize)
{
return Nu_ConvertMORToUNI(stringMOR, bufUNI, bufSize);
}
NUFXLIB_API size_t NuConvertUNIToMOR(const UNICHAR* stringUNI,
char* bufMOR, size_t bufSize)
{
return Nu_ConvertUNIToMOR(stringUNI, bufMOR, bufSize);
}
/* /*
* =========================================================================== * ===========================================================================
@ -771,13 +740,13 @@ NuIsPresizedThreadID(NuThreadID threadID)
* =========================================================================== * ===========================================================================
*/ */
NUFXLIB_API NuCallback NUFXLIB_API NuCallback NuSetSelectionFilter(NuArchive* pArchive,
NuSetSelectionFilter(NuArchive* pArchive, NuCallback filterFunc) NuCallback filterFunc)
{ {
NuError err; NuError err;
NuCallback oldFunc = kNuInvalidCallback; NuCallback oldFunc = kNuInvalidCallback;
/*Assert(!((ulong)filterFunc % 4));*/ /*Assert(!((uint32_t)filterFunc % 4));*/
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
oldFunc = pArchive->selectionFilterFunc; oldFunc = pArchive->selectionFilterFunc;
@ -787,13 +756,13 @@ NuSetSelectionFilter(NuArchive* pArchive, NuCallback filterFunc)
return oldFunc; return oldFunc;
} }
NUFXLIB_API NuCallback NUFXLIB_API NuCallback NuSetOutputPathnameFilter(NuArchive* pArchive,
NuSetOutputPathnameFilter(NuArchive* pArchive, NuCallback filterFunc) NuCallback filterFunc)
{ {
NuError err; NuError err;
NuCallback oldFunc = kNuInvalidCallback; NuCallback oldFunc = kNuInvalidCallback;
/*Assert(!((ulong)filterFunc % 4));*/ /*Assert(!((uint32_t)filterFunc % 4));*/
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
oldFunc = pArchive->outputPathnameFunc; oldFunc = pArchive->outputPathnameFunc;
@ -803,13 +772,13 @@ NuSetOutputPathnameFilter(NuArchive* pArchive, NuCallback filterFunc)
return oldFunc; return oldFunc;
} }
NUFXLIB_API NuCallback NUFXLIB_API NuCallback NuSetProgressUpdater(NuArchive* pArchive,
NuSetProgressUpdater(NuArchive* pArchive, NuCallback updateFunc) NuCallback updateFunc)
{ {
NuError err; NuError err;
NuCallback oldFunc = kNuInvalidCallback; NuCallback oldFunc = kNuInvalidCallback;
/*Assert(!((ulong)updateFunc % 4));*/ /*Assert(!((uint32_t)updateFunc % 4));*/
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
oldFunc = pArchive->progressUpdaterFunc; oldFunc = pArchive->progressUpdaterFunc;
@ -819,13 +788,13 @@ NuSetProgressUpdater(NuArchive* pArchive, NuCallback updateFunc)
return oldFunc; return oldFunc;
} }
NUFXLIB_API NuCallback NUFXLIB_API NuCallback NuSetErrorHandler(NuArchive* pArchive,
NuSetErrorHandler(NuArchive* pArchive, NuCallback errorFunc) NuCallback errorFunc)
{ {
NuError err; NuError err;
NuCallback oldFunc = kNuInvalidCallback; NuCallback oldFunc = kNuInvalidCallback;
/*Assert(!((ulong)errorFunc % 4));*/ /*Assert(!((uint32_t)errorFunc % 4));*/
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
oldFunc = pArchive->errorHandlerFunc; oldFunc = pArchive->errorHandlerFunc;
@ -835,13 +804,13 @@ NuSetErrorHandler(NuArchive* pArchive, NuCallback errorFunc)
return oldFunc; return oldFunc;
} }
NUFXLIB_API NuCallback NUFXLIB_API NuCallback NuSetErrorMessageHandler(NuArchive* pArchive,
NuSetErrorMessageHandler(NuArchive* pArchive, NuCallback messageHandlerFunc) NuCallback messageHandlerFunc)
{ {
NuError err; NuError err;
NuCallback oldFunc = kNuInvalidCallback; NuCallback oldFunc = kNuInvalidCallback;
/*Assert(!((ulong)messageHandlerFunc % 4));*/ /*Assert(!((uint32_t)messageHandlerFunc % 4));*/
if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) { if ((err = Nu_ValidateNuArchive(pArchive)) == kNuErrNone) {
oldFunc = pArchive->messageHandlerFunc; oldFunc = pArchive->messageHandlerFunc;
@ -851,11 +820,10 @@ NuSetErrorMessageHandler(NuArchive* pArchive, NuCallback messageHandlerFunc)
return oldFunc; return oldFunc;
} }
NUFXLIB_API NuCallback NUFXLIB_API NuCallback NuSetGlobalErrorMessageHandler(NuCallback messageHandlerFunc)
NuSetGlobalErrorMessageHandler(NuCallback messageHandlerFunc)
{ {
NuCallback oldFunc = kNuInvalidCallback; NuCallback oldFunc = kNuInvalidCallback;
/*Assert(!((ulong)messageHandlerFunc % 4));*/ /*Assert(!((uint32_t)messageHandlerFunc % 4));*/
oldFunc = gNuGlobalErrorMessageHandler; oldFunc = gNuGlobalErrorMessageHandler;
gNuGlobalErrorMessageHandler = messageHandlerFunc; gNuGlobalErrorMessageHandler = messageHandlerFunc;

View File

@ -12,18 +12,18 @@
/* /*
* "Expand" an uncompressed thread. * "Expand" an uncompressed thread.
*/ */
static NuError static NuError Nu_ExpandUncompressed(NuArchive* pArchive,
Nu_ExpandUncompressed(NuArchive* pArchive, const NuRecord* pRecord, const NuRecord* pRecord, const NuThread* pThread, FILE* infp,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc) NuFunnel* pFunnel, uint16_t* pCrc)
{ {
NuError err; NuError err;
/*uchar* buffer = nil;*/ /*uint8_t* buffer = NULL;*/
ulong count, getsize; uint32_t count, getsize;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(infp != nil); Assert(infp != NULL);
Assert(pFunnel != nil); Assert(pFunnel != NULL);
/* doesn't have to be same size as funnel, but it's not a bad idea */ /* doesn't have to be same size as funnel, but it's not a bad idea */
/*buffer = Nu_Malloc(pArchive, kNuFunnelBufSize);*/ /*buffer = Nu_Malloc(pArchive, kNuFunnelBufSize);*/
@ -43,7 +43,7 @@ Nu_ExpandUncompressed(NuArchive* pArchive, const NuRecord* pRecord,
err = Nu_FRead(infp, pArchive->compBuf, getsize); err = Nu_FRead(infp, pArchive->compBuf, getsize);
BailError(err); BailError(err);
if (pCrc != nil) if (pCrc != NULL)
*pCrc = Nu_CalcCRC16(*pCrc, pArchive->compBuf, getsize); *pCrc = Nu_CalcCRC16(*pCrc, pArchive->compBuf, getsize);
err = Nu_FunnelWrite(pArchive, pFunnel, pArchive->compBuf, getsize); err = Nu_FunnelWrite(pArchive, pFunnel, pArchive->compBuf, getsize);
BailError(err); BailError(err);
@ -63,18 +63,17 @@ bail:
* Copy the "raw" data out of the thread. Unlike the preceeding function, * Copy the "raw" data out of the thread. Unlike the preceeding function,
* this reads up to "thCompThreadEOF", and doesn't even try to compute a CRC. * this reads up to "thCompThreadEOF", and doesn't even try to compute a CRC.
*/ */
static NuError static NuError Nu_ExpandRaw(NuArchive* pArchive, const NuThread* pThread,
Nu_ExpandRaw(NuArchive* pArchive, const NuThread* pThread, FILE* infp, FILE* infp, NuFunnel* pFunnel)
NuFunnel* pFunnel)
{ {
NuError err; NuError err;
/*uchar* buffer = nil;*/ /*uint8_t* buffer = NULL;*/
ulong count, getsize; uint32_t count, getsize;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(infp != nil); Assert(infp != NULL);
Assert(pFunnel != nil); Assert(pFunnel != NULL);
/* doesn't have to be same size as funnel, but it's not a bad idea */ /* doesn't have to be same size as funnel, but it's not a bad idea */
/*buffer = Nu_Malloc(pArchive, kNuFunnelBufSize);*/ /*buffer = Nu_Malloc(pArchive, kNuFunnelBufSize);*/
@ -108,13 +107,12 @@ bail:
* Expand a thread from "infp" to "pFunnel", using the compression * Expand a thread from "infp" to "pFunnel", using the compression
* and stream length specified by "pThread". * and stream length specified by "pThread".
*/ */
NuError NuError Nu_ExpandStream(NuArchive* pArchive, const NuRecord* pRecord,
Nu_ExpandStream(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel) const NuThread* pThread, FILE* infp, NuFunnel* pFunnel)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
ushort calcCrc; uint16_t calcCrc;
ushort* pCalcCrc; uint16_t* pCalcCrc;
if (!pThread->thThreadEOF && !pThread->thCompThreadEOF) { if (!pThread->thThreadEOF && !pThread->thCompThreadEOF) {
/* somebody stored an empty file! */ /* somebody stored an empty file! */
@ -134,7 +132,7 @@ Nu_ExpandStream(NuArchive* pArchive, const NuRecord* pRecord,
* unfortunately, unprotected before v3. * unfortunately, unprotected before v3.
*/ */
calcCrc = kNuInitialThreadCRC; calcCrc = kNuInitialThreadCRC;
pCalcCrc = nil; pCalcCrc = NULL;
if (Nu_ThreadHasCRC(pRecord->recVersionNumber, NuGetThreadID(pThread)) && if (Nu_ThreadHasCRC(pRecord->recVersionNumber, NuGetThreadID(pThread)) &&
!pArchive->valIgnoreCRC) !pArchive->valIgnoreCRC)
{ {
@ -205,7 +203,7 @@ Nu_ExpandStream(NuArchive* pArchive, const NuRecord* pRecord,
/* /*
* If we have a CRC to check, check it. * If we have a CRC to check, check it.
*/ */
if (pCalcCrc != nil) { if (pCalcCrc != NULL) {
if (calcCrc != pThread->thThreadCRC) { if (calcCrc != pThread->thThreadCRC) {
if (!Nu_ShouldIgnoreBadCRC(pArchive, pRecord, kNuErrBadThreadCRC)) { if (!Nu_ShouldIgnoreBadCRC(pArchive, pRecord, kNuErrBadThreadCRC)) {
err = kNuErrBadDataCRC; err = kNuErrBadDataCRC;

File diff suppressed because it is too large Load Diff

View File

@ -22,38 +22,36 @@
* The same structure will be used when expanding all threads in a given * The same structure will be used when expanding all threads in a given
* record. * record.
*/ */
NuError NuError Nu_ProgressDataInit_Compress(NuArchive* pArchive,
Nu_ProgressDataInit_Compress(NuArchive* pArchive, NuProgressData* pProgressData, NuProgressData* pProgressData, const NuRecord* pRecord,
const NuRecord* pRecord, const char* origPathname) const UNICHAR* origPathnameUNI, const UNICHAR* pathnameUNI)
{ {
const char* cp; const char* cp;
Assert(pProgressData != nil); Assert(pProgressData != NULL);
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pRecord != nil); Assert(pRecord != NULL);
Assert(origPathname != nil); Assert(origPathnameUNI != NULL);
Assert(pathnameUNI != NULL);
pProgressData->pRecord = pRecord; pProgressData->pRecord = pRecord;
pProgressData->origPathname = origPathname; pProgressData->origPathnameUNI = origPathnameUNI;
pProgressData->pathname = pRecord->filename; pProgressData->pathnameUNI = pathnameUNI;
cp = strrchr(pRecord->filename, cp = strrchr(pathnameUNI, NuGetSepFromSysInfo(pRecord->recFileSysInfo));
NuGetSepFromSysInfo(pRecord->recFileSysInfo)); if (cp == NULL || *(cp+1) == '\0')
if (cp == nil || *(cp+1) == '\0') pProgressData->filenameUNI = pProgressData->pathnameUNI;
pProgressData->filename = pProgressData->pathname;
else else
pProgressData->filename = cp+1; pProgressData->filenameUNI = cp+1;
pProgressData->operation = kNuOpAdd; pProgressData->operation = kNuOpAdd;
pProgressData->state = kNuProgressPreparing; pProgressData->state = kNuProgressPreparing;
/*pProgressData->compressedLength = 0;*/
/*pProgressData->compressedProgress = 0;*/
pProgressData->uncompressedLength = 0; pProgressData->uncompressedLength = 0;
pProgressData->uncompressedProgress = 0; pProgressData->uncompressedProgress = 0;
pProgressData->compress.threadFormat = (NuThreadFormat)-1; pProgressData->compress.threadFormat = (NuThreadFormat)-1;
/* ya know... if this is nil, none of the above matters much */ /* ya know... if this is NULL, none of the above matters much */
pProgressData->progressFunc = pArchive->progressUpdaterFunc; pProgressData->progressFunc = pArchive->progressUpdaterFunc;
return kNuErrNone; return kNuErrNone;
@ -67,31 +65,32 @@ Nu_ProgressDataInit_Compress(NuArchive* pArchive, NuProgressData* pProgressData,
* The same structure will be used when expanding all threads in a given * The same structure will be used when expanding all threads in a given
* record. * record.
*/ */
NuError NuError Nu_ProgressDataInit_Expand(NuArchive* pArchive,
Nu_ProgressDataInit_Expand(NuArchive* pArchive, NuProgressData* pProgressData, NuProgressData* pProgressData, const NuRecord* pRecord,
const NuRecord* pRecord, const char* newPathname, char newFssep, const UNICHAR* newPathnameUNI, UNICHAR newFssep,
NuValue convertEOL) const UNICHAR* origPathnameUNI, NuValue convertEOL)
{ {
const NuThread* pThreadIter; const NuThread* pThreadIter;
const char* cp; const char* cp;
int i; int i;
Assert(pProgressData != nil); Assert(pProgressData != NULL);
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pRecord != nil); Assert(pRecord != NULL);
Assert(newPathname != nil); Assert(newPathnameUNI != NULL);
Assert(origPathnameUNI != NULL);
Assert(newFssep != 0); Assert(newFssep != 0);
pProgressData->pRecord = pRecord; pProgressData->pRecord = pRecord;
pProgressData->expand.pThread = nil; pProgressData->expand.pThread = NULL;
pProgressData->origPathname = pRecord->filename; pProgressData->origPathnameUNI = origPathnameUNI;
pProgressData->pathname = newPathname; pProgressData->pathnameUNI = newPathnameUNI;
cp = strrchr(newPathname, newFssep); cp = strrchr(newPathnameUNI, newFssep);
if (cp == nil || *(cp+1) == '\0') if (cp == NULL || *(cp+1) == '\0')
pProgressData->filename = newPathname; pProgressData->filenameUNI = newPathnameUNI;
else else
pProgressData->filename = cp+1; pProgressData->filenameUNI = cp+1;
pProgressData->expand.convertEOL = convertEOL; pProgressData->expand.convertEOL = convertEOL;
@ -111,12 +110,10 @@ Nu_ProgressDataInit_Expand(NuArchive* pArchive, NuProgressData* pProgressData,
if (pArchive->testMode) if (pArchive->testMode)
pProgressData->operation = kNuOpTest; pProgressData->operation = kNuOpTest;
pProgressData->state = kNuProgressPreparing; pProgressData->state = kNuProgressPreparing;
/*pProgressData->expand.compressedLength = 0;*/
/*pProgressData->expand.compressedProgress = 0;*/
pProgressData->uncompressedLength = 0; pProgressData->uncompressedLength = 0;
pProgressData->uncompressedProgress = 0; pProgressData->uncompressedProgress = 0;
/* ya know... if this is nil, none of the above matters much */ /* ya know... if this is NULL, none of the above matters much */
pProgressData->progressFunc = pArchive->progressUpdaterFunc; pProgressData->progressFunc = pArchive->progressUpdaterFunc;
return kNuErrNone; return kNuErrNone;
@ -126,18 +123,17 @@ Nu_ProgressDataInit_Expand(NuArchive* pArchive, NuProgressData* pProgressData,
/* /*
* Do the setup on a ProgressData prior to compressing a thread. * Do the setup on a ProgressData prior to compressing a thread.
*/ */
NuError NuError Nu_ProgressDataCompressPrep(NuArchive* pArchive, NuStraw* pStraw,
Nu_ProgressDataCompressPrep(NuArchive* pArchive, NuStraw* pStraw, NuThreadFormat threadFormat, uint32_t sourceLen)
NuThreadFormat threadFormat, ulong sourceLen)
{ {
NuProgressData* pProgressData; NuProgressData* pProgressData;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(sourceLen < 32767*65536); Assert(sourceLen < 32767*65536);
pProgressData = pStraw->pProgress; pProgressData = pStraw->pProgress;
if (pProgressData == nil) if (pProgressData == NULL)
return kNuErrNone; return kNuErrNone;
pProgressData->uncompressedLength = sourceLen; pProgressData->uncompressedLength = sourceLen;
@ -151,18 +147,17 @@ Nu_ProgressDataCompressPrep(NuArchive* pArchive, NuStraw* pStraw,
* *
* "pThread" is the thread being expanded. * "pThread" is the thread being expanded.
*/ */
NuError NuError Nu_ProgressDataExpandPrep(NuArchive* pArchive, NuFunnel* pFunnel,
Nu_ProgressDataExpandPrep(NuArchive* pArchive, NuFunnel* pFunnel,
const NuThread* pThread) const NuThread* pThread)
{ {
NuProgressData* pProgressData; NuProgressData* pProgressData;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pFunnel != nil); Assert(pFunnel != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
pProgressData = pFunnel->pProgress; pProgressData = pFunnel->pProgress;
if (pProgressData == nil) if (pProgressData == NULL)
return kNuErrNone; return kNuErrNone;
/*pProgressData->compressedLength = pThread->thCompThreadEOF;*/ /*pProgressData->compressedLength = pThread->thCompThreadEOF;*/
@ -175,10 +170,9 @@ Nu_ProgressDataExpandPrep(NuArchive* pArchive, NuFunnel* pFunnel,
/* /*
* Compute a completion percentage. * Compute a completion percentage.
*/ */
static int static int Nu_ComputePercent(uint32_t total, uint32_t progress)
Nu_ComputePercent(ulong total, ulong progress)
{ {
ulong perc; uint32_t perc;
if (!total) if (!total)
return 0; return 0;
@ -200,15 +194,14 @@ Nu_ComputePercent(ulong total, ulong progress)
* Send the initial progress message, before the output file is opened * Send the initial progress message, before the output file is opened
* (when extracting) or the input file is opened (when adding). * (when extracting) or the input file is opened (when adding).
*/ */
NuError NuError Nu_SendInitialProgress(NuArchive* pArchive, NuProgressData* pProgress)
Nu_SendInitialProgress(NuArchive* pArchive, NuProgressData* pProgress)
{ {
NuResult result; NuResult result;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pProgress != nil); Assert(pProgress != NULL);
if (pProgress->progressFunc == nil) if (pProgress->progressFunc == NULL)
return kNuErrNone; return kNuErrNone;
pProgress->percentComplete = Nu_ComputePercent( pProgress->percentComplete = Nu_ComputePercent(
@ -234,15 +227,15 @@ Nu_SendInitialProgress(NuArchive* pArchive, NuProgressData* pProgress)
/* /*
* Allocate and initialize a Funnel. * Allocate and initialize a Funnel.
*/ */
NuError NuError Nu_FunnelNew(NuArchive* pArchive, NuDataSink* pDataSink,
Nu_FunnelNew(NuArchive* pArchive, NuDataSink* pDataSink, NuValue convertEOL, NuValue convertEOL, NuValue convertEOLTo, NuProgressData* pProgress,
NuValue convertEOLTo, NuProgressData* pProgress, NuFunnel** ppFunnel) NuFunnel** ppFunnel)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuFunnel* pFunnel = nil; NuFunnel* pFunnel = NULL;
Assert(ppFunnel != nil); Assert(ppFunnel != NULL);
Assert(pDataSink != nil); Assert(pDataSink != NULL);
Assert(convertEOL == kNuConvertOff || Assert(convertEOL == kNuConvertOff ||
convertEOL == kNuConvertOn || convertEOL == kNuConvertOn ||
convertEOL == kNuConvertAuto); convertEOL == kNuConvertAuto);
@ -278,10 +271,9 @@ bail:
* The data should already have been written; it's not the duty of a * The data should already have been written; it's not the duty of a
* "free" function to flush data out. * "free" function to flush data out.
*/ */
NuError NuError Nu_FunnelFree(NuArchive* pArchive, NuFunnel* pFunnel)
Nu_FunnelFree(NuArchive* pArchive, NuFunnel* pFunnel)
{ {
if (pFunnel == nil) if (pFunnel == NULL)
return kNuErrNone; return kNuErrNone;
#ifdef DEBUG_MSGS #ifdef DEBUG_MSGS
@ -304,10 +296,9 @@ Nu_FunnelFree(NuArchive* pArchive, NuFunnel* pFunnel)
* allows us to bail out as soon as it's apparent that compression is * allows us to bail out as soon as it's apparent that compression is
* failing and is actually resulting in a larger file. * failing and is actually resulting in a larger file.
*/ */
void void Nu_FunnelSetMaxOutput(NuFunnel* pFunnel, uint32_t maxBytes)
Nu_FunnelSetMaxOutput(NuFunnel* pFunnel, ulong maxBytes)
{ {
Assert(pFunnel != nil); Assert(pFunnel != NULL);
Assert(maxBytes > 0); Assert(maxBytes > 0);
pFunnel->outMax = maxBytes; pFunnel->outMax = maxBytes;
@ -324,13 +315,12 @@ Nu_FunnelSetMaxOutput(NuFunnel* pFunnel, ulong maxBytes)
* character must have its high bit set, except for spaces (0x20). * character must have its high bit set, except for spaces (0x20).
* (The exception is courtesy Glen Bredon's "Merlin".) * (The exception is courtesy Glen Bredon's "Merlin".)
*/ */
static Boolean static Boolean Nu_CheckHighASCII(const NuFunnel* pFunnel, const uint8_t* buffer,
Nu_CheckHighASCII(const NuFunnel* pFunnel, const unsigned char* buffer, uint32_t count)
unsigned long count)
{ {
Boolean isHighASCII; Boolean isHighASCII;
Assert(buffer != nil); Assert(buffer != NULL);
Assert(count != 0); Assert(count != 0);
Assert(pFunnel->checkStripHighASCII); Assert(pFunnel->checkStripHighASCII);
@ -405,12 +395,12 @@ static const char gNuIsBinary[256] = {
* Returns kConvEOLOff or kConvEOLOn, and sets pFunnel->doStripHighASCII * Returns kConvEOLOff or kConvEOLOn, and sets pFunnel->doStripHighASCII
* if pFunnel->CheckStripHighASCII is set. * if pFunnel->CheckStripHighASCII is set.
*/ */
static NuValue static NuValue Nu_DetermineConversion(NuFunnel* pFunnel, const uint8_t* buffer,
Nu_DetermineConversion(NuFunnel* pFunnel, const uchar* buffer, ulong count) uint32_t count)
{ {
ulong bufCount, numBinary, numLF, numCR; uint32_t bufCount, numBinary, numLF, numCR;
Boolean isHighASCII; Boolean isHighASCII;
uchar val; uint8_t val;
if (count < kNuMinConvThreshold) if (count < kNuMinConvThreshold)
return kNuConvertOff; return kNuConvertOff;
@ -484,12 +474,12 @@ Nu_DetermineConversion(NuFunnel* pFunnel, const uchar* buffer, ulong count)
* This is either a Funnel function or a DataSink function, depending on * This is either a Funnel function or a DataSink function, depending on
* your perspective. * your perspective.
*/ */
static inline void static inline void Nu_FunnelPutBlock(NuFunnel* pFunnel, const uint8_t* buf,
Nu_FunnelPutBlock(NuFunnel* pFunnel, const uchar* buf, ulong len) uint32_t len)
{ {
Assert(pFunnel != nil); Assert(pFunnel != NULL);
Assert(pFunnel->pDataSink != nil); Assert(pFunnel->pDataSink != NULL);
Assert(buf != nil); Assert(buf != NULL);
Assert(len > 0); Assert(len > 0);
#if 0 #if 0
@ -511,10 +501,9 @@ Nu_FunnelPutBlock(NuFunnel* pFunnel, const uchar* buf, ulong len)
/* /*
* Output the EOL marker requested for this system. * Output the EOL marker requested for this system.
*/ */
static inline void static inline void Nu_PutEOL(NuFunnel* pFunnel)
Nu_PutEOL(NuFunnel* pFunnel)
{ {
uchar ch; uint8_t ch;
if (pFunnel->convertEOLTo == kNuEOLCR) { if (pFunnel->convertEOLTo == kNuEOLCR) {
ch = kNuCharCR; ch = kNuCharCR;
@ -540,11 +529,11 @@ Nu_PutEOL(NuFunnel* pFunnel)
* that looks like an EOL mark and convert it. Doesn't matter if it's * that looks like an EOL mark and convert it. Doesn't matter if it's
* CR, LF, or CRLF; all three get converted to whatever the system uses. * CR, LF, or CRLF; all three get converted to whatever the system uses.
*/ */
static NuError static NuError Nu_FunnelWriteConvert(NuFunnel* pFunnel, const uint8_t* buffer,
Nu_FunnelWriteConvert(NuFunnel* pFunnel, const uchar* buffer, ulong count) uint32_t count)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
ulong progressCount = count; uint32_t progressCount = count;
/*if (pFunnel->outMaxExceeded) /*if (pFunnel->outMaxExceeded)
return kNuErrOutMax;*/ return kNuErrOutMax;*/
@ -566,7 +555,7 @@ Nu_FunnelWriteConvert(NuFunnel* pFunnel, const uchar* buffer, ulong count)
pFunnel->convertEOL = kNuConvertOff; pFunnel->convertEOL = kNuConvertOff;
} }
/* put it where the progress meter can see it */ /* put it where the progress meter can see it */
if (pFunnel->pProgress != nil) if (pFunnel->pProgress != NULL)
pFunnel->pProgress->expand.convertEOL = pFunnel->convertEOL; pFunnel->pProgress->expand.convertEOL = pFunnel->convertEOL;
} else if (pFunnel->convertEOL == kNuConvertOn) { } else if (pFunnel->convertEOL == kNuConvertOn) {
if (pFunnel->checkStripHighASCII) { if (pFunnel->checkStripHighASCII) {
@ -589,7 +578,7 @@ Nu_FunnelWriteConvert(NuFunnel* pFunnel, const uchar* buffer, ulong count)
} else { } else {
/* do the EOL conversion and optional high-bit stripping */ /* do the EOL conversion and optional high-bit stripping */
Boolean lastCR = pFunnel->lastCR; /* make local copy */ Boolean lastCR = pFunnel->lastCR; /* make local copy */
uchar uch; uint8_t uch;
int mask; int mask;
if (pFunnel->doStripHighASCII) if (pFunnel->doStripHighASCII)
@ -627,7 +616,7 @@ Nu_FunnelWriteConvert(NuFunnel* pFunnel, const uchar* buffer, ulong count)
err = Nu_DataSinkGetError(pFunnel->pDataSink); err = Nu_DataSinkGetError(pFunnel->pDataSink);
/* update progress counter with pre-LFCR count */ /* update progress counter with pre-LFCR count */
if (err == kNuErrNone && pFunnel->pProgress != nil) if (err == kNuErrNone && pFunnel->pProgress != NULL)
pFunnel->pProgress->uncompressedProgress += progressCount; pFunnel->pProgress->uncompressedProgress += progressCount;
return err; return err;
@ -637,8 +626,7 @@ Nu_FunnelWriteConvert(NuFunnel* pFunnel, const uchar* buffer, ulong count)
/* /*
* Flush any data currently in the funnel. * Flush any data currently in the funnel.
*/ */
NuError NuError Nu_FunnelFlush(NuArchive* pArchive, NuFunnel* pFunnel)
Nu_FunnelFlush(NuArchive* pArchive, NuFunnel* pFunnel)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
@ -661,9 +649,8 @@ bail:
* Write a bunch of bytes into a funnel. They will be held in the buffer * Write a bunch of bytes into a funnel. They will be held in the buffer
* if they fit, or flushed out the bottom if not. * if they fit, or flushed out the bottom if not.
*/ */
NuError NuError Nu_FunnelWrite(NuArchive* pArchive, NuFunnel* pFunnel,
Nu_FunnelWrite(NuArchive* pArchive, NuFunnel* pFunnel, const uchar* buffer, const uint8_t* buffer, uint32_t count)
ulong count)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
@ -714,12 +701,11 @@ bail:
/* /*
* Set the Funnel's progress state. * Set the Funnel's progress state.
*/ */
NuError NuError Nu_FunnelSetProgressState(NuFunnel* pFunnel, NuProgressState state)
Nu_FunnelSetProgressState(NuFunnel* pFunnel, NuProgressState state)
{ {
Assert(pFunnel != nil); Assert(pFunnel != NULL);
if (pFunnel->pProgress == nil) if (pFunnel->pProgress == NULL)
return kNuErrNone; return kNuErrNone;
pFunnel->pProgress->state = state; pFunnel->pProgress->state = state;
@ -731,20 +717,19 @@ Nu_FunnelSetProgressState(NuFunnel* pFunnel, NuProgressState state)
/* /*
* Send a progress update to the application, if they're interested. * Send a progress update to the application, if they're interested.
*/ */
NuError NuError Nu_FunnelSendProgressUpdate(NuArchive* pArchive, NuFunnel* pFunnel)
Nu_FunnelSendProgressUpdate(NuArchive* pArchive, NuFunnel* pFunnel)
{ {
NuProgressData* pProgress; NuProgressData* pProgress;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pFunnel != nil); Assert(pFunnel != NULL);
pProgress = pFunnel->pProgress; pProgress = pFunnel->pProgress;
if (pProgress == nil) if (pProgress == NULL)
return kNuErrNone; /* no progress meter attached */ return kNuErrNone; /* no progress meter attached */
/* don't continue if they're not accepting progress messages */ /* don't continue if they're not accepting progress messages */
if (pProgress->progressFunc == nil) if (pProgress->progressFunc == NULL)
return kNuErrNone; return kNuErrNone;
/* other than the choice of arguments, it's pretty much the same story */ /* other than the choice of arguments, it's pretty much the same story */
@ -755,11 +740,10 @@ Nu_FunnelSendProgressUpdate(NuArchive* pArchive, NuFunnel* pFunnel)
/* /*
* Pull the "doExpand" parameter out of the data source. * Pull the "doExpand" parameter out of the data source.
*/ */
Boolean Boolean Nu_FunnelGetDoExpand(NuFunnel* pFunnel)
Nu_FunnelGetDoExpand(NuFunnel* pFunnel)
{ {
Assert(pFunnel != nil); Assert(pFunnel != NULL);
Assert(pFunnel->pDataSink != nil); Assert(pFunnel->pDataSink != NULL);
return Nu_DataSinkGetDoExpand(pFunnel->pDataSink); return Nu_DataSinkGetDoExpand(pFunnel->pDataSink);
} }
@ -774,15 +758,14 @@ Nu_FunnelGetDoExpand(NuFunnel* pFunnel)
/* /*
* Allocate and initialize a Straw. * Allocate and initialize a Straw.
*/ */
NuError NuError Nu_StrawNew(NuArchive* pArchive, NuDataSource* pDataSource,
Nu_StrawNew(NuArchive* pArchive, NuDataSource* pDataSource,
NuProgressData* pProgress, NuStraw** ppStraw) NuProgressData* pProgress, NuStraw** ppStraw)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuStraw* pStraw = nil; NuStraw* pStraw = NULL;
Assert(ppStraw != nil); Assert(ppStraw != NULL);
Assert(pDataSource != nil); Assert(pDataSource != NULL);
pStraw = Nu_Calloc(pArchive, sizeof(*pStraw)); pStraw = Nu_Calloc(pArchive, sizeof(*pStraw));
BailAlloc(pStraw); BailAlloc(pStraw);
@ -802,10 +785,9 @@ bail:
/* /*
* Free a Straw. * Free a Straw.
*/ */
NuError NuError Nu_StrawFree(NuArchive* pArchive, NuStraw* pStraw)
Nu_StrawFree(NuArchive* pArchive, NuStraw* pStraw)
{ {
if (pStraw == nil) if (pStraw == NULL)
return kNuErrNone; return kNuErrNone;
/* we don't own the data source or progress meter */ /* we don't own the data source or progress meter */
@ -818,11 +800,10 @@ Nu_StrawFree(NuArchive* pArchive, NuStraw* pStraw)
/* /*
* Set the Straw's progress state. * Set the Straw's progress state.
*/ */
NuError NuError Nu_StrawSetProgressState(NuStraw* pStraw, NuProgressState state)
Nu_StrawSetProgressState(NuStraw* pStraw, NuProgressState state)
{ {
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(pStraw->pProgress != nil); Assert(pStraw->pProgress != NULL);
pStraw->pProgress->state = state; pStraw->pProgress->state = state;
@ -832,20 +813,19 @@ Nu_StrawSetProgressState(NuStraw* pStraw, NuProgressState state)
/* /*
* Send a progress update to the application, if they're interested. * Send a progress update to the application, if they're interested.
*/ */
NuError NuError Nu_StrawSendProgressUpdate(NuArchive* pArchive, NuStraw* pStraw)
Nu_StrawSendProgressUpdate(NuArchive* pArchive, NuStraw* pStraw)
{ {
NuProgressData* pProgress; NuProgressData* pProgress;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pStraw != nil); Assert(pStraw != NULL);
pProgress = pStraw->pProgress; pProgress = pStraw->pProgress;
if (pProgress == nil) if (pProgress == NULL)
return kNuErrNone; /* no progress meter attached */ return kNuErrNone; /* no progress meter attached */
/* don't continue if they're not accepting progress messages */ /* don't continue if they're not accepting progress messages */
if (pProgress->progressFunc == nil) if (pProgress->progressFunc == NULL)
return kNuErrNone; return kNuErrNone;
/* other than the choice of arguments, it's pretty much the same story */ /* other than the choice of arguments, it's pretty much the same story */
@ -856,14 +836,14 @@ Nu_StrawSendProgressUpdate(NuArchive* pArchive, NuStraw* pStraw)
/* /*
* Read data from a straw. * Read data from a straw.
*/ */
NuError NuError Nu_StrawRead(NuArchive* pArchive, NuStraw* pStraw, uint8_t* buffer,
Nu_StrawRead(NuArchive* pArchive, NuStraw* pStraw, uchar* buffer, long len) long len)
{ {
NuError err; NuError err;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(buffer != nil); Assert(buffer != NULL);
Assert(len > 0); Assert(len > 0);
/* /*
@ -887,7 +867,7 @@ Nu_StrawRead(NuArchive* pArchive, NuStraw* pStraw, uchar* buffer, long len)
* on the previous call. (This assumes that whatever they asked for * on the previous call. (This assumes that whatever they asked for
* last time has already been fully processed.) * last time has already been fully processed.)
*/ */
if (pStraw->pProgress != nil) { if (pStraw->pProgress != NULL) {
pStraw->pProgress->uncompressedProgress = pStraw->lastProgress; pStraw->pProgress->uncompressedProgress = pStraw->lastProgress;
pStraw->lastProgress += len; pStraw->lastProgress += len;
@ -911,11 +891,10 @@ bail:
* Rewind a straw. This rewinds the underlying data source, and resets * Rewind a straw. This rewinds the underlying data source, and resets
* some progress counters. * some progress counters.
*/ */
NuError NuError Nu_StrawRewind(NuArchive* pArchive, NuStraw* pStraw)
Nu_StrawRewind(NuArchive* pArchive, NuStraw* pStraw)
{ {
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(pStraw->pDataSource != nil); Assert(pStraw->pDataSource != NULL);
pStraw->lastProgress = 0; pStraw->lastProgress = 0;
pStraw->lastDisplayed = 0; pStraw->lastDisplayed = 0;

View File

@ -25,10 +25,10 @@
/* /*
* Selected definitions from compress.h. * Selected definitions from compress.h.
*/ */
typedef unsigned short CODE; typedef uint16_t CODE;
typedef unsigned char UCHAR; typedef uint8_t UCHAR;
typedef unsigned int INTCODE; typedef uint32_t INTCODE;
typedef unsigned int HASH; typedef uint32_t HASH;
typedef int FLAG; typedef int FLAG;
#ifndef FALSE /* let's get some sense to this */ #ifndef FALSE /* let's get some sense to this */
@ -80,7 +80,7 @@ static UCHAR gNu_magic_header[] = { 0x1F,0x9D };
* Normally in COMPUSI.UNI. * Normally in COMPUSI.UNI.
*/ */
static inline ALLOCTYPE FAR * static inline ALLOCTYPE FAR *
Nu_LZC_emalloc(NuArchive* pArchive, unsigned int x, int y) Nu_LZC_emalloc(NuArchive* pArchive, uint32_t x, int y)
{ {
return Nu_Malloc(pArchive, x*y); return Nu_Malloc(pArchive, x*y);
} }
@ -153,7 +153,7 @@ Nu_LZC_efree(NuArchive* pArchive, ALLOCTYPE FAR * ptr)
typedef struct LZCState { typedef struct LZCState {
NuArchive* pArchive; NuArchive* pArchive;
int doCalcCRC; int doCalcCRC;
ushort crc; uint16_t crc;
/* compression */ /* compression */
NuStraw* pStraw; NuStraw* pStraw;
@ -163,7 +163,7 @@ typedef struct LZCState {
/* expansion */ /* expansion */
FILE* infp; FILE* infp;
NuFunnel* pFunnel; NuFunnel* pFunnel;
ushort* pCrc; uint16_t* pCrc;
long compRemaining; long compRemaining;
@ -251,18 +251,18 @@ static CONST INTCODE gNu_mc[] = {
#ifdef __STDC__ #ifdef __STDC__
#ifdef DEBUG_LZC #ifdef DEBUG_LZC
#define allocx(type, ptr, size) \ #define allocx(type, ptr, size) \
(((ptr) = (type FAR *) Nu_LZC_emalloc(pArchive, (unsigned int)(size),sizeof(type))) == NULLPTR(type) \ (((ptr) = (type FAR *) Nu_LZC_emalloc(pArchive, (uint32_t)(size),sizeof(type))) == NULLPTR(type) \
? (DBUG(("%s: "#ptr" -- ", "LZC")), NOMEM) : OK \ ? (DBUG(("%s: "#ptr" -- ", "LZC")), NOMEM) : OK \
) )
#else #else
#define allocx(type,ptr,size) \ #define allocx(type,ptr,size) \
(((ptr) = (type FAR *) Nu_LZC_emalloc(pArchive, (unsigned int)(size),sizeof(type))) == NULLPTR(type) \ (((ptr) = (type FAR *) Nu_LZC_emalloc(pArchive, (uint32_t)(size),sizeof(type))) == NULLPTR(type) \
? NOMEM : OK \ ? NOMEM : OK \
) )
#endif #endif
#else #else
#define allocx(type,ptr,size) \ #define allocx(type,ptr,size) \
(((ptr) = (type FAR *) Nu_LZC_emalloc(pArchive, (unsigned int)(size),sizeof(type))) == NULLPTR(type) \ (((ptr) = (type FAR *) Nu_LZC_emalloc(pArchive, (uint32_t)(size),sizeof(type))) == NULLPTR(type) \
? NOMEM : OK \ ? NOMEM : OK \
) )
#endif #endif
@ -300,8 +300,8 @@ static CONST INTCODE gNu_mc[] = {
#endif #endif
static int static int Nu_LZC_alloc_tables(LZCState* pLzcState, INTCODE newmaxcode,
Nu_LZC_alloc_tables(LZCState* pLzcState, INTCODE newmaxcode, HASH newhashsize) HASH newhashsize)
{ {
NuArchive* pArchive = pLzcState->pArchive; NuArchive* pArchive = pLzcState->pArchive;
/*static INTCODE oldmaxcode = 0;*/ /*static INTCODE oldmaxcode = 0;*/
@ -421,8 +421,7 @@ Nu_LZC_alloc_tables(LZCState* pLzcState, INTCODE newmaxcode, HASH newhashsize)
* =========================================================================== * ===========================================================================
*/ */
static void static void Nu_prratio(long int num, long int den)
Nu_prratio(long int num, long int den)
{ {
register int q; /* Doesn't need to be long */ register int q; /* Doesn't need to be long */
@ -443,8 +442,7 @@ Nu_prratio(long int num, long int den)
/* table clear for block compress */ /* table clear for block compress */
/* this is for adaptive reset present in version 4.0 joe release */ /* this is for adaptive reset present in version 4.0 joe release */
/* DjG, sets it up and returns TRUE to compress and FALSE to not compress */ /* DjG, sets it up and returns TRUE to compress and FALSE to not compress */
static int static int Nu_LZC_cl_block(LZCState* pLzcState)
Nu_LZC_cl_block(LZCState* pLzcState)
{ {
register long int rat; register long int rat;
@ -486,8 +484,7 @@ Nu_LZC_cl_block(LZCState* pLzcState)
static CONST UCHAR gNu_rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff}; static CONST UCHAR gNu_rmask[9] = {0x00, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f, 0xff};
static void static void Nu_LZC_putcode(LZCState* pLzcState, INTCODE code, register int bits)
Nu_LZC_putcode(LZCState* pLzcState, INTCODE code, register int bits)
{ {
/*static int oldbits = 0;*/ /*static int oldbits = 0;*/
/*static UCHAR outbuf[MAXBITS];*/ /*static UCHAR outbuf[MAXBITS];*/
@ -554,11 +551,10 @@ Nu_LZC_putcode(LZCState* pLzcState, INTCODE code, register int bits)
* *
* Returns kNuLZCEOF as the value when we're out of data. * Returns kNuLZCEOF as the value when we're out of data.
*/ */
static NuError static NuError Nu_LZCGetcCRC(LZCState* pLzcState, int* pSym)
Nu_LZCGetcCRC(LZCState* pLzcState, int* pSym)
{ {
NuError err; NuError err;
uchar c; uint8_t c;
if (!pLzcState->uncompRemaining) { if (!pLzcState->uncompRemaining) {
*pSym = kNuLZCEOF; *pSym = kNuLZCEOF;
@ -579,15 +575,14 @@ Nu_LZCGetcCRC(LZCState* pLzcState, int* pSym)
/* /*
* compress stdin to stdout * compress stdin to stdout
*/ */
static void static void Nu_LZC_compress(LZCState* pLzcState, uint32_t* pDstLen)
Nu_LZC_compress(LZCState* pLzcState, ulong* pDstLen)
{ {
int c,adjbits; int c,adjbits;
register HASH hash; register HASH hash;
register INTCODE code; register INTCODE code;
HASH hashf[256]; HASH hashf[256];
Assert(pLzcState->outfp != nil); Assert(pLzcState->outfp != NULL);
pLzcState->maxcode = Maxcode(pLzcState->maxbits); pLzcState->maxcode = Maxcode(pLzcState->maxbits);
pLzcState->hashsize = Hashsize(pLzcState->maxbits); pLzcState->hashsize = Hashsize(pLzcState->maxbits);
@ -758,9 +753,8 @@ Nu_LZC_compress(LZCState* pLzcState, ulong* pDstLen)
/* /*
* NufxLib interface to LZC compression. * NufxLib interface to LZC compression.
*/ */
static NuError static NuError Nu_CompressLZC(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressLZC(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc, int maxbits)
ulong srcLen, ulong* pDstLen, ushort* pCrc, int maxbits)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
LZCState lzcState; LZCState lzcState;
@ -771,7 +765,7 @@ Nu_CompressLZC(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
lzcState.outfp = fp; lzcState.outfp = fp;
lzcState.uncompRemaining = srcLen; lzcState.uncompRemaining = srcLen;
if (pCrc == nil) { if (pCrc == NULL) {
lzcState.doCalcCRC = false; lzcState.doCalcCRC = false;
} else { } else {
lzcState.doCalcCRC = true; lzcState.doCalcCRC = true;
@ -800,22 +794,20 @@ Nu_CompressLZC(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
#endif #endif
free_array(char,lzcState.sfx, 256); free_array(char,lzcState.sfx, 256);
if (pCrc != nil) if (pCrc != NULL)
*pCrc = lzcState.crc; *pCrc = lzcState.crc;
return err; return err;
} }
NuError NuError Nu_CompressLZC12(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressLZC12(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc)
ulong srcLen, ulong* pDstLen, ushort* pCrc)
{ {
return Nu_CompressLZC(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, 12); return Nu_CompressLZC(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, 12);
} }
NuError NuError Nu_CompressLZC16(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressLZC16(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc)
ulong srcLen, ulong* pDstLen, ushort* pCrc)
{ {
return Nu_CompressLZC(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, 16); return Nu_CompressLZC(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, 16);
} }
@ -833,22 +825,20 @@ Nu_CompressLZC16(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
* *
* Returns kNuLZCEOF as the value when we're out of data. * Returns kNuLZCEOF as the value when we're out of data.
*/ */
static NuError static NuError Nu_LZCPutcCRC(LZCState* pLzcState, char c)
Nu_LZCPutcCRC(LZCState* pLzcState, char c)
{ {
NuError err; NuError err;
err = Nu_FunnelWrite(pLzcState->pArchive, pLzcState->pFunnel, err = Nu_FunnelWrite(pLzcState->pArchive, pLzcState->pFunnel,
(uchar*) &c, 1); (uint8_t*) &c, 1);
if (pLzcState->doCalcCRC) if (pLzcState->doCalcCRC)
pLzcState->crc = Nu_CalcCRC16(pLzcState->crc, (uchar*) &c, 1); pLzcState->crc = Nu_CalcCRC16(pLzcState->crc, (uint8_t*) &c, 1);
return err; return err;
} }
static int static int Nu_LZC_nextcode(LZCState* pLzcState, INTCODE* codeptr)
Nu_LZC_nextcode(LZCState* pLzcState, INTCODE* codeptr)
/* Get the next code from input and put it in *codeptr. /* Get the next code from input and put it in *codeptr.
* Return (TRUE) on success, or return (FALSE) on end-of-file. * Return (TRUE) on success, or return (FALSE) on end-of-file.
* Adapted from COMPRESS V4.0. * Adapted from COMPRESS V4.0.
@ -898,8 +888,7 @@ Nu_LZC_nextcode(LZCState* pLzcState, INTCODE* codeptr)
return (TRUE); return (TRUE);
} }
static void static void Nu_LZC_decompress(LZCState* pLzcState, uint32_t compressedLen)
Nu_LZC_decompress(LZCState* pLzcState, ulong compressedLen)
{ {
NuArchive* pArchive = pLzcState->pArchive; NuArchive* pArchive = pLzcState->pArchive;
register int i; register int i;
@ -911,7 +900,7 @@ Nu_LZC_decompress(LZCState* pLzcState, ulong compressedLen)
/*static*/ int maxtoklen = MAXTOKLEN; /*static*/ int maxtoklen = MAXTOKLEN;
int flags; int flags;
Assert(pLzcState->infp != nil); Assert(pLzcState->infp != NULL);
pLzcState->exit_stat = OK; pLzcState->exit_stat = OK;
@ -1060,9 +1049,8 @@ Nu_LZC_decompress(LZCState* pLzcState, ulong compressedLen)
/* /*
* NufxLib interface to LZC expansion. * NufxLib interface to LZC expansion.
*/ */
NuError NuError Nu_ExpandLZC(NuArchive* pArchive, const NuRecord* pRecord,
Nu_ExpandLZC(NuArchive* pArchive, const NuRecord* pRecord, const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc)
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
LZCState lzcState; LZCState lzcState;
@ -1072,7 +1060,7 @@ Nu_ExpandLZC(NuArchive* pArchive, const NuRecord* pRecord,
lzcState.infp = infp; lzcState.infp = infp;
lzcState.pFunnel = pFunnel; lzcState.pFunnel = pFunnel;
if (pCrc == nil) { if (pCrc == NULL) {
lzcState.doCalcCRC = false; lzcState.doCalcCRC = false;
} else { } else {
lzcState.doCalcCRC = true; lzcState.doCalcCRC = true;
@ -1098,7 +1086,7 @@ Nu_ExpandLZC(NuArchive* pArchive, const NuRecord* pRecord,
#endif #endif
free_array(char,lzcState.sfx, 256); free_array(char,lzcState.sfx, 256);
if (pCrc != nil) if (pCrc != NULL)
*pCrc = lzcState.crc; *pCrc = lzcState.crc;
return err; return err;
} }

View File

@ -119,17 +119,17 @@ static const int gNuBitMask[] = {
typedef struct LZWCompressState { typedef struct LZWCompressState {
NuArchive* pArchive; NuArchive* pArchive;
ushort entry[kNuLZWHashSize]; /* uint or ushort */ uint16_t entry[kNuLZWHashSize]; /* uint or ushort */
ushort prefix[kNuLZWMaxCode+1]; /* uint or ushort */ uint16_t prefix[kNuLZWMaxCode+1]; /* uint or ushort */
uchar suffix[kNuLZWMaxCode+1]; uint8_t suffix[kNuLZWMaxCode+1];
ushort hashFunc[kNuLZWHashFuncTblSize]; /* uint or ushort */ uint16_t hashFunc[kNuLZWHashFuncTblSize]; /* uint or ushort */
uchar inputBuf[kNuLZWBlockSize]; /* 4K of raw input */ uint8_t inputBuf[kNuLZWBlockSize]; /* 4K of raw input */
uchar rleBuf[kNuLZWBlockSize*2 + kNuSafetyPadding]; uint8_t rleBuf[kNuLZWBlockSize*2 + kNuSafetyPadding];
uchar lzwBuf[(kNuLZWBlockSize * 3) / 2 + kNuSafetyPadding]; uint8_t lzwBuf[(kNuLZWBlockSize * 3) / 2 + kNuSafetyPadding];
ushort chunkCrc; /* CRC for LZW/1 */ uint16_t chunkCrc; /* CRC for LZW/1 */
/* LZW/2 state variables */ /* LZW/2 state variables */
int nextFree; int nextFree;
@ -146,15 +146,14 @@ typedef struct LZWCompressState {
* the hash function. This way we don't have to re-create it for * the hash function. This way we don't have to re-create it for
* every file, or store it statically in the binary. * every file, or store it statically in the binary.
*/ */
static NuError static NuError Nu_AllocLZWCompressState(NuArchive* pArchive)
Nu_AllocLZWCompressState(NuArchive* pArchive)
{ {
NuError err; NuError err;
LZWCompressState* lzwState; LZWCompressState* lzwState;
int ic; int ic;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pArchive->lzwCompressState == nil); Assert(pArchive->lzwCompressState == NULL);
/* allocate the general-purpose compression buffer, if needed */ /* allocate the general-purpose compression buffer, if needed */
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
@ -162,7 +161,7 @@ Nu_AllocLZWCompressState(NuArchive* pArchive)
return err; return err;
pArchive->lzwCompressState = Nu_Malloc(pArchive, sizeof(LZWCompressState)); pArchive->lzwCompressState = Nu_Malloc(pArchive, sizeof(LZWCompressState));
if (pArchive->lzwCompressState == nil) if (pArchive->lzwCompressState == NULL)
return kNuErrMalloc; return kNuErrMalloc;
/* /*
@ -191,13 +190,12 @@ Nu_AllocLZWCompressState(NuArchive* pArchive)
* The RLE format is "<delim> <char> <count>", where count is zero-based * The RLE format is "<delim> <char> <count>", where count is zero-based
* (i.e. for three bytes we encode "2", allowing us to express 1-256). * (i.e. for three bytes we encode "2", allowing us to express 1-256).
*/ */
static NuError static NuError Nu_CompressBlockRLE(LZWCompressState* lzwState, int* pRLESize)
Nu_CompressBlockRLE(LZWCompressState* lzwState, int* pRLESize)
{ {
const uchar* inPtr = lzwState->inputBuf; const uint8_t* inPtr = lzwState->inputBuf;
const uchar* endPtr = inPtr + kNuLZWBlockSize; const uint8_t* endPtr = inPtr + kNuLZWBlockSize;
uchar* outPtr = lzwState->rleBuf; uint8_t* outPtr = lzwState->rleBuf;
uchar matchChar; uint8_t matchChar;
int matchCount; int matchCount;
while (inPtr < endPtr) { while (inPtr < endPtr) {
@ -258,10 +256,9 @@ Nu_CompressBlockRLE(LZWCompressState* lzwState, int* pRLESize)
/* /*
* Clear the LZW table. Also resets the LZW/2 state. * Clear the LZW table. Also resets the LZW/2 state.
*/ */
static void static void Nu_ClearLZWTable(LZWCompressState* lzwState)
Nu_ClearLZWTable(LZWCompressState* lzwState)
{ {
Assert(lzwState != nil); Assert(lzwState != NULL);
/*DBUG_LZW(("### clear table\n"));*/ /*DBUG_LZW(("### clear table\n"));*/
@ -296,11 +293,11 @@ Nu_ClearLZWTable(LZWCompressState* lzwState)
* *
* (Turning this into a macro might speed things up.) * (Turning this into a macro might speed things up.)
*/ */
static inline void static inline void Nu_LZWPutCode(uint8_t** pOutBuf, uint32_t prefixCode,
Nu_LZWPutCode(uchar** pOutBuf, ulong prefixCode, int codeBits, int* pAtBit) int codeBits, int* pAtBit)
{ {
int atBit = *pAtBit; int atBit = *pAtBit;
uchar* outBuf = *pOutBuf; uint8_t* outBuf = *pOutBuf;
/*DBUG_LZW(("### PUT: prefixCode=0x%04lx, codeBits=%d, atBit=%d\n", /*DBUG_LZW(("### PUT: prefixCode=0x%04lx, codeBits=%d, atBit=%d\n",
prefixCode, codeBits, atBit));*/ prefixCode, codeBits, atBit));*/
@ -313,20 +310,20 @@ Nu_LZWPutCode(uchar** pOutBuf, ulong prefixCode, int codeBits, int* pAtBit)
/* merge it with the buffer contents (if necessary) and write lo bits */ /* merge it with the buffer contents (if necessary) and write lo bits */
outBuf--; outBuf--;
*outBuf = (uchar)((*outBuf & gNuBitMask[atBit]) | prefixCode); *outBuf = (uint8_t)((*outBuf & gNuBitMask[atBit]) | prefixCode);
outBuf++; outBuf++;
} else { } else {
/* nothing to merge with; write lo byte at next posn and advance */ /* nothing to merge with; write lo byte at next posn and advance */
*outBuf++ = (uchar)prefixCode; *outBuf++ = (uint8_t)prefixCode;
} }
/* codes are at least 9 bits, so we know we have to write one more */ /* codes are at least 9 bits, so we know we have to write one more */
*outBuf++ = (uchar)(prefixCode >> 8); *outBuf++ = (uint8_t)(prefixCode >> 8);
/* in some cases, we may have to write yet another */ /* in some cases, we may have to write yet another */
atBit += codeBits; atBit += codeBits;
if (atBit > 16) if (atBit > 16)
*outBuf++ = (uchar)(prefixCode >> 16); *outBuf++ = (uint8_t)(prefixCode >> 16);
*pAtBit = atBit & 0x07; *pAtBit = atBit & 0x07;
*pOutBuf = outBuf; *pOutBuf = outBuf;
@ -353,23 +350,22 @@ Nu_LZWPutCode(uchar** pOutBuf, ulong prefixCode, int codeBits, int* pAtBit)
* "resetFix" logic in the expansion functions. Code 0x0101 is essentially * "resetFix" logic in the expansion functions. Code 0x0101 is essentially
* lost in this situation. * lost in this situation.
*/ */
static NuError static NuError Nu_CompressLZWBlock(LZWCompressState* lzwState,
Nu_CompressLZWBlock(LZWCompressState* lzwState, const uchar* inputBuf, const uint8_t* inputBuf, int inputCount, int* pOutputCount)
int inputCount, int* pOutputCount)
{ {
int nextFree, ic, atBit, codeBits; int nextFree, ic, atBit, codeBits;
int hash, hashDelta; int hash, hashDelta;
int prefixCode, code, highCode; int prefixCode, code, highCode;
const uchar* inputEnd = inputBuf + inputCount; const uint8_t* inputEnd = inputBuf + inputCount;
/* local copies of lzwState members, for speed */ /* local copies of lzwState members, for speed */
const ushort* pHashFunc = lzwState->hashFunc; const uint16_t* pHashFunc = lzwState->hashFunc;
ushort* pEntry = lzwState->entry; uint16_t* pEntry = lzwState->entry;
ushort* pPrefix = lzwState->prefix; uint16_t* pPrefix = lzwState->prefix;
uchar* pSuffix = lzwState->suffix; uint8_t* pSuffix = lzwState->suffix;
uchar* outBuf = lzwState->lzwBuf; uint8_t* outBuf = lzwState->lzwBuf;
Assert(lzwState != nil); Assert(lzwState != NULL);
Assert(inputBuf != nil); Assert(inputBuf != NULL);
Assert(inputCount > 0 && inputCount <= kNuLZWBlockSize); Assert(inputCount > 0 && inputCount <= kNuLZWBlockSize);
/* make sure nobody has been messing with the types */ /* make sure nobody has been messing with the types */
Assert(sizeof(pHashFunc[0]) == sizeof(lzwState->hashFunc[0])); Assert(sizeof(pHashFunc[0]) == sizeof(lzwState->hashFunc[0]));
@ -555,35 +551,34 @@ Nu_CompressLZWBlock(LZWCompressState* lzwState, const uchar* inputBuf,
* *
* On exit, the output file will be positioned past the last byte written. * On exit, the output file will be positioned past the last byte written.
*/ */
static NuError static NuError Nu_CompressLZW(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressLZW(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pThreadCrc, Boolean isType2)
ulong srcLen, ulong* pDstLen, ushort* pThreadCrc, Boolean isType2)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
LZWCompressState* lzwState; LZWCompressState* lzwState;
long initialOffset; long initialOffset;
const uchar* lzwInputBuf; const uint8_t* lzwInputBuf;
uint blockSize, rleSize, lzwSize; uint32_t blockSize, rleSize, lzwSize;
long compressedLen; long compressedLen;
Boolean keepLzw; Boolean keepLzw;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pStraw != nil); Assert(pStraw != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(srcLen > 0); Assert(srcLen > 0);
Assert(pDstLen != nil); Assert(pDstLen != NULL);
Assert(pThreadCrc != nil); Assert(pThreadCrc != NULL);
Assert(isType2 == true || isType2 == false); Assert(isType2 == true || isType2 == false);
/* /*
* Do some initialization and set-up. * Do some initialization and set-up.
*/ */
if (pArchive->lzwCompressState == nil) { if (pArchive->lzwCompressState == NULL) {
err = Nu_AllocLZWCompressState(pArchive); err = Nu_AllocLZWCompressState(pArchive);
BailError(err); BailError(err);
} }
Assert(pArchive->lzwCompressState != nil); Assert(pArchive->lzwCompressState != NULL);
Assert(pArchive->compBuf != nil); Assert(pArchive->compBuf != NULL);
lzwState = pArchive->lzwCompressState; lzwState = pArchive->lzwCompressState;
lzwState->pArchive = pArchive; lzwState->pArchive = pArchive;
@ -782,9 +777,8 @@ bail:
/* /*
* Compress ShrinkIt-style "LZW/1". * Compress ShrinkIt-style "LZW/1".
*/ */
NuError NuError Nu_CompressLZW1(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressLZW1(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc)
ulong srcLen, ulong* pDstLen, ushort* pCrc)
{ {
return Nu_CompressLZW(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, false); return Nu_CompressLZW(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, false);
} }
@ -792,9 +786,8 @@ Nu_CompressLZW1(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
/* /*
* Compress ShrinkIt-style "LZW/2". * Compress ShrinkIt-style "LZW/2".
*/ */
NuError NuError Nu_CompressLZW2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressLZW2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc)
ulong srcLen, ulong* pDstLen, ushort* pCrc)
{ {
return Nu_CompressLZW(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, true); return Nu_CompressLZW(pArchive, pStraw, fp, srcLen, pDstLen, pCrc, true);
} }
@ -813,21 +806,21 @@ Nu_CompressLZW2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
/* /*
* Static tables useful for bit manipulation. * Static tables useful for bit manipulation.
*/ */
static const uint gNuMaskTable[17] = { static const uint32_t gNuMaskTable[17] = {
0x0000, 0x01ff, 0x03ff, 0x03ff, 0x07ff, 0x07ff, 0x07ff, 0x07ff, 0x0000, 0x01ff, 0x03ff, 0x03ff, 0x07ff, 0x07ff, 0x07ff, 0x07ff,
0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff, 0x0fff,
0x0fff 0x0fff
}; };
/* convert high byte of "entry" into a bit width */ /* convert high byte of "entry" into a bit width */
static const uint gNuBitWidth[17] = { static const uint32_t gNuBitWidth[17] = {
8,9,10,10,11,11,11,11,12,12,12,12,12,12,12,12,12 8,9,10,10,11,11,11,11,12,12,12,12,12,12,12,12,12
}; };
/* entry in the trie */ /* entry in the trie */
typedef struct TableEntry { typedef struct TableEntry {
uchar ch; uint8_t ch;
uint prefix; uint32_t prefix;
} TableEntry; } TableEntry;
/* /*
@ -839,38 +832,38 @@ typedef struct LZWExpandState {
NuArchive* pArchive; NuArchive* pArchive;
TableEntry trie[4096-256]; /* holds from 9 bits to 12 bits */ TableEntry trie[4096-256]; /* holds from 9 bits to 12 bits */
uchar stack[kNuLZWBlockSize]; uint8_t stack[kNuLZWBlockSize];
uint entry; /* 16-bit index into table */ // some of these don't need to be 32 bits; they were "uint" before
uint oldcode; /* carryover state for LZW/2 */ uint32_t entry; /* 16-bit index into table */
uint incode; /* carryover state for LZW/2 */ uint32_t oldcode; /* carryover state for LZW/2 */
uint finalc; /* carryover state for LZW/2 */ uint32_t incode; /* carryover state for LZW/2 */
uint32_t finalc; /* carryover state for LZW/2 */
Boolean resetFix; /* work around an LZW/2 bug */ Boolean resetFix; /* work around an LZW/2 bug */
ushort chunkCrc; /* CRC we calculate for LZW/1 */ uint16_t chunkCrc; /* CRC we calculate for LZW/1 */
ushort fileCrc; /* CRC stored with file */ uint16_t fileCrc; /* CRC stored with file */
uchar diskVol; /* disk volume # */ uint8_t diskVol; /* disk volume # */
uchar rleEscape; /* RLE escape char, usually 0xdb */ uint8_t rleEscape; /* RLE escape char, usually 0xdb */
ulong dataInBuffer; /* #of bytes in compBuf */ uint32_t dataInBuffer; /* #of bytes in compBuf */
uchar* dataPtr; /* current data offset */ uint8_t* dataPtr; /* current data offset */
uchar lzwOutBuf[kNuLZWBlockSize + kNuSafetyPadding]; uint8_t lzwOutBuf[kNuLZWBlockSize + kNuSafetyPadding];
uchar rleOutBuf[kNuLZWBlockSize + kNuSafetyPadding]; uint8_t rleOutBuf[kNuLZWBlockSize + kNuSafetyPadding];
} LZWExpandState; } LZWExpandState;
/* /*
* Allocate some "reusable" state for LZW expansion. * Allocate some "reusable" state for LZW expansion.
*/ */
static NuError static NuError Nu_AllocLZWExpandState(NuArchive* pArchive)
Nu_AllocLZWExpandState(NuArchive* pArchive)
{ {
NuError err; NuError err;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pArchive->lzwExpandState == nil); Assert(pArchive->lzwExpandState == NULL);
/* allocate the general-purpose compression buffer, if needed */ /* allocate the general-purpose compression buffer, if needed */
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
@ -878,7 +871,7 @@ Nu_AllocLZWExpandState(NuArchive* pArchive)
return err; return err;
pArchive->lzwExpandState = Nu_Malloc(pArchive, sizeof(LZWExpandState)); pArchive->lzwExpandState = Nu_Malloc(pArchive, sizeof(LZWExpandState));
if (pArchive->lzwExpandState == nil) if (pArchive->lzwExpandState == NULL)
return kNuErrMalloc; return kNuErrMalloc;
return kNuErrNone; return kNuErrNone;
} }
@ -896,8 +889,8 @@ Nu_AllocLZWExpandState(NuArchive* pArchive)
( Nu_LZWPopCheck(lzwState, stackPtr), *(--stackPtr) ) ( Nu_LZWPopCheck(lzwState, stackPtr), *(--stackPtr) )
# define Nu_LZWStackEmpty() ( stackPtr == lzwState->stack ) # define Nu_LZWStackEmpty() ( stackPtr == lzwState->stack )
static inline void static inline void Nu_LZWPushCheck(uint8_t uch, const LZWExpandState* lzwState,
Nu_LZWPushCheck(uchar uch, const LZWExpandState* lzwState,const uchar* stackPtr) const uint8_t* stackPtr)
{ {
if (stackPtr >= lzwState->stack + sizeof(lzwState->stack)) { if (stackPtr >= lzwState->stack + sizeof(lzwState->stack)) {
Nu_ReportError(lzwState->NU_BLOB, kNuErrBadData, "stack overflow"); Nu_ReportError(lzwState->NU_BLOB, kNuErrBadData, "stack overflow");
@ -905,8 +898,8 @@ Nu_LZWPushCheck(uchar uch, const LZWExpandState* lzwState,const uchar* stackPtr)
} }
} }
static inline void static inline void Nu_LZWPopCheck(const LZWExpandState* lzwState,
Nu_LZWPopCheck(const LZWExpandState* lzwState, const uchar* stackPtr) const uint8_t* stackPtr)
{ {
if (stackPtr == lzwState->stack) { if (stackPtr == lzwState->stack) {
Nu_ReportError(lzwState->NU_BLOB, kNuErrBadData, "stack underflow"); Nu_ReportError(lzwState->NU_BLOB, kNuErrBadData, "stack underflow");
@ -927,13 +920,11 @@ Nu_LZWPopCheck(const LZWExpandState* lzwState, const uchar* stackPtr)
* *
* (Turning this into a macro might speed things up.) * (Turning this into a macro might speed things up.)
*/ */
static inline uint static inline uint32_t Nu_LZWGetCode(const uint8_t** pInBuf, uint32_t entry,
Nu_LZWGetCode(const uchar** pInBuf, uint entry, int* pAtBit, uint* pLastByte) int* pAtBit, uint32_t* pLastByte)
{ {
uint numBits, startBit, lastBit; uint32_t numBits, startBit, lastBit;
ulong value; uint32_t value;
Assert(sizeof(uint) >= 2);
numBits = (entry +1) >> 8; /* bit-width of next code */ numBits = (entry +1) >> 8; /* bit-width of next code */
startBit = *pAtBit; startBit = *pAtBit;
@ -952,7 +943,7 @@ Nu_LZWGetCode(const uchar** pInBuf, uint entry, int* pAtBit, uint* pLastByte)
/* need two more bytes */ /* need two more bytes */
value |= *(*pInBuf)++ << 8; value |= *(*pInBuf)++ << 8;
*pLastByte = *(*pInBuf)++; *pLastByte = *(*pInBuf)++;
value |= (ulong) *pLastByte << 16; value |= (uint32_t) *pLastByte << 16;
} else { } else {
/* only need one more byte */ /* only need one more byte */
*pLastByte = *(*pInBuf)++; *pLastByte = *(*pInBuf)++;
@ -977,20 +968,19 @@ Nu_LZWGetCode(const uchar** pInBuf, uint entry, int* pAtBit, uint* pLastByte)
* *
* Reads from lzwState->dataPtr, writes to lzwState->lzwOutBuf. * Reads from lzwState->dataPtr, writes to lzwState->lzwOutBuf.
*/ */
static NuError static NuError Nu_ExpandLZW1(LZWExpandState* lzwState, uint32_t expectedLen)
Nu_ExpandLZW1(LZWExpandState* lzwState, uint expectedLen)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
TableEntry* tablePtr; TableEntry* tablePtr;
int atBit; int atBit;
uint entry, oldcode, incode, ptr; uint32_t entry, oldcode, incode, ptr;
uint lastByte, finalc; uint32_t lastByte, finalc;
const uchar* inbuf; const uint8_t* inbuf;
uchar* outbuf; uint8_t* outbuf;
uchar* outbufend; uint8_t* outbufend;
uchar* stackPtr; uint8_t* stackPtr;
Assert(lzwState != nil); Assert(lzwState != NULL);
Assert(expectedLen > 0 && expectedLen <= kNuLZWBlockSize); Assert(expectedLen > 0 && expectedLen <= kNuLZWBlockSize);
inbuf = lzwState->dataPtr; inbuf = lzwState->dataPtr;
@ -1024,7 +1014,7 @@ Nu_ExpandLZW1(LZWExpandState* lzwState, uint expectedLen)
err = kNuErrBadData; err = kNuErrBadData;
return err; return err;
} }
Nu_LZWPush((uchar)finalc); Nu_LZWPush((uint8_t)finalc);
ptr = oldcode; ptr = oldcode;
} }
@ -1062,7 +1052,7 @@ bail:
/* adjust input buffer */ /* adjust input buffer */
lzwState->dataInBuffer -= (inbuf - lzwState->dataPtr); lzwState->dataInBuffer -= (inbuf - lzwState->dataPtr);
Assert(lzwState->dataInBuffer < 32767*65536); Assert(lzwState->dataInBuffer < 32767*65536);
lzwState->dataPtr = (uchar*)inbuf; lzwState->dataPtr = (uint8_t*)inbuf;
return err; return err;
} }
@ -1077,24 +1067,23 @@ bail:
* In some cases, "expectedInputUsed" will be -1 to indicate that the * In some cases, "expectedInputUsed" will be -1 to indicate that the
* value is not known. * value is not known.
*/ */
static NuError static NuError Nu_ExpandLZW2(LZWExpandState* lzwState, uint32_t expectedLen,
Nu_ExpandLZW2(LZWExpandState* lzwState, uint expectedLen, uint32_t expectedInputUsed)
uint expectedInputUsed)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
TableEntry* tablePtr; TableEntry* tablePtr;
int atBit; int atBit;
uint entry, oldcode, incode, ptr; uint32_t entry, oldcode, incode, ptr;
uint lastByte, finalc; uint32_t lastByte, finalc;
const uchar* inbuf; const uint8_t* inbuf;
const uchar* inbufend; const uint8_t* inbufend;
uchar* outbuf; uint8_t* outbuf;
uchar* outbufend; uint8_t* outbufend;
uchar* stackPtr; uint8_t* stackPtr;
/*DBUG_LZW(("### LZW/2 block start (compIn=%d, rleOut=%d, entry=0x%04x)\n", /*DBUG_LZW(("### LZW/2 block start (compIn=%d, rleOut=%d, entry=0x%04x)\n",
expectedInputUsed, expectedLen, lzwState->entry));*/ expectedInputUsed, expectedLen, lzwState->entry));*/
Assert(lzwState != nil); Assert(lzwState != NULL);
Assert(expectedLen > 0 && expectedLen <= kNuLZWBlockSize); Assert(expectedLen > 0 && expectedLen <= kNuLZWBlockSize);
inbuf = lzwState->dataPtr; inbuf = lzwState->dataPtr;
@ -1171,7 +1160,7 @@ main_loop:
err = kNuErrBadData; err = kNuErrBadData;
return err; return err;
} }
Nu_LZWPush((uchar)finalc); Nu_LZWPush((uint8_t)finalc);
ptr = oldcode; ptr = oldcode;
} }
@ -1203,7 +1192,7 @@ main_loop:
bail: bail:
/*DBUG_LZW(("### end of block\n"));*/ /*DBUG_LZW(("### end of block\n"));*/
if (expectedInputUsed != (unsigned int) -1 && inbuf != inbufend) { if (expectedInputUsed != (uint32_t) -1 && inbuf != inbufend) {
/* data was corrupted; if we keep going this will get worse */ /* data was corrupted; if we keep going this will get worse */
DBUG(("--- inbuf != inbufend in ExpandLZW2 (diff=%d)\n", DBUG(("--- inbuf != inbufend in ExpandLZW2 (diff=%d)\n",
inbufend - inbuf)); inbufend - inbuf));
@ -1215,7 +1204,7 @@ bail:
/* adjust input buffer */ /* adjust input buffer */
lzwState->dataInBuffer -= (inbuf - lzwState->dataPtr); lzwState->dataInBuffer -= (inbuf - lzwState->dataPtr);
Assert(lzwState->dataInBuffer < 32767*65536); Assert(lzwState->dataInBuffer < 32767*65536);
lzwState->dataPtr = (uchar*)inbuf; lzwState->dataPtr = (uint8_t*)inbuf;
/* save off local copies of stuff */ /* save off local copies of stuff */
lzwState->entry = entry; lzwState->entry = entry;
@ -1230,15 +1219,14 @@ bail:
/* /*
* Expands a chunk of RLEd data into 4K of output. * Expands a chunk of RLEd data into 4K of output.
*/ */
static NuError static NuError Nu_ExpandRLE(LZWExpandState* lzwState, const uint8_t* inbuf,
Nu_ExpandRLE(LZWExpandState* lzwState, const uchar* inbuf, uint32_t expectedInputUsed)
uint expectedInputUsed)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
uchar *outbuf; uint8_t *outbuf;
uchar *outbufend; uint8_t *outbufend;
const uchar *inbufend; const uint8_t *inbufend;
uchar uch, rleEscape; uint8_t uch, rleEscape;
int count; int count;
outbuf = lzwState->rleOutBuf; outbuf = lzwState->rleOutBuf;
@ -1284,8 +1272,7 @@ bail:
/* /*
* Utility function to get a byte from the input buffer. * Utility function to get a byte from the input buffer.
*/ */
static inline uchar static inline uint8_t Nu_GetHeaderByte(LZWExpandState* lzwState)
Nu_GetHeaderByte(LZWExpandState* lzwState)
{ {
lzwState->dataInBuffer--; lzwState->dataInBuffer--;
Assert(lzwState->dataInBuffer > 0); Assert(lzwState->dataInBuffer > 0);
@ -1298,33 +1285,33 @@ Nu_GetHeaderByte(LZWExpandState* lzwState)
* This manages the input data buffer, passing chunks of compressed data * This manages the input data buffer, passing chunks of compressed data
* into the appropriate expansion function. * into the appropriate expansion function.
* *
* Pass in nil for "pThreadCrc" if no thread CRC is desired. Otherwise, * Pass in NULL for "pThreadCrc" if no thread CRC is desired. Otherwise,
* "*pThreadCrc" should already be set to its initial value. On exit it * "*pThreadCrc" should already be set to its initial value. On exit it
* will contain the CRC of the uncompressed data. * will contain the CRC of the uncompressed data.
*/ */
NuError NuError Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord, const NuThread* pThread, FILE* infp, NuFunnel* pFunnel,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pThreadCrc) uint16_t* pThreadCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
Boolean isType2; Boolean isType2;
LZWExpandState* lzwState; LZWExpandState* lzwState;
ulong compRemaining, uncompRemaining, minSize; uint32_t compRemaining, uncompRemaining, minSize;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(infp != nil); Assert(infp != NULL);
Assert(pFunnel != nil); Assert(pFunnel != NULL);
/* /*
* Do some initialization and set-up. * Do some initialization and set-up.
*/ */
if (pArchive->lzwExpandState == nil) { if (pArchive->lzwExpandState == NULL) {
err = Nu_AllocLZWExpandState(pArchive); err = Nu_AllocLZWExpandState(pArchive);
BailError(err); BailError(err);
} }
Assert(pArchive->lzwExpandState != nil); Assert(pArchive->lzwExpandState != NULL);
Assert(pArchive->compBuf != nil); Assert(pArchive->compBuf != NULL);
lzwState = pArchive->lzwExpandState; lzwState = pArchive->lzwExpandState;
lzwState->pArchive = pArchive; lzwState->pArchive = pArchive;
@ -1368,7 +1355,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
compRemaining -= 2; compRemaining -= 2;
lzwState->dataInBuffer = 0; lzwState->dataInBuffer = 0;
lzwState->dataPtr = nil; lzwState->dataPtr = NULL;
/* reset pointers */ /* reset pointers */
lzwState->entry = kNuLZWFirstCode; /* 0x0101 */ lzwState->entry = kNuLZWFirstCode; /* 0x0101 */
@ -1396,11 +1383,11 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
while (uncompRemaining) { while (uncompRemaining) {
Boolean rleUsed; Boolean rleUsed;
Boolean lzwUsed; Boolean lzwUsed;
ulong getSize; uint32_t getSize;
uint rleLen; /* length after RLE; 4096 if no RLE */ uint32_t rleLen; /* length after RLE; 4096 if no RLE */
uint lzwLen = 0; /* type 2 only */ uint32_t lzwLen = 0; /* type 2 only */
uint writeLen, inCount; uint32_t writeLen, inCount;
const uchar* writeBuf; const uint8_t* writeBuf;
/* if we're low, and there's more data available, read more */ /* if we're low, and there's more data available, read more */
if (lzwState->dataInBuffer < kNuLZWDesiredChunk && compRemaining) { if (lzwState->dataInBuffer < kNuLZWDesiredChunk && compRemaining) {
@ -1409,7 +1396,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
* the buffer. * the buffer.
*/ */
if (lzwState->dataInBuffer) { if (lzwState->dataInBuffer) {
Assert(lzwState->dataPtr != nil); Assert(lzwState->dataPtr != NULL);
Assert(pArchive->compBuf != lzwState->dataPtr); Assert(pArchive->compBuf != lzwState->dataPtr);
memmove(pArchive->compBuf, lzwState->dataPtr, memmove(pArchive->compBuf, lzwState->dataPtr,
lzwState->dataInBuffer); lzwState->dataInBuffer);
@ -1429,7 +1416,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
getSize); getSize);
if (err != kNuErrNone) { if (err != kNuErrNone) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"failed reading compressed data (%ld bytes)", getSize); "failed reading compressed data (%u bytes)", getSize);
goto bail; goto bail;
} }
lzwState->dataInBuffer += getSize; lzwState->dataInBuffer += getSize;
@ -1476,7 +1463,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
writeLen = kNuLZWBlockSize; writeLen = kNuLZWBlockSize;
#ifndef NDEBUG #ifndef NDEBUG
writeBuf = nil; writeBuf = NULL;
#endif #endif
/* /*
@ -1491,7 +1478,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
} else { } else {
if (pRecord->isBadMac || pArchive->valIgnoreLZW2Len) { if (pRecord->isBadMac || pArchive->valIgnoreLZW2Len) {
/* might be big-endian, might be okay; just ignore it */ /* might be big-endian, might be okay; just ignore it */
lzwLen = (unsigned int) -1; lzwLen = (uint32_t) -1;
} else if (lzwState->dataInBuffer < lzwLen) { } else if (lzwState->dataInBuffer < lzwLen) {
/* rare -- GSHK will do this if you don't let it finish */ /* rare -- GSHK will do this if you don't let it finish */
err = kNuErrBufferUnderrun; err = kNuErrBufferUnderrun;
@ -1537,7 +1524,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
lzwState->resetFix = false; lzwState->resetFix = false;
} }
Assert(writeBuf != nil); Assert(writeBuf != NULL);
/* /*
* Compute the CRC of the uncompressed data, and write it. For * Compute the CRC of the uncompressed data, and write it. For
@ -1547,7 +1534,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
* See commentary in the compression code for why we have to * See commentary in the compression code for why we have to
* compute two CRCs for LZW/1. * compute two CRCs for LZW/1.
*/ */
if (pThreadCrc != nil) { if (pThreadCrc != NULL) {
*pThreadCrc = Nu_CalcCRC16(*pThreadCrc, writeBuf, writeLen); *pThreadCrc = Nu_CalcCRC16(*pThreadCrc, writeBuf, writeLen);
} }
if (!isType2) { if (!isType2) {
@ -1590,7 +1577,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
DBUG(("--- Found %ld bytes following compressed data (compRem=%ld)\n", DBUG(("--- Found %ld bytes following compressed data (compRem=%ld)\n",
lzwState->dataInBuffer, compRemaining)); lzwState->dataInBuffer, compRemaining));
if (lzwState->dataInBuffer > 32) { if (lzwState->dataInBuffer > 32) {
Nu_ReportError(NU_BLOB, kNuErrNone, "(Warning) lots of fluff (%ld)", Nu_ReportError(NU_BLOB, kNuErrNone, "(Warning) lots of fluff (%u)",
lzwState->dataInBuffer); lzwState->dataInBuffer);
} }
} }
@ -1602,7 +1589,7 @@ Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
if (compRemaining) { if (compRemaining) {
err = kNuErrBadData; err = kNuErrBadData;
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"not all compressed data was used (%ld/%ld)", "not all compressed data was used (%u/%u)",
compRemaining, lzwState->dataInBuffer); compRemaining, lzwState->dataInBuffer);
goto bail; goto bail;
} }

View File

@ -12,6 +12,9 @@
# #
# The shared library support currently leaves much to be desired. # The shared library support currently leaves much to be desired.
# #
# If you build with -DDEBUG_MSGS, nulib2 will be able to use the hidden
# 'g' command, which generates a verbose archive dump for debugging.
#
# NufxLib install location. # NufxLib install location.
prefix = @prefix@ prefix = @prefix@
@ -33,12 +36,12 @@ OPT = @CFLAGS@
GCC_FLAGS = -Wall -Wwrite-strings -Wstrict-prototypes -Wpointer-arith -Wshadow GCC_FLAGS = -Wall -Wwrite-strings -Wstrict-prototypes -Wpointer-arith -Wshadow
CFLAGS = @BUILD_FLAGS@ -I. @DEFS@ -DOPTFLAGSTR="\"$(OPT)\"" CFLAGS = @BUILD_FLAGS@ -I. @DEFS@ -DOPTFLAGSTR="\"$(OPT)\""
SRCS = Archive.c ArchiveIO.c Bzip2.c Compress.c Crc16.c Debug.c \ SRCS = Archive.c ArchiveIO.c Bzip2.c Charset.c Compress.c Crc16.c \
Deferred.c Deflate.c Entry.c Expand.c FileIO.c Funnel.c \ Debug.c Deferred.c Deflate.c Entry.c Expand.c FileIO.c Funnel.c \
Lzc.c Lzw.c MiscStuff.c MiscUtils.c Record.c SourceSink.c \ Lzc.c Lzw.c MiscStuff.c MiscUtils.c Record.c SourceSink.c \
Squeeze.c Thread.c Value.c Version.c Squeeze.c Thread.c Value.c Version.c
OBJS = Archive.o ArchiveIO.o Bzip2.o Compress.o Crc16.o Debug.o \ OBJS = Archive.o ArchiveIO.o Bzip2.o Charset.o Compress.o Crc16.o \
Deferred.o Deflate.o Entry.o Expand.o FileIO.o Funnel.o \ Debug.o Deferred.o Deflate.o Entry.o Expand.o FileIO.o Funnel.o \
Lzc.o Lzw.o MiscStuff.o MiscUtils.o Record.o SourceSink.o \ Lzc.o Lzw.o MiscStuff.o MiscUtils.o Record.o SourceSink.o \
Squeeze.o Thread.o Value.o Version.o Squeeze.o Thread.o Value.o Version.o
@ -79,7 +82,7 @@ $(STATIC_PRODUCT): $(OBJS)
$(AR) $@ $(OBJS) $(AR) $@ $(OBJS)
@RANLIB@ $@ @RANLIB@ $@
# BUG: we probably want -fPIC -D_REENTRANT on the compile lines for this. # BUG: we need -fPIC, maybe -D_REENTRANT when compiling for this.
# BUG: for Linux we may want -Wl,-soname,libnufx.so.1 on the link line. # BUG: for Linux we may want -Wl,-soname,libnufx.so.1 on the link line.
$(SHARED_PRODUCT): $(OBJS) $(SHARED_PRODUCT): $(OBJS)
-rm -f $(STATIC_PRODUCT) $(SHARED_PRODUCT) -rm -f $(STATIC_PRODUCT) $(SHARED_PRODUCT)
@ -97,7 +100,6 @@ tags::
distclean: clean distclean: clean
(cd samples; make distclean) (cd samples; make distclean)
-rm -f Version.c
-rm -f Makefile Makefile.bak -rm -f Makefile Makefile.bak
-rm -f config.log config.cache config.status config.h -rm -f config.log config.cache config.status config.h
-rm -f tags -rm -f tags
@ -111,12 +113,29 @@ baktar:
@gzip -9 nufxlib.tar @gzip -9 nufxlib.tar
@mv -i nufxlib.tar.gz /home/fadden/BAK/ @mv -i nufxlib.tar.gz /home/fadden/BAK/
depend: # dependency info
makedepend -- $(CFLAGS) -I/usr/local/include -- $(SRCS) COMMON_HDRS = NufxLibPriv.h NufxLib.h MiscStuff.h SysDefs.h
@(cd samples; unset CFLAGS OBJS; @SET_MAKE@ $(MAKE) depend) Archive.o: Archive.c $(COMMON_HDRS)
ArchiveIO.o: ArchiveIO.c $(COMMON_HDRS)
# catch OPTFLAGSTR updates Bzip2.o: Bzip2.c $(COMMON_HDRS)
Version.o: Makefile Charset.o: Charset.c $(COMMON_HDRS)
Compress.o: Compress.c $(COMMON_HDRS)
# DO NOT DELETE THIS LINE -- make depend depends on it. Crc16.o: Crc16.c $(COMMON_HDRS)
Debug.o: Debug.c $(COMMON_HDRS)
Deferred.o: Deferred.c $(COMMON_HDRS)
Deflate.o: Deflate.c $(COMMON_HDRS)
Entry.o: Entry.c $(COMMON_HDRS)
Expand.o: Expand.c $(COMMON_HDRS)
FileIO.o: FileIO.c $(COMMON_HDRS)
Funnel.o: Funnel.c $(COMMON_HDRS)
Lzc.o: Lzc.c $(COMMON_HDRS)
Lzw.o: Lzw.c $(COMMON_HDRS)
MiscStuff.o: MiscStuff.c $(COMMON_HDRS)
MiscUtils.o: MiscUtils.c $(COMMON_HDRS)
Record.o: Record.c $(COMMON_HDRS)
SourceSink.o: SourceSink.c $(COMMON_HDRS)
Squeeze.o: Squeeze.c $(COMMON_HDRS)
Thread.o: Thread.c $(COMMON_HDRS)
Value.o: Value.c $(COMMON_HDRS)
Version.o: Version.c $(COMMON_HDRS) Makefile

View File

@ -65,16 +65,16 @@ LDFLAGS = $(LDFLAGS) zlib.lib
# object files # object files
OBJS = Archive.obj ArchiveIO.obj Bzip2.obj Compress.obj Crc16.obj Debug.obj \ OBJS = Archive.obj ArchiveIO.obj Bzip2.obj Charset.obj Compress.obj \
Deferred.obj Deflate.obj Entry.obj Expand.obj FileIO.obj Funnel.obj \ Crc16.obj Debug.obj Deferred.obj Deflate.obj Entry.obj Expand.obj \
Lzc.obj Lzw.obj MiscStuff.obj MiscUtils.obj Record.obj SourceSink.obj \ FileIO.obj Funnel.obj Lzc.obj Lzw.obj MiscStuff.obj MiscUtils.obj \
Squeeze.obj Thread.obj Value.obj Version.obj Record.obj SourceSink.obj Squeeze.obj Thread.obj Value.obj Version.obj
# build targets -- static library, dynamic library, and test programs # build targets -- static library, dynamic library, and test programs
all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) \ all: $(STATICLIB) $(SHAREDLIB) $(IMPLIB) \
exerciser.exe imgconv.exe launder.exe test-basic.exe \ exerciser.exe imgconv.exe launder.exe test-basic.exe test-basic-d.exe \
test-basic-d.exe test-extract.exe test-simple.exe test-twirl.exe test-extract.exe test-names.exe test-simple.exe test-twirl.exe
clean: clean:
-del *.obj *.pdb *.exp -del *.obj *.pdb *.exp
@ -107,6 +107,9 @@ test-basic-d.exe: TestBasic.obj $(IMPLIB)
test-extract.exe: TestExtract.obj $(STATICLIB) test-extract.exe: TestExtract.obj $(STATICLIB)
$(LD) $(LDFLAGS) -out:$@ TestExtract.obj $(STATICLIB) $(LD) $(LDFLAGS) -out:$@ TestExtract.obj $(STATICLIB)
test-names.exe: TestNames.obj $(STATICLIB)
$(LD) $(LDFLAGS) -out:$@ TestNames.obj $(STATICLIB)
test-simple.exe: TestSimple.obj $(STATICLIB) test-simple.exe: TestSimple.obj $(STATICLIB)
$(LD) $(LDFLAGS) -out:$@ TestSimple.obj $(STATICLIB) $(LD) $(LDFLAGS) -out:$@ TestSimple.obj $(STATICLIB)
@ -125,6 +128,7 @@ COMMON_HDRS = NufxLibPriv.h NufxLib.h MiscStuff.h SysDefs.h
Archive.obj: Archive.c $(COMMON_HDRS) Archive.obj: Archive.c $(COMMON_HDRS)
ArchiveIO.obj: ArchiveIO.c $(COMMON_HDRS) ArchiveIO.obj: ArchiveIO.c $(COMMON_HDRS)
Bzip2.obj: Bzip2.c $(COMMON_HDRS) Bzip2.obj: Bzip2.c $(COMMON_HDRS)
Charset.obj: Charset.c $(COMMON_HDRS)
Compress.obj: Compress.c $(COMMON_HDRS) Compress.obj: Compress.c $(COMMON_HDRS)
Crc16.obj: Crc16.c $(COMMON_HDRS) Crc16.obj: Crc16.c $(COMMON_HDRS)
Debug.obj: Debug.c $(COMMON_HDRS) Debug.obj: Debug.c $(COMMON_HDRS)
@ -150,6 +154,7 @@ ImgConv.obj: samples/ImgConv.c $(COMMON_HDRS)
Launder.obj: samples/Launder.c $(COMMON_HDRS) Launder.obj: samples/Launder.c $(COMMON_HDRS)
TestBasic.obj: samples/TestBasic.c $(COMMON_HDRS) TestBasic.obj: samples/TestBasic.c $(COMMON_HDRS)
TestExtract.obj: samples/TestExtract.c $(COMMON_HDRS) TestExtract.obj: samples/TestExtract.c $(COMMON_HDRS)
TestNames.obj: samples/TestNames.c $(COMMON_HDRS)
TestSimple.obj: samples/TestSimple.c $(COMMON_HDRS) TestSimple.obj: samples/TestSimple.c $(COMMON_HDRS)
TestTwirl.obj: samples/TestTwirl.c $(COMMON_HDRS) TestTwirl.obj: samples/TestTwirl.c $(COMMON_HDRS)

View File

@ -16,8 +16,7 @@
* Return a pointer to the appropriate string in the system table, or NULL * Return a pointer to the appropriate string in the system table, or NULL
* if the value is out of bounds. * if the value is out of bounds.
*/ */
const char* const char* Nu_strerror(int errnum)
Nu_strerror(int errnum)
{ {
extern int sys_nerr; extern int sys_nerr;
extern char *sys_errlist[]; extern char *sys_errlist[];
@ -38,8 +37,7 @@ Nu_strerror(int errnum)
* from BSD, is available in the PGP 2.6.2 distribution, but this should * from BSD, is available in the PGP 2.6.2 distribution, but this should
* suffice for those few systems that don't have memmove. * suffice for those few systems that don't have memmove.
*/ */
void* void* Nu_memmove(void* dst, const void* src, size_t n)
Nu_memmove(void* dst, const void* src, size_t n)
{ {
void* retval = dst; void* retval = dst;
char* srcp = (char*)src; char* srcp = (char*)src;
@ -80,8 +78,7 @@ Nu_memmove(void* dst, const void* src, size_t n)
* For our purposes here, strtol does all we need it to. Someday * For our purposes here, strtol does all we need it to. Someday
* we should replace this with a "real" version. * we should replace this with a "real" version.
*/ */
unsigned long unsigned long Nu_strtoul(const char *nptr, char **endptr, int base)
Nu_strtoul(const char *nptr, char **endptr, int base)
{ {
return strtol(nptr, endptr, base); return strtol(nptr, endptr, base);
} }
@ -91,8 +88,7 @@ Nu_strtoul(const char *nptr, char **endptr, int base)
/* /*
* Compare two strings, case-insensitive. * Compare two strings, case-insensitive.
*/ */
int int Nu_strcasecmp(const char *str1, const char *str2)
Nu_strcasecmp(const char *str1, const char *str2)
{ {
while (*str1 && *str2 && toupper(*str1) == toupper(*str2)) while (*str1 && *str2 && toupper(*str1) == toupper(*str2))
str1++, str2++; str1++, str2++;
@ -105,8 +101,7 @@ Nu_strcasecmp(const char *str1, const char *str2)
/* /*
* Compare two strings, case-insensitive, stopping after "n" chars. * Compare two strings, case-insensitive, stopping after "n" chars.
*/ */
int int Nu_strncasecmp(const char *str1, const char *str2, size_t n)
Nu_strncasecmp(const char *str1, const char *str2, size_t n)
{ {
while (n && *str1 && *str2 && toupper(*str1) == toupper(*str2)) while (n && *str1 && *str2 && toupper(*str1) == toupper(*str2))
str1++, str2++, n--; str1++, str2++, n--;

View File

@ -6,8 +6,8 @@
* Misc stuff (shared between nufxlib and nulib2). This is a collection * Misc stuff (shared between nufxlib and nulib2). This is a collection
* of miscellaneous types and macros that I find generally useful. * of miscellaneous types and macros that I find generally useful.
*/ */
#ifndef __MiscStuff__ #ifndef NUFXLIB_MISCSTUFF_H
#define __MiscStuff__ #define NUFXLIB_MISCSTUFF_H
#define VALGRIND /* assume we're using it */ #define VALGRIND /* assume we're using it */
@ -42,11 +42,7 @@ int Nu_strncasecmp(const char *s1, const char *s2, size_t n);
* Misc types. * Misc types.
*/ */
#include <sys/types.h> typedef unsigned char Boolean;
#define nil NULL /* I can't seem to stop typing 'nil' now */
typedef uchar Boolean;
#define false (0) #define false (0)
#define true (!false) #define true (!false)
@ -63,7 +59,7 @@ typedef uchar Boolean;
(x) <= '9' ? (x) - '0' : toupper(x) +10 - 'A' ) (x) <= '9' ? (x) - '0' : toupper(x) +10 - 'A' )
/* convert number from 0-15 to hex digit */ /* convert number from 0-15 to hex digit */
#define HexConv(x) ( ((uint)(x)) <= 15 ? \ #define HexConv(x) ( ((unsigned int)(x)) <= 15 ? \
( (x) <= 9 ? (x) + '0' : (x) -10 + 'A') : -1 ) ( (x) <= 9 ? (x) + '0' : (x) -10 + 'A') : -1 )
@ -106,4 +102,4 @@ typedef uchar Boolean;
#define kInvalidPtr ((void*)0xa3a3a3a3) #define kInvalidPtr ((void*)0xa3a3a3a3)
#endif /*__MiscStuff__*/ #endif /*NUFXLIB_MISCSTUFF_H*/

View File

@ -6,13 +6,12 @@
* *
* Miscellaneous NufxLib utility functions. * Miscellaneous NufxLib utility functions.
*/ */
#define __MiscUtils_c__
#include "NufxLibPriv.h" #include "NufxLibPriv.h"
/* /*
* Big fat hairy global. Unfortunately this is unavoidable. * Big fat hairy global. Unfortunately this is unavoidable.
*/ */
NuCallback gNuGlobalErrorMessageHandler = nil; NuCallback gNuGlobalErrorMessageHandler = NULL;
static const char* kNufxLibName = "nufxlib"; static const char* kNufxLibName = "nufxlib";
@ -21,8 +20,7 @@ static const char* kNufxLibName = "nufxlib";
/* /*
* strerror() equivalent for NufxLib errors. * strerror() equivalent for NufxLib errors.
*/ */
const char* const char* Nu_StrError(NuError err)
Nu_StrError(NuError err)
{ {
/* /*
* BUG: this should be set up as per-thread storage in an MT environment. * BUG: this should be set up as per-thread storage in an MT environment.
@ -32,7 +30,7 @@ Nu_StrError(NuError err)
* to return this. * to return this.
* *
* An easier solution, should this present a problem for someone, would * An easier solution, should this present a problem for someone, would
* be to have the function return nil or "unknown error" when the * be to have the function return NULL or "unknown error" when the
* error value isn't recognized. I'd recommend leaving it as-is for * error value isn't recognized. I'd recommend leaving it as-is for
* debug builds, though, as it's helpful to know *which* error is not * debug builds, though, as it's helpful to know *which* error is not
* recognized. * recognized.
@ -200,15 +198,15 @@ Nu_StrError(NuError err)
* Similar to perror(), but takes the error as an argument, and knows * Similar to perror(), but takes the error as an argument, and knows
* about NufxLib errors as well as system errors. * about NufxLib errors as well as system errors.
* *
* Depending on the compiler, "file", "line", and "function" may be nil/zero. * Depending on the compiler, "file", "line", and "function" may be NULL/zero.
* *
* Calling here with "pArchive"==nil is allowed, but should only be done * Calling here with "pArchive"==NULL is allowed, but should only be done
* if the archive is inaccessible (perhaps because it failed to open). We * if the archive is inaccessible (perhaps because it failed to open). We
* can't invoke the error message callback if the pointer is nil. * can't invoke the error message callback if the pointer is NULL.
*/ */
void void Nu_ReportError(NuArchive* pArchive, const char* file, int line,
Nu_ReportError(NuArchive* pArchive, const char* file, int line, const char* function, Boolean isDebug, NuError err,
const char* function, Boolean isDebug, NuError err, const char* format, ...) const UNICHAR* format, ...)
{ {
NuErrorMessage errorMessage; NuErrorMessage errorMessage;
const char* msg; const char* msg;
@ -219,7 +217,7 @@ Nu_ReportError(NuArchive* pArchive, const char* file, int line,
int cc; int cc;
#endif #endif
Assert(format != nil); Assert(format != NULL);
va_start(args, format); va_start(args, format);
@ -247,28 +245,28 @@ Nu_ReportError(NuArchive* pArchive, const char* file, int line,
strcpy(buf+count, ": "); strcpy(buf+count, ": ");
count += 2; count += 2;
msg = nil; msg = NULL;
if (err >= 0) if (err >= 0)
msg = strerror(err); msg = strerror(err);
if (msg == nil) if (msg == NULL)
msg = Nu_StrError(err); msg = Nu_StrError(err);
#if defined(HAVE_SNPRINTF) && defined(SNPRINTF_DECLARED) #if defined(HAVE_SNPRINTF) && defined(SNPRINTF_DECLARED)
if (msg == nil) if (msg == NULL)
snprintf(buf+count, sizeof(buf) - count, snprintf(buf+count, sizeof(buf) - count,
"(unknown err=%d)", err); "(unknown err=%d)", err);
else else
snprintf(buf+count, sizeof(buf) - count, "%s", msg); snprintf(buf+count, sizeof(buf) - count, "%s", msg);
#else #else
#ifdef SPRINTF_RETURNS_INT #ifdef SPRINTF_RETURNS_INT
if (msg == nil) if (msg == NULL)
cc = sprintf(buf+count, "(unknown err=%d)", err); cc = sprintf(buf+count, "(unknown err=%d)", err);
else else
cc = sprintf(buf+count, "%s", msg); cc = sprintf(buf+count, "%s", msg);
Assert(cc > 0); Assert(cc > 0);
count += cc; count += cc;
#else #else
if (msg == nil) if (msg == NULL)
sprintf(buf+count, "(unknown err=%d)", err); sprintf(buf+count, "(unknown err=%d)", err);
else else
sprintf(buf+count, "%s", msg); sprintf(buf+count, "%s", msg);
@ -284,8 +282,8 @@ Nu_ReportError(NuArchive* pArchive, const char* file, int line,
Assert(count <= kNuHeftyBufSize); Assert(count <= kNuHeftyBufSize);
#endif #endif
if ((pArchive != nil && pArchive->messageHandlerFunc == nil) || if ((pArchive != NULL && pArchive->messageHandlerFunc == NULL) ||
(pArchive == nil && gNuGlobalErrorMessageHandler == nil)) (pArchive == NULL && gNuGlobalErrorMessageHandler == NULL))
{ {
if (isDebug) { if (isDebug) {
fprintf(stderr, "%s: [%s:%d %s] %s\n", kNufxLibName, fprintf(stderr, "%s: [%s:%d %s] %s\n", kNufxLibName,
@ -301,7 +299,7 @@ Nu_ReportError(NuArchive* pArchive, const char* file, int line,
errorMessage.line = line; errorMessage.line = line;
errorMessage.function = function; errorMessage.function = function;
if (pArchive == nil) if (pArchive == NULL)
(void) (*gNuGlobalErrorMessageHandler)(pArchive, &errorMessage); (void) (*gNuGlobalErrorMessageHandler)(pArchive, &errorMessage);
else else
(void) (*pArchive->messageHandlerFunc)(pArchive, &errorMessage); (void) (*pArchive->messageHandlerFunc)(pArchive, &errorMessage);
@ -322,48 +320,46 @@ bail:
*/ */
#ifndef USE_DMALLOC #ifndef USE_DMALLOC
void* void* Nu_Malloc(NuArchive* pArchive, size_t size)
Nu_Malloc(NuArchive* pArchive, size_t size)
{ {
void* _result; void* _result;
Assert(size > 0); Assert(size > 0);
_result = malloc(size); _result = malloc(size);
if (_result == nil) { if (_result == NULL) {
Nu_ReportError(NU_BLOB, kNuErrMalloc, "malloc(%u) failed", (uint) size); Nu_ReportError(NU_BLOB, kNuErrMalloc,
"malloc(%u) failed", (unsigned int) size);
DebugAbort(); /* leave a core dump if we're built for it */ DebugAbort(); /* leave a core dump if we're built for it */
} }
DebugFill(_result, size); DebugFill(_result, size);
return _result; return _result;
} }
void* void* Nu_Calloc(NuArchive* pArchive, size_t size)
Nu_Calloc(NuArchive* pArchive, size_t size)
{ {
void* _cresult = Nu_Malloc(pArchive, size); void* _cresult = Nu_Malloc(pArchive, size);
memset(_cresult, 0, size); memset(_cresult, 0, size);
return _cresult; return _cresult;
} }
void* void* Nu_Realloc(NuArchive* pArchive, void* ptr, size_t size)
Nu_Realloc(NuArchive* pArchive, void* ptr, size_t size)
{ {
void* _result; void* _result;
Assert(ptr != nil); /* disallow this usage */ Assert(ptr != NULL); /* disallow this usage */
Assert(size > 0); /* disallow this usage */ Assert(size > 0); /* disallow this usage */
_result = realloc(ptr, size); _result = realloc(ptr, size);
if (_result == nil) { if (_result == NULL) {
Nu_ReportError(NU_BLOB, kNuErrMalloc, "realloc(%u) failed",(uint) size); Nu_ReportError(NU_BLOB, kNuErrMalloc,
"realloc(%u) failed", (unsigned int) size);
DebugAbort(); /* leave a core dump if we're built for it */ DebugAbort(); /* leave a core dump if we're built for it */
} }
return _result; return _result;
} }
void void Nu_Free(NuArchive* pArchive, void* ptr)
Nu_Free(NuArchive* pArchive, void* ptr)
{ {
if (ptr != nil) if (ptr != NULL)
free(ptr); free(ptr);
} }
#endif #endif
@ -372,11 +368,10 @@ Nu_Free(NuArchive* pArchive, void* ptr)
* If somebody internal wants to set doClose on a buffer DataSource * If somebody internal wants to set doClose on a buffer DataSource
* (looks like "Rename" does), we need to supply a "free" callback. * (looks like "Rename" does), we need to supply a "free" callback.
*/ */
NuResult NuResult Nu_InternalFreeCallback(NuArchive* pArchive, void* args)
Nu_InternalFreeCallback(NuArchive* pArchive, void* args)
{ {
DBUG(("+++ internal free callback 0x%08lx\n", (long) args)); DBUG(("+++ internal free callback 0x%08lx\n", (long) args));
Nu_Free(nil, args); Nu_Free(NULL, args);
return kNuOK; return kNuOK;
} }

View File

@ -6,10 +6,11 @@
* *
* External interface (types, defines, and function prototypes). * External interface (types, defines, and function prototypes).
*/ */
#ifndef __NufxLib__ #ifndef NUFXLIB_NUFXLIB_H
#define __NufxLib__ #define NUFXLIB_NUFXLIB_H
#include <stdio.h> #include <stdio.h>
#include <stdint.h>
#ifdef __cplusplus #ifdef __cplusplus
@ -31,9 +32,9 @@ extern "C" {
* The "bug" version can usually be ignored, since it represents minor * The "bug" version can usually be ignored, since it represents minor
* fixes. Unless, of course, your code depends upon that fix. * fixes. Unless, of course, your code depends upon that fix.
*/ */
#define kNuVersionMajor 2 #define kNuVersionMajor 3
#define kNuVersionMinor 2 #define kNuVersionMinor 0
#define kNuVersionBug 2 #define kNuVersionBug 0
/* /*
@ -42,6 +43,33 @@ extern "C" {
* =========================================================================== * ===========================================================================
*/ */
/*
* Unicode character type. For Linux and Mac OS X, filenames use "narrow"
* characters and UTF-8 encoding, which allows them to use standard file I/O
* functions like fopen(). Windows uses UTF-16, which requires a different
* character type and an alternative set of I/O functions like _wfopen().
*
* The idea is that NufxLib API functions will operate on filenames with
* the OS dominant method, so on Windows the API accepts UTF-16. This
* definition is a bit like Windows TCHAR, but it's dependent on the OS, not
* on whether _MBCS or _UNICODE is defined.
*
* The app can include "Unichar.h" to get definitions for functions that
* switch between narrow and wide functions (e.g. "unistrlen()" becomes
* strlen() or wcslen() as appropriate).
*
* We switch based on _WIN32, because we're not really switching on
* filename-character size; the key issue is all the pesky wide I/O calls.
*/
#if defined(_WIN32)
// TODO: complete this
//# include <wchar.h>
//# define UNICHAR wchar_t
# define UNICHAR char
#else
# define UNICHAR char
#endif
/* /*
* Error values returned from functions. * Error values returned from functions.
* *
@ -148,27 +176,27 @@ typedef enum NuResult {
* NuRecordIdxs are assigned to records in an archive. You may assume that * NuRecordIdxs are assigned to records in an archive. You may assume that
* the values are unique, but that is all. * the values are unique, but that is all.
*/ */
typedef unsigned long NuRecordIdx; typedef uint32_t NuRecordIdx;
/* /*
* NuThreadIdxs are assigned to threads within a record. Again, you may * NuThreadIdxs are assigned to threads within a record. Again, you may
* assume that the values are unique within a record, but that is all. * assume that the values are unique within a record, but that is all.
*/ */
typedef unsigned long NuThreadIdx; typedef uint32_t NuThreadIdx;
/* /*
* Thread ID, a combination of thread_class and thread_kind. Standard * Thread ID, a combination of thread_class and thread_kind. Standard
* values have explicit identifiers. * values have explicit identifiers.
*/ */
typedef unsigned long NuThreadID; typedef uint32_t NuThreadID;
#define NuMakeThreadID(class, kind) /* construct a NuThreadID */ \ #define NuMakeThreadID(class, kind) /* construct a NuThreadID */ \
((unsigned long)(class) << 16 | (unsigned long)(kind)) ((uint32_t)(class) << 16 | (uint32_t)(kind))
#define NuGetThreadID(pThread) /* pull NuThreadID out of NuThread */ \ #define NuGetThreadID(pThread) /* pull NuThreadID out of NuThread */ \
(NuMakeThreadID((pThread)->thThreadClass, (pThread)->thThreadKind)) (NuMakeThreadID((pThread)->thThreadClass, (pThread)->thThreadKind))
#define NuThreadIDGetClass(threadID) /* get threadClass from NuThreadID */ \ #define NuThreadIDGetClass(threadID) /* get threadClass from NuThreadID */ \
((unsigned short) ((unsigned long)(threadID) >> 16)) ((uint16_t) ((uint32_t)(threadID) >> 16))
#define NuThreadIDGetKind(threadID) /* get threadKind from NuThreadID */ \ #define NuThreadIDGetKind(threadID) /* get threadKind from NuThreadID */ \
((unsigned short) ((threadID) & 0xffff)) ((uint16_t) ((threadID) & 0xffff))
#define kNuThreadClassMessage 0x0000 #define kNuThreadClassMessage 0x0000
#define kNuThreadClassControl 0x0001 #define kNuThreadClassControl 0x0001
#define kNuThreadClassData 0x0002 #define kNuThreadClassData 0x0002
@ -198,10 +226,10 @@ typedef enum NuThreadFormat {
/* extract the filesystem separator char from the "file_sys_info" field */ /* extract the filesystem separator char from the "file_sys_info" field */
#define NuGetSepFromSysInfo(sysInfo) \ #define NuGetSepFromSysInfo(sysInfo) \
((char) ((sysInfo) & 0xff)) ((UNICHAR) ((sysInfo) & 0xff))
/* return a file_sys_info with a replaced filesystem separator */ /* return a file_sys_info with a replaced filesystem separator */
#define NuSetSepInSysInfo(sysInfo, newSep) \ #define NuSetSepInSysInfo(sysInfo, newSep) \
((unsigned short) (((sysInfo) & 0xff00) | ((newSep) & 0xff)) ) ((uint16_t) (((sysInfo) & 0xff00) | ((newSep) & 0xff)) )
/* GS/OS-defined file system identifiers; sadly, UNIX is not among them */ /* GS/OS-defined file system identifiers; sadly, UNIX is not among them */
typedef enum NuFileSysID { typedef enum NuFileSysID {
@ -273,7 +301,7 @@ typedef enum NuValueID {
kNuValueIgnoreLZW2Len = 14, kNuValueIgnoreLZW2Len = 14,
kNuValueHandleBadMac = 15 kNuValueHandleBadMac = 15
} NuValueID; } NuValueID;
typedef unsigned long NuValue; typedef uint32_t NuValue;
/* /*
* Enumerated values for things you pass in a NuValue. * Enumerated values for things you pass in a NuValue.
@ -322,7 +350,7 @@ typedef enum NuAttrID {
kNuAttrHeaderOffset = 3, kNuAttrHeaderOffset = 3,
kNuAttrJunkOffset = 4, kNuAttrJunkOffset = 4,
} NuAttrID; } NuAttrID;
typedef unsigned long NuAttr; typedef uint32_t NuAttr;
/* /*
* Archive types. * Archive types.
@ -381,14 +409,14 @@ typedef union NuDataSink NuDataSink; /* dummy def for internal struct */
* NuFX Date/Time structure; same as TimeRec from IIgs "misctool.h". * NuFX Date/Time structure; same as TimeRec from IIgs "misctool.h".
*/ */
typedef struct NuDateTime { typedef struct NuDateTime {
unsigned char second; /* 0-59 */ uint8_t second; /* 0-59 */
unsigned char minute; /* 0-59 */ uint8_t minute; /* 0-59 */
unsigned char hour; /* 0-23 */ uint8_t hour; /* 0-23 */
unsigned char year; /* year - 1900 */ uint8_t year; /* year - 1900 */
unsigned char day; /* 0-30 */ uint8_t day; /* 0-30 */
unsigned char month; /* 0-11 */ uint8_t month; /* 0-11 */
unsigned char extra; /* (must be zero) */ uint8_t extra; /* (must be zero) */
unsigned char weekDay; /* 1-7 (1=sunday) */ uint8_t weekDay; /* 1-7 (1=sunday) */
} NuDateTime; } NuDateTime;
/* /*
@ -399,26 +427,30 @@ typedef struct NuDateTime {
*/ */
typedef struct NuThread { typedef struct NuThread {
/* from the archive */ /* from the archive */
unsigned short thThreadClass; uint16_t thThreadClass;
NuThreadFormat thThreadFormat; NuThreadFormat thThreadFormat;
unsigned short thThreadKind; uint16_t thThreadKind;
unsigned short thThreadCRC; /* comp or uncomp data; see rec vers */ uint16_t thThreadCRC; /* comp or uncomp data; see rec vers */
unsigned long thThreadEOF; uint32_t thThreadEOF;
unsigned long thCompThreadEOF; uint32_t thCompThreadEOF;
/* extra goodies */ /* extra goodies */
NuThreadIdx threadIdx; NuThreadIdx threadIdx;
unsigned long actualThreadEOF; /* disk images might be off */ uint32_t actualThreadEOF; /* disk images might be off */
long fileOffset; /* fseek offset to data in shk */ long fileOffset; /* fseek offset to data in shk */
/* internal use only */ /* internal use only */
unsigned short used; /* mark as uninteresting */ uint16_t used; /* mark as uninteresting */
} NuThread; } NuThread;
/* /*
* NuFX "record" definition. * NuFX "record" definition.
* *
* (Note to developers: update Nu_AddRecord if this changes.) * (Note to developers: update Nu_AddRecord if this changes.)
*
* The filenames are in Mac OS Roman format. It's arguable whether MOR
* strings should be part of the interface at all. However, the API
* pre-dates the inclusion of Unicode support, and I'm leaving it alone.
*/ */
#define kNufxIDLen 4 /* len of 'NuFX' with funky MSBs */ #define kNufxIDLen 4 /* len of 'NuFX' with funky MSBs */
#define kNuReasonableAttribCount 256 #define kNuReasonableAttribCount 256
@ -428,52 +460,52 @@ typedef struct NuThread {
#define kNuOurRecordVersion 3 /* what we write */ #define kNuOurRecordVersion 3 /* what we write */
typedef struct NuRecord { typedef struct NuRecord {
/* version 0+ */ /* version 0+ */
unsigned char recNufxID[kNufxIDLen]; uint8_t recNufxID[kNufxIDLen];
unsigned short recHeaderCRC; uint16_t recHeaderCRC;
unsigned short recAttribCount; uint16_t recAttribCount;
unsigned short recVersionNumber; uint16_t recVersionNumber;
unsigned long recTotalThreads; uint32_t recTotalThreads;
NuFileSysID recFileSysID; NuFileSysID recFileSysID;
unsigned short recFileSysInfo; uint16_t recFileSysInfo;
unsigned long recAccess; uint32_t recAccess;
unsigned long recFileType; uint32_t recFileType;
unsigned long recExtraType; uint32_t recExtraType;
unsigned short recStorageType; /* NuStorage*,file_sys_block_size */ uint16_t recStorageType; /* NuStorage*,file_sys_block_size */
NuDateTime recCreateWhen; NuDateTime recCreateWhen;
NuDateTime recModWhen; NuDateTime recModWhen;
NuDateTime recArchiveWhen; NuDateTime recArchiveWhen;
/* option lists only in version 1+ */ /* option lists only in version 1+ */
unsigned short recOptionSize; uint16_t recOptionSize;
unsigned char* recOptionList; /* NULL if v0 or recOptionSize==0 */ uint8_t* recOptionList; /* NULL if v0 or recOptionSize==0 */
/* data specified by recAttribCount, not accounted for by option list */ /* data specified by recAttribCount, not accounted for by option list */
long extraCount; int32_t extraCount;
unsigned char* extraBytes; uint8_t* extraBytes;
unsigned short recFilenameLength; /* usually zero */ uint16_t recFilenameLength; /* usually zero */
char* recFilename; /* doubles as disk volume_name */ char* recFilenameMOR; /* doubles as disk volume_name */
/* extra goodies; "dirtyHeader" does not apply to anything below */ /* extra goodies; "dirtyHeader" does not apply to anything below */
NuRecordIdx recordIdx; /* session-unique record index */ NuRecordIdx recordIdx; /* session-unique record index */
char* threadFilename; /* extracted from filename thread */ char* threadFilenameMOR; /* extracted from filename thread */
char* newFilename; /* memorized during "add file" call */ char* newFilenameMOR; /* memorized during "add file" call */
const char* filename; /* points at recFilen or threadFilen */ const char* filenameMOR; /* points at recFilen or threadFilen */
unsigned long recHeaderLength; /* size of rec hdr, incl thread hdrs */ uint32_t recHeaderLength; /* size of rec hdr, incl thread hdrs */
unsigned long totalCompLength; /* total len of data in archive file */ uint32_t totalCompLength; /* total len of data in archive file */
long fakeThreads; /* used by "MaskDataless" */ uint32_t fakeThreads; /* used by "MaskDataless" */
int isBadMac; /* malformed "bad mac" header */ int isBadMac; /* malformed "bad mac" header */
long fileOffset; /* file offset of record header */ long fileOffset; /* file offset of record header */
/* use provided interface to access this */ /* use provided interface to access this */
struct NuThread* pThreads; /* ptr to thread array */ struct NuThread* pThreads; /* ptr to thread array */
/* private -- things the application shouldn't look at */ /* private -- things the application shouldn't look at */
struct NuRecord* pNext; /* used internally */ struct NuRecord* pNext; /* used internally */
NuThreadMod* pThreadMods; /* used internally */ NuThreadMod* pThreadMods; /* used internally */
short dirtyHeader; /* set in "copy" when hdr fields uptd */ short dirtyHeader; /* set in "copy" when hdr fields uptd */
short dropRecFilename; /* if set, we're dropping this name */ short dropRecFilename; /* if set, we're dropping this name */
} NuRecord; } NuRecord;
/* /*
@ -488,18 +520,18 @@ typedef struct NuRecord {
#define kNuMaxMHVersion 2 /* max we can handle */ #define kNuMaxMHVersion 2 /* max we can handle */
#define kNuOurMHVersion 2 /* what we write */ #define kNuOurMHVersion 2 /* what we write */
typedef struct NuMasterHeader { typedef struct NuMasterHeader {
unsigned char mhNufileID[kNufileIDLen]; uint8_t mhNufileID[kNufileIDLen];
unsigned short mhMasterCRC; uint16_t mhMasterCRC;
unsigned long mhTotalRecords; uint32_t mhTotalRecords;
NuDateTime mhArchiveCreateWhen; NuDateTime mhArchiveCreateWhen;
NuDateTime mhArchiveModWhen; NuDateTime mhArchiveModWhen;
unsigned short mhMasterVersion; uint16_t mhMasterVersion;
unsigned char mhReserved1[kNufileMasterReserved1Len]; uint8_t mhReserved1[kNufileMasterReserved1Len];
unsigned long mhMasterEOF; uint32_t mhMasterEOF;
unsigned char mhReserved2[kNufileMasterReserved2Len]; uint8_t mhReserved2[kNufileMasterReserved2Len];
/* private -- internal use only */ /* private -- internal use only */
short isValid; short isValid;
} NuMasterHeader; } NuMasterHeader;
@ -514,35 +546,40 @@ typedef struct NuMasterHeader {
* a small subset of the full record. * a small subset of the full record.
*/ */
typedef struct NuRecordAttr { typedef struct NuRecordAttr {
NuFileSysID fileSysID; NuFileSysID fileSysID;
/*unsigned short fileSysInfo;*/ /*uint16_t fileSysInfo;*/
unsigned long access; uint32_t access;
unsigned long fileType; uint32_t fileType;
unsigned long extraType; uint32_t extraType;
NuDateTime createWhen; NuDateTime createWhen;
NuDateTime modWhen; NuDateTime modWhen;
NuDateTime archiveWhen; NuDateTime archiveWhen;
} NuRecordAttr; } NuRecordAttr;
/* /*
* Some additional details about a file. * Some additional details about a file.
*
* Ideally (from an API cleanliness perspective) the storage name would
* be passed around as UTF-8 and converted internally. Passing it as
* MOR required fewer changes to the library, and allows us to avoid
* having to deal with illegal characters.
*/ */
typedef struct NuFileDetails { typedef struct NuFileDetails {
/* used during AddFile call */ /* used during AddFile call */
NuThreadID threadID; /* data, rsrc, disk img? */ NuThreadID threadID; /* data, rsrc, disk img? */
const char* origName; const void* origName; /* arbitrary pointer, usually a string */
/* these go straight into the NuRecord */ /* these go straight into the NuRecord */
const char* storageName; const char* storageNameMOR;
NuFileSysID fileSysID; NuFileSysID fileSysID;
unsigned short fileSysInfo; uint16_t fileSysInfo;
unsigned long access; uint32_t access;
unsigned long fileType; uint32_t fileType;
unsigned long extraType; uint32_t extraType;
unsigned short storageType; /* use Unknown, or disk block size */ uint16_t storageType; /* use Unknown, or disk block size */
NuDateTime createWhen; NuDateTime createWhen;
NuDateTime modWhen; NuDateTime modWhen;
NuDateTime archiveWhen; NuDateTime archiveWhen;
} NuFileDetails; } NuFileDetails;
@ -550,23 +587,23 @@ typedef struct NuFileDetails {
* Passed into the SelectionFilter callback. * Passed into the SelectionFilter callback.
*/ */
typedef struct NuSelectionProposal { typedef struct NuSelectionProposal {
const NuRecord* pRecord; const NuRecord* pRecord;
const NuThread* pThread; const NuThread* pThread;
} NuSelectionProposal; } NuSelectionProposal;
/* /*
* Passed into the OutputPathnameFilter callback. * Passed into the OutputPathnameFilter callback.
*/ */
typedef struct NuPathnameProposal { typedef struct NuPathnameProposal {
const char* pathname; const UNICHAR* pathnameUNI;
char filenameSeparator; char filenameSeparator;
const NuRecord* pRecord; const NuRecord* pRecord;
const NuThread* pThread; const NuThread* pThread;
const char* newPathname; const UNICHAR* newPathnameUNI;
unsigned char newFilenameSeparator; uint8_t newFilenameSeparator;
/*NuThreadID newStorage;*/ /*NuThreadID newStorage;*/
NuDataSink* newDataSink; NuDataSink* newDataSink;
} NuPathnameProposal; } NuPathnameProposal;
@ -598,7 +635,8 @@ typedef enum NuProgressState {
} NuProgressState; } NuProgressState;
/* /*
* Passed into the ProgressUpdater callback. * Passed into the ProgressUpdater callback. All pointers become
* invalid when the callback returns.
* *
* [ Thought for the day: add an optional flag that causes us to only * [ Thought for the day: add an optional flag that causes us to only
* call the progressFunc when the "percentComplete" changes by more * call the progressFunc when the "percentComplete" changes by more
@ -606,36 +644,36 @@ typedef enum NuProgressState {
*/ */
typedef struct NuProgressData { typedef struct NuProgressData {
/* what are we doing */ /* what are we doing */
NuOperation operation; NuOperation operation;
/* what specifically are we doing */ /* what specifically are we doing */
NuProgressState state; NuProgressState state;
/* how far along are we */ /* how far along are we */
short percentComplete; /* 0-100 */ short percentComplete; /* 0-100 */
/* original pathname (in archive for expand, on disk for compress) */ /* original pathname (in archive for expand, on disk for compress) */
const char* origPathname; const UNICHAR* origPathnameUNI;
/* processed pathname (PathnameFilter for expand, in-record for compress) */ /* processed pathname (PathnameFilter for expand, in-record for compress) */
const char* pathname; const UNICHAR* pathnameUNI;
/* basename of "pathname" */ /* basename of "pathname" (for convenience) */
const char* filename; const UNICHAR* filenameUNI;
/* pointer to the record we're expanding from */ /* pointer to the record we're expanding from */
const NuRecord* pRecord; const NuRecord* pRecord;
unsigned long uncompressedLength; /* size of uncompressed data */ uint32_t uncompressedLength; /* size of uncompressed data */
unsigned long uncompressedProgress; /* #of bytes in/out */ uint32_t uncompressedProgress; /* #of bytes in/out */
struct { struct {
NuThreadFormat threadFormat; /* compression being applied */ NuThreadFormat threadFormat; /* compression being applied */
} compress; } compress;
struct { struct {
unsigned long totalCompressedLength; /* all "data" threads */ uint32_t totalCompressedLength; /* all "data" threads */
unsigned long totalUncompressedLength; uint32_t totalUncompressedLength;
/*unsigned long compressedLength; * size of compressed data */ /*uint32_t compressedLength; * size of compressed data */
/*unsigned long compressedProgress; * #of compressed bytes in/out*/ /*uint32_t compressedProgress; * #of compressed bytes in/out*/
const NuThread* pThread; /* thread we're working on */ const NuThread* pThread; /* thread we're working on */
NuValue convertEOL; /* set if LF/CR conv is on */ NuValue convertEOL; /* set if LF/CR conv is on */
} expand; } expand;
/* pay no attention */ /* pay no attention */
@ -649,11 +687,11 @@ typedef struct NuErrorStatus {
NuOperation operation; /* were we adding, extracting, ?? */ NuOperation operation; /* were we adding, extracting, ?? */
NuError err; /* library error code */ NuError err; /* library error code */
int sysErr; /* system error code, if applicable */ int sysErr; /* system error code, if applicable */
const char* message; /* (optional) message to user */ const UNICHAR* message; /* (optional) message to user */
const NuRecord* pRecord; /* relevant record, if any */ const NuRecord* pRecord; /* relevant record, if any */
const char* pathname; /* problematic pathname, if any */ const UNICHAR* pathnameUNI; /* problematic pathname, if any */
const char* origPathname; /* original pathname, if any */ const void* origPathname; /* original pathname ref, if any */
char filenameSeparator; /* fssep for pathname, if any */ UNICHAR filenameSeparator; /* fssep for pathname, if any */
/*char origArchiveTouched;*/ /*char origArchiveTouched;*/
char canAbort; /* give option to abort */ char canAbort; /* give option to abort */
@ -669,14 +707,14 @@ typedef struct NuErrorStatus {
* Error message callback gets one of these. * Error message callback gets one of these.
*/ */
typedef struct NuErrorMessage { typedef struct NuErrorMessage {
const char* message; /* the message itself */ const char* message; /* the message itself (UTF-8) */
NuError err; /* relevant error code (may be none) */ NuError err; /* relevant error code (may be none) */
short isDebug; /* set for debug-only messages */ short isDebug; /* set for debug-only messages */
/* these identify where the message originated if lib built w/debug set */ /* these identify where the message originated if lib built w/debug set */
const char* file; /* source file */ const char* file; /* source file (UTF-8) */
int line; /* line number */ int line; /* line number */
const char* function; /* function name (might be nil) */ const char* function; /* function name (might be NULL) */
} NuErrorMessage; } NuErrorMessage;
@ -727,37 +765,38 @@ NUFXLIB_API NuError NuExtract(NuArchive* pArchive);
NUFXLIB_API NuError NuTest(NuArchive* pArchive); NUFXLIB_API NuError NuTest(NuArchive* pArchive);
/* strictly non-streaming read-only interfaces */ /* strictly non-streaming read-only interfaces */
NUFXLIB_API NuError NuOpenRO(const char* archivePathname,NuArchive** ppArchive); NUFXLIB_API NuError NuOpenRO(const UNICHAR* archivePathnameUNI,
NuArchive** ppArchive);
NUFXLIB_API NuError NuExtractRecord(NuArchive* pArchive, NuRecordIdx recordIdx); NUFXLIB_API NuError NuExtractRecord(NuArchive* pArchive, NuRecordIdx recordIdx);
NUFXLIB_API NuError NuExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx, NUFXLIB_API NuError NuExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
NuDataSink* pDataSink); NuDataSink* pDataSink);
NUFXLIB_API NuError NuTestRecord(NuArchive* pArchive, NuRecordIdx recordIdx); NUFXLIB_API NuError NuTestRecord(NuArchive* pArchive, NuRecordIdx recordIdx);
NUFXLIB_API NuError NuGetRecord(NuArchive* pArchive, NuRecordIdx recordIdx, NUFXLIB_API NuError NuGetRecord(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecord** ppRecord); const NuRecord** ppRecord);
NUFXLIB_API NuError NuGetRecordIdxByName(NuArchive* pArchive, const char* name, NUFXLIB_API NuError NuGetRecordIdxByName(NuArchive* pArchive,
NuRecordIdx* pRecordIdx); const char* nameMOR, NuRecordIdx* pRecordIdx);
NUFXLIB_API NuError NuGetRecordIdxByPosition(NuArchive* pArchive, NUFXLIB_API NuError NuGetRecordIdxByPosition(NuArchive* pArchive,
unsigned long position, NuRecordIdx* pRecordIdx); uint32_t position, NuRecordIdx* pRecordIdx);
/* read/write interfaces */ /* read/write interfaces */
NUFXLIB_API NuError NuOpenRW(const char* archivePathname, NUFXLIB_API NuError NuOpenRW(const UNICHAR* archivePathnameUNI,
const char* tempPathname, unsigned long flags, const UNICHAR* tempPathnameUNI, uint32_t flags,
NuArchive** ppArchive); NuArchive** ppArchive);
NUFXLIB_API NuError NuFlush(NuArchive* pArchive, long* pStatusFlags); NUFXLIB_API NuError NuFlush(NuArchive* pArchive, uint32_t* pStatusFlags);
NUFXLIB_API NuError NuAddRecord(NuArchive* pArchive, NUFXLIB_API NuError NuAddRecord(NuArchive* pArchive,
const NuFileDetails* pFileDetails, NuRecordIdx* pRecordIdx); const NuFileDetails* pFileDetails, NuRecordIdx* pRecordIdx);
NUFXLIB_API NuError NuAddThread(NuArchive* pArchive, NuRecordIdx recordIdx, NUFXLIB_API NuError NuAddThread(NuArchive* pArchive, NuRecordIdx recordIdx,
NuThreadID threadID, NuDataSource* pDataSource, NuThreadID threadID, NuDataSource* pDataSource,
NuThreadIdx* pThreadIdx); NuThreadIdx* pThreadIdx);
NUFXLIB_API NuError NuAddFile(NuArchive* pArchive, const char* pathname, NUFXLIB_API NuError NuAddFile(NuArchive* pArchive, const UNICHAR* pathnameUNI,
const NuFileDetails* pFileDetails, short fromRsrcFork, const NuFileDetails* pFileDetails, short fromRsrcFork,
NuRecordIdx* pRecordIdx); NuRecordIdx* pRecordIdx);
NUFXLIB_API NuError NuRename(NuArchive* pArchive, NuRecordIdx recordIdx, NUFXLIB_API NuError NuRename(NuArchive* pArchive, NuRecordIdx recordIdx,
const char* pathname, char fssep); const char* pathnameMOR, UNICHAR fssep);
NUFXLIB_API NuError NuSetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx, NUFXLIB_API NuError NuSetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecordAttr* pRecordAttr); const NuRecordAttr* pRecordAttr);
NUFXLIB_API NuError NuUpdatePresizedThread(NuArchive* pArchive, NUFXLIB_API NuError NuUpdatePresizedThread(NuArchive* pArchive,
NuThreadIdx threadIdx, NuDataSource* pDataSource, long* pMaxLen); NuThreadIdx threadIdx, NuDataSource* pDataSource, int32_t* pMaxLen);
NUFXLIB_API NuError NuDelete(NuArchive* pArchive); NUFXLIB_API NuError NuDelete(NuArchive* pArchive);
NUFXLIB_API NuError NuDeleteRecord(NuArchive* pArchive, NuRecordIdx recordIdx); NUFXLIB_API NuError NuDeleteRecord(NuArchive* pArchive, NuRecordIdx recordIdx);
NUFXLIB_API NuError NuDeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx); NUFXLIB_API NuError NuDeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx);
@ -779,31 +818,31 @@ NUFXLIB_API NuError NuDebugDumpArchive(NuArchive* pArchive);
/* sources and sinks */ /* sources and sinks */
NUFXLIB_API NuError NuCreateDataSourceForFile(NuThreadFormat threadFormat, NUFXLIB_API NuError NuCreateDataSourceForFile(NuThreadFormat threadFormat,
unsigned long otherLen, const char* pathname, uint32_t otherLen, const UNICHAR* pathnameUNI,
short isFromRsrcFork, NuDataSource** ppDataSource); short isFromRsrcFork, NuDataSource** ppDataSource);
NUFXLIB_API NuError NuCreateDataSourceForFP(NuThreadFormat threadFormat, NUFXLIB_API NuError NuCreateDataSourceForFP(NuThreadFormat threadFormat,
unsigned long otherLen, FILE* fp, long offset, long length, uint32_t otherLen, FILE* fp, long offset, long length,
NuCallback closeFunc, NuDataSource** ppDataSource); NuCallback closeFunc, NuDataSource** ppDataSource);
NUFXLIB_API NuError NuCreateDataSourceForBuffer(NuThreadFormat threadFormat, NUFXLIB_API NuError NuCreateDataSourceForBuffer(NuThreadFormat threadFormat,
unsigned long otherLen, const unsigned char* buffer, long offset, uint32_t otherLen, const uint8_t* buffer, long offset,
long length, NuCallback freeFunc, NuDataSource** ppDataSource); long length, NuCallback freeFunc, NuDataSource** ppDataSource);
NUFXLIB_API NuError NuFreeDataSource(NuDataSource* pDataSource); NUFXLIB_API NuError NuFreeDataSource(NuDataSource* pDataSource);
NUFXLIB_API NuError NuDataSourceSetRawCrc(NuDataSource* pDataSource, NUFXLIB_API NuError NuDataSourceSetRawCrc(NuDataSource* pDataSource,
unsigned short crc); uint16_t crc);
NUFXLIB_API NuError NuCreateDataSinkForFile(short doExpand, NuValue convertEOL, NUFXLIB_API NuError NuCreateDataSinkForFile(short doExpand, NuValue convertEOL,
const char* pathname, char fssep, NuDataSink** ppDataSink); const UNICHAR* pathnameUNI, UNICHAR fssep, NuDataSink** ppDataSink);
NUFXLIB_API NuError NuCreateDataSinkForFP(short doExpand, NuValue convertEOL, NUFXLIB_API NuError NuCreateDataSinkForFP(short doExpand, NuValue convertEOL,
FILE* fp, NuDataSink** ppDataSink); FILE* fp, NuDataSink** ppDataSink);
NUFXLIB_API NuError NuCreateDataSinkForBuffer(short doExpand, NUFXLIB_API NuError NuCreateDataSinkForBuffer(short doExpand,
NuValue convertEOL, unsigned char* buffer, unsigned long bufLen, NuValue convertEOL, uint8_t* buffer, uint32_t bufLen,
NuDataSink** ppDataSink); NuDataSink** ppDataSink);
NUFXLIB_API NuError NuFreeDataSink(NuDataSink* pDataSink); NUFXLIB_API NuError NuFreeDataSink(NuDataSink* pDataSink);
NUFXLIB_API NuError NuDataSinkGetOutCount(NuDataSink* pDataSink, NUFXLIB_API NuError NuDataSinkGetOutCount(NuDataSink* pDataSink,
unsigned long* pOutCount); uint32_t* pOutCount);
/* miscellaneous non-archive operations */ /* miscellaneous non-archive operations */
NUFXLIB_API NuError NuGetVersion(long* pMajorVersion, long* pMinorVersion, NUFXLIB_API NuError NuGetVersion(int32_t* pMajorVersion, int32_t* pMinorVersion,
long* pBugVersion, const char** ppBuildDate, int32_t* pBugVersion, const char** ppBuildDate,
const char** ppBuildFlags); const char** ppBuildFlags);
NUFXLIB_API const char* NuStrError(NuError err); NUFXLIB_API const char* NuStrError(NuError err);
NUFXLIB_API NuError NuTestFeature(NuFeature feature); NUFXLIB_API NuError NuTestFeature(NuFeature feature);
@ -811,13 +850,18 @@ NUFXLIB_API void NuRecordCopyAttr(NuRecordAttr* pRecordAttr,
const NuRecord* pRecord); const NuRecord* pRecord);
NUFXLIB_API NuError NuRecordCopyThreads(const NuRecord* pRecord, NUFXLIB_API NuError NuRecordCopyThreads(const NuRecord* pRecord,
NuThread** ppThreads); NuThread** ppThreads);
NUFXLIB_API unsigned long NuRecordGetNumThreads(const NuRecord* pRecord); NUFXLIB_API uint32_t NuRecordGetNumThreads(const NuRecord* pRecord);
NUFXLIB_API const NuThread* NuThreadGetByIdx(const NuThread* pThread, long idx); NUFXLIB_API const NuThread* NuThreadGetByIdx(const NuThread* pThread,
int32_t idx);
NUFXLIB_API short NuIsPresizedThreadID(NuThreadID threadID); NUFXLIB_API short NuIsPresizedThreadID(NuThreadID threadID);
NUFXLIB_API size_t NuConvertMORToUNI(const char* stringMOR,
UNICHAR* bufUNI, size_t bufSize);
NUFXLIB_API size_t NuConvertUNIToMOR(const UNICHAR* stringUNI,
char* bufMOR, size_t bufSize);
#define NuGetThread(pRecord, idx) ( (const NuThread*) \ #define NuGetThread(pRecord, idx) ( (const NuThread*) \
((unsigned long) (idx) < (unsigned long) (pRecord)->recTotalThreads ? \ ((uint32_t) (idx) < (pRecord)->recTotalThreads ? \
&(pRecord)->pThreads[(idx)] : NULL) \ &(pRecord)->pThreads[(idx)] : NULL) \
) )
@ -840,4 +884,4 @@ NUFXLIB_API NuCallback NuSetGlobalErrorMessageHandler(NuCallback messageHandlerF
} }
#endif #endif
#endif /*__NufxLib__*/ #endif /*NUFXLIB_NUFXLIB_H*/

View File

@ -6,8 +6,8 @@
* *
* Global internal declarations and definitions. * Global internal declarations and definitions.
*/ */
#ifndef __NufxLibPriv__ #ifndef NUFXLIB_NUFXLIBPRIV_H
#define __NufxLibPriv__ #define NUFXLIB_NUFXLIBPRIV_H
/* include files that everybody needs */ /* include files that everybody needs */
#include "SysDefs.h" #include "SysDefs.h"
@ -86,7 +86,7 @@ typedef enum NuOpenMode {
*/ */
typedef struct NuRecordSet { typedef struct NuRecordSet {
Boolean loaded; Boolean loaded;
ulong numRecords; uint32_t numRecords;
NuRecord* nuRecordHead; NuRecord* nuRecordHead;
NuRecord* nuRecordTail; NuRecord* nuRecordTail;
} NuRecordSet; } NuRecordSet;
@ -95,12 +95,12 @@ typedef struct NuRecordSet {
* Archive state. * Archive state.
*/ */
struct NuArchive { struct NuArchive {
ulong structMagic; uint32_t structMagic;
Boolean busy; Boolean busy;
NuOpenMode openMode; NuOpenMode openMode;
Boolean newlyCreated; Boolean newlyCreated;
char* archivePathname; /* pathname or "(stream)" */ UNICHAR* archivePathnameUNI; /* pathname or "(stream)" */
FILE* archiveFp; FILE* archiveFp;
NuArchiveType archiveType; NuArchiveType archiveType;
@ -108,7 +108,7 @@ struct NuArchive {
long junkOffset; /* skip past leading junk */ long junkOffset; /* skip past leading junk */
long headerOffset; /* adjustment for BXY/SEA/BSE */ long headerOffset; /* adjustment for BXY/SEA/BSE */
char* tmpPathname; /* temp file, for writes */ UNICHAR* tmpPathnameUNI; /* temp file, for writes */
FILE* tmpFp; FILE* tmpFp;
/* used during initial processing; helps avoid ftell() calls */ /* used during initial processing; helps avoid ftell() calls */
@ -118,9 +118,9 @@ struct NuArchive {
Boolean testMode; Boolean testMode;
/* clumsy way of remembering name used for other fork in forked file */ /* clumsy way of remembering name used for other fork in forked file */
const char* lastFileCreated; const UNICHAR* lastFileCreatedUNI;
/* clumsy way to avoid trying to create the same subdir several times */ /* clumsy way to avoid trying to create the same subdir several times */
const char* lastDirCreated; const UNICHAR* lastDirCreatedUNI;
/* master header from the archive */ /* master header from the archive */
NuMasterHeader masterHeader; /* original */ NuMasterHeader masterHeader; /* original */
@ -135,7 +135,7 @@ struct NuArchive {
NuRecordSet newRecordSet; /* newly-added records */ NuRecordSet newRecordSet; /* newly-added records */
/* state for compression functions */ /* state for compression functions */
uchar* compBuf; /* large general-purpose buffer */ uint8_t* compBuf; /* large general-purpose buffer */
void* lzwCompressState; /* state for LZW/1 and LZW/2 */ void* lzwCompressState; /* state for LZW/1 and LZW/2 */
void* lzwExpandState; /* state for LZW/1 and LZW/2 */ void* lzwExpandState; /* state for LZW/1 and LZW/2 */
@ -169,7 +169,7 @@ struct NuArchive {
#define kNuArchiveStructMagic 0xc0edbabe #define kNuArchiveStructMagic 0xc0edbabe
#define kNuDefaultRecordName "UNKNOWN" #define kNuDefaultRecordName "UNKNOWN" /* use ASCII charset */
/* /*
@ -256,7 +256,7 @@ struct NuThreadMod {
*/ */
typedef struct NuFunnel { typedef struct NuFunnel {
/* data storage */ /* data storage */
uchar* buffer; /* kNuFunnelBufSize worth of storage */ uint8_t* buffer; /* kNuFunnelBufSize worth of storage */
long bufCount; /* #of bytes in buffer */ long bufCount; /* #of bytes in buffer */
/* text conversion; if "auto", on first flush we convert to "on" or "off" */ /* text conversion; if "auto", on first flush we convert to "on" or "off" */
@ -270,10 +270,10 @@ typedef struct NuFunnel {
Boolean isFirstWrite; /* cleared on first write */ Boolean isFirstWrite; /* cleared on first write */
#if 0 #if 0
ulong inCount; /* total #of bytes in the top */ uint32_t inCount; /* total #of bytes in the top */
ulong outCount; /* total #of bytes out the bottom */ uint32_t outCount; /* total #of bytes out the bottom */
ulong outMax; /* flag an err when outCount exceeds this */ uint32_t outMax; /* flag an err when outCount exceeds this */
Boolean outMaxExceeded; /* in fact, it's this flag */ Boolean outMaxExceeded; /* in fact, it's this flag */
#endif #endif
@ -302,11 +302,11 @@ typedef struct NuStraw {
NuDataSource* pDataSource; NuDataSource* pDataSource;
/* progress update fields */ /* progress update fields */
ulong lastProgress; uint32_t lastProgress;
ulong lastDisplayed; uint32_t lastDisplayed;
} NuStraw; } NuStraw;
/*NuError Nu_CopyStreamToStream(FILE* outfp, FILE* infp, ulong count);*/ /*NuError Nu_CopyStreamToStream(FILE* outfp, FILE* infp, uint32_t count);*/
/* /*
@ -329,10 +329,10 @@ typedef enum NuDataSourceType {
typedef struct NuDataSourceCommon { typedef struct NuDataSourceCommon {
NuDataSourceType sourceType; NuDataSourceType sourceType;
NuThreadFormat threadFormat; /* is it already compressed? */ NuThreadFormat threadFormat; /* is it already compressed? */
ushort rawCrc; /* crc for already-compressed data*/ uint16_t rawCrc; /* crc for already-compressed data*/
/*Boolean doClose; \* close on completion? */ /*Boolean doClose; \* close on completion? */
ulong dataLen; /* length of data (var for buf) */ uint32_t dataLen; /* length of data (var for buf) */
ulong otherLen; /* uncomp len or preset buf size */ uint32_t otherLen; /* uncomp len or preset buf size */
int refCount; /* so we can copy structs */ int refCount; /* so we can copy structs */
} NuDataSourceCommon; } NuDataSourceCommon;
@ -343,7 +343,7 @@ union NuDataSource {
struct { struct {
NuDataSourceCommon common; NuDataSourceCommon common;
char* pathname; UNICHAR* pathnameUNI;
Boolean fromRsrcFork; Boolean fromRsrcFork;
/* temp storage; only valid when processing in library */ /* temp storage; only valid when processing in library */
@ -360,7 +360,7 @@ union NuDataSource {
struct { struct {
NuDataSourceCommon common; NuDataSourceCommon common;
const uchar* buffer; /* non-const if doClose=true */ const uint8_t* buffer; /* non-const if doClose=true */
long offset; /* starting offset */ long offset; /* starting offset */
long curOffset; /* current offset */ long curOffset; /* current offset */
@ -387,7 +387,7 @@ typedef struct NuDataSinkCommon {
NuDataSinkType sinkType; NuDataSinkType sinkType;
Boolean doExpand; /* expand file? */ Boolean doExpand; /* expand file? */
NuValue convertEOL; /* convert EOL? (req "expand") */ NuValue convertEOL; /* convert EOL? (req "expand") */
ulong outCount; uint32_t outCount;
} NuDataSinkCommon; } NuDataSinkCommon;
union NuDataSink { union NuDataSink {
@ -397,10 +397,10 @@ union NuDataSink {
struct { struct {
NuDataSinkCommon common; NuDataSinkCommon common;
char* pathname; /* file to open */ UNICHAR* pathnameUNI; /* file to open */
char fssep; UNICHAR fssep;
/* temp storage; must be nil except when processing in library */ /* temp storage; must be NULL except when processing in library */
FILE* fp; FILE* fp;
} toFile; } toFile;
@ -411,8 +411,8 @@ union NuDataSink {
struct { struct {
NuDataSinkCommon common; NuDataSinkCommon common;
uchar* buffer; uint8_t* buffer;
ulong bufLen; /* max amount of data "buffer" holds */ uint32_t bufLen; /* max amount of data "buffer" holds */
NuError stickyErr; NuError stickyErr;
} toBuffer; } toBuffer;
}; };
@ -469,13 +469,13 @@ union NuDataSink {
goto bail; \ goto bail; \
} }
#define BailNil(val) { \ #define BailNil(val) { \
if ((val) == nil) { \ if ((val) == NULL) { \
err = kNuErrUnexpectedNil; \ err = kNuErrUnexpectedNil; \
BailError(err); \ BailError(err); \
} \ } \
} }
#define BailAlloc(val) { \ #define BailAlloc(val) { \
if ((val) == nil) { \ if ((val) == NULL) { \
err = kNuErrMalloc; \ err = kNuErrMalloc; \
BailError(err); \ BailError(err); \
} \ } \
@ -498,9 +498,9 @@ NuError Nu_UpdateWrapper(NuArchive* pArchive, FILE* fp);
NuError Nu_AdjustWrapperPadding(NuArchive* pArchive, FILE* fp); NuError Nu_AdjustWrapperPadding(NuArchive* pArchive, FILE* fp);
NuError Nu_AllocCompressionBufferIFN(NuArchive* pArchive); NuError Nu_AllocCompressionBufferIFN(NuArchive* pArchive);
NuError Nu_StreamOpenRO(FILE* infp, NuArchive** ppArchive); NuError Nu_StreamOpenRO(FILE* infp, NuArchive** ppArchive);
NuError Nu_OpenRO(const char* filename, NuArchive** ppArchive); NuError Nu_OpenRO(const UNICHAR* archivePathnameUNI, NuArchive** ppArchive);
NuError Nu_OpenRW(const char* archivePathname, const char* tempPathname, NuError Nu_OpenRW(const UNICHAR* archivePathnameUNI,
ulong flags, NuArchive** ppArchive); const UNICHAR* tempPathnameUNI, uint32_t flags, NuArchive** ppArchive);
NuError Nu_WriteMasterHeader(NuArchive* pArchive, FILE* fp, NuError Nu_WriteMasterHeader(NuArchive* pArchive, FILE* fp,
NuMasterHeader* pMasterHeader); NuMasterHeader* pMasterHeader);
NuError Nu_Close(NuArchive* pArchive); NuError Nu_Close(NuArchive* pArchive);
@ -509,28 +509,28 @@ NuError Nu_RenameTempToArchive(NuArchive* pArchive);
NuError Nu_DeleteArchiveFile(NuArchive* pArchive); NuError Nu_DeleteArchiveFile(NuArchive* pArchive);
/* ArchiveIO.c */ /* ArchiveIO.c */
uchar Nu_ReadOneC(NuArchive* pArchive, FILE* fp, ushort* pCrc); uint8_t Nu_ReadOneC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc);
uchar Nu_ReadOne(NuArchive* pArchive, FILE* fp); uint8_t Nu_ReadOne(NuArchive* pArchive, FILE* fp);
void Nu_WriteOneC(NuArchive* pArchive, FILE* fp, uchar val, ushort* pCrc); void Nu_WriteOneC(NuArchive* pArchive, FILE* fp, uint8_t val, uint16_t* pCrc);
void Nu_WriteOne(NuArchive* pArchive, FILE* fp, uchar val); void Nu_WriteOne(NuArchive* pArchive, FILE* fp, uint8_t val);
ushort Nu_ReadTwoC(NuArchive* pArchive, FILE* fp, ushort* pCrc); uint16_t Nu_ReadTwoC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc);
ushort Nu_ReadTwo(NuArchive* pArchive, FILE* fp); uint16_t Nu_ReadTwo(NuArchive* pArchive, FILE* fp);
void Nu_WriteTwoC(NuArchive* pArchive, FILE* fp, ushort val, ushort* pCrc); void Nu_WriteTwoC(NuArchive* pArchive, FILE* fp, uint16_t val, uint16_t* pCrc);
void Nu_WriteTwo(NuArchive* pArchive, FILE* fp, ushort val); void Nu_WriteTwo(NuArchive* pArchive, FILE* fp, uint16_t val);
ulong Nu_ReadFourC(NuArchive* pArchive, FILE* fp, ushort* pCrc); uint32_t Nu_ReadFourC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc);
ulong Nu_ReadFour(NuArchive* pArchive, FILE* fp); uint32_t Nu_ReadFour(NuArchive* pArchive, FILE* fp);
void Nu_WriteFourC(NuArchive* pArchive, FILE* fp, ulong val, ushort* pCrc); void Nu_WriteFourC(NuArchive* pArchive, FILE* fp, uint32_t val, uint16_t* pCrc);
void Nu_WriteFour(NuArchive* pArchive, FILE* fp, ulong val); void Nu_WriteFour(NuArchive* pArchive, FILE* fp, uint32_t val);
NuDateTime Nu_ReadDateTimeC(NuArchive* pArchive, FILE* fp, ushort* pCrc); NuDateTime Nu_ReadDateTimeC(NuArchive* pArchive, FILE* fp, uint16_t* pCrc);
NuDateTime Nu_ReadDateTime(NuArchive* pArchive, FILE* fp, ushort* pCrc); NuDateTime Nu_ReadDateTime(NuArchive* pArchive, FILE* fp, uint16_t* pCrc);
void Nu_WriteDateTimeC(NuArchive* pArchive, FILE* fp, NuDateTime dateTime, void Nu_WriteDateTimeC(NuArchive* pArchive, FILE* fp, NuDateTime dateTime,
ushort* pCrc); uint16_t* pCrc);
void Nu_WriteDateTime(NuArchive* pArchive, FILE* fp, NuDateTime dateTime); void Nu_WriteDateTime(NuArchive* pArchive, FILE* fp, NuDateTime dateTime);
void Nu_ReadBytesC(NuArchive* pArchive, FILE* fp, void* vbuffer, long count, void Nu_ReadBytesC(NuArchive* pArchive, FILE* fp, void* vbuffer, long count,
ushort* pCrc); uint16_t* pCrc);
void Nu_ReadBytes(NuArchive* pArchive, FILE* fp, void* vbuffer, long count); void Nu_ReadBytes(NuArchive* pArchive, FILE* fp, void* vbuffer, long count);
void Nu_WriteBytesC(NuArchive* pArchive, FILE* fp, const void* vbuffer, void Nu_WriteBytesC(NuArchive* pArchive, FILE* fp, const void* vbuffer,
long count, ushort* pCrc); long count, uint16_t* pCrc);
void Nu_WriteBytes(NuArchive* pArchive, FILE* fp, const void* vbuffer, void Nu_WriteBytes(NuArchive* pArchive, FILE* fp, const void* vbuffer,
long count); long count);
NuError Nu_HeaderIOFailed(NuArchive* pArchive, FILE* fp); NuError Nu_HeaderIOFailed(NuArchive* pArchive, FILE* fp);
@ -540,9 +540,16 @@ NuError Nu_RewindArchive(NuArchive* pArchive);
/* Bzip2.c */ /* Bzip2.c */
NuError Nu_CompressBzip2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, NuError Nu_CompressBzip2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
ulong srcLen, ulong* pDstLen, ushort* pCrc); uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc);
NuError Nu_ExpandBzip2(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_ExpandBzip2(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc); const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc);
/* Charset.c */
size_t Nu_ConvertMORToUNI(const char* stringMOR, UNICHAR* bufUNI,
size_t bufSize);
UNICHAR* Nu_CopyMORToUNI(const char* stringMOR);
size_t Nu_ConvertUNIToMOR(const UNICHAR* stringUNI, char* bufMOR,
size_t bufSize);
/* Compress.c */ /* Compress.c */
NuError Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource, NuError Nu_CompressToArchive(NuArchive* pArchive, NuDataSource* pDataSource,
@ -554,22 +561,17 @@ NuError Nu_CopyPresizedToArchive(NuArchive* pArchive,
NuThread* pThread, char** ppSavedCopy); NuThread* pThread, char** ppSavedCopy);
/* Crc16.c */ /* Crc16.c */
extern const ushort gNuCrc16Table[256]; extern const uint16_t gNuCrc16Table[256];
ushort Nu_CalcCRC16(ushort seed, const uchar* ptr, int count); uint16_t Nu_CalcCRC16(uint16_t seed, const uint8_t* ptr, int count);
#ifdef __Crc16_c__ /* just doing "static inline" warns def-but-not-used */ /*
#define CRC_INLINE /**/ * Update the CRC-16.
#else *
#define CRC_INLINE extern inline * _val (uint8_t) is the byte to add to the CRC. It's evaluated once.
#endif * _crc (uint16_t) is the previous CRC. It's evaluated twice.
#if defined(inline) && !defined(__Crc16_c__) /* somebody ovrd inline def? */ * Returns the updated CRC as a uint16_t.
ushort Nu_UpdateCRC16(uchar val, ushort crc); */
#else #define Nu_UpdateCRC16(_val, _crc) \
CRC_INLINE ushort (gNuCrc16Table[(((_crc) >> 8) & 0xff) ^ (_val)] ^ ((_crc) << 8))
Nu_UpdateCRC16(uchar val, ushort crc)
{
return (gNuCrc16Table[((crc >> 8) & 0xFF) ^ val] ^ (crc << 8)) & 0xFFFF;
}
#endif
/* Debug.c */ /* Debug.c */
#if defined(DEBUG_MSGS) || !defined(NDEBUG) #if defined(DEBUG_MSGS) || !defined(NDEBUG)
@ -591,13 +593,13 @@ NuError Nu_ThreadModAdd_FindByThreadID(const NuRecord* pRecord,
void Nu_FreeThreadMods(NuArchive* pArchive, NuRecord* pRecord); void Nu_FreeThreadMods(NuArchive* pArchive, NuRecord* pRecord);
NuThreadMod* Nu_ThreadMod_FindByThreadIdx(const NuRecord* pRecord, NuThreadMod* Nu_ThreadMod_FindByThreadIdx(const NuRecord* pRecord,
NuThreadIdx threadIdx); NuThreadIdx threadIdx);
NuError Nu_Flush(NuArchive* pArchive, long* pStatusFlags); NuError Nu_Flush(NuArchive* pArchive, uint32_t* pStatusFlags);
/* Deflate.c */ /* Deflate.c */
NuError Nu_CompressDeflate(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, NuError Nu_CompressDeflate(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
ulong srcLen, ulong* pDstLen, ushort* pCrc); uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc);
NuError Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_ExpandDeflate(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc); const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc);
/* Expand.c */ /* Expand.c */
NuError Nu_ExpandStream(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_ExpandStream(NuArchive* pArchive, const NuRecord* pRecord,
@ -607,14 +609,14 @@ NuError Nu_ExpandStream(NuArchive* pArchive, const NuRecord* pRecord,
void Nu_SetCurrentDateTime(NuDateTime* pDateTime); void Nu_SetCurrentDateTime(NuDateTime* pDateTime);
Boolean Nu_IsOlder(const NuDateTime* pWhen1, const NuDateTime* pWhen2); Boolean Nu_IsOlder(const NuDateTime* pWhen1, const NuDateTime* pWhen2);
NuError Nu_OpenOutputFile(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_OpenOutputFile(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread, const char* newPathname, char newFssep, const NuThread* pThread, const UNICHAR* newPathnameUNI, UNICHAR newFssep,
FILE** pFp); FILE** pFp);
NuError Nu_CloseOutputFile(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_CloseOutputFile(NuArchive* pArchive, const NuRecord* pRecord,
FILE* fp, const char* pathname); FILE* fp, const UNICHAR* pathnameUNI);
NuError Nu_OpenInputFile(NuArchive* pArchive, const char* pathname, NuError Nu_OpenInputFile(NuArchive* pArchive, const UNICHAR* pathnameUNI,
Boolean openRsrc, FILE** pFp); Boolean openRsrc, FILE** pFp);
NuError Nu_DeleteFile(const char* pathname); NuError Nu_DeleteFile(const UNICHAR* pathnameUNI);
NuError Nu_RenameFile(const char* fromPath, const char* toPath); NuError Nu_RenameFile(const UNICHAR* fromPathUNI, const UNICHAR* toPathUNI);
NuError Nu_FTell(FILE* fp, long* pOffset); NuError Nu_FTell(FILE* fp, long* pOffset);
NuError Nu_FSeek(FILE* fp, long offset, int ptrname); NuError Nu_FSeek(FILE* fp, long offset, int ptrname);
NuError Nu_FRead(FILE* fp, void* buf, size_t nbyte); NuError Nu_FRead(FILE* fp, void* buf, size_t nbyte);
@ -627,22 +629,23 @@ NuError Nu_TruncateOpenFile(FILE* fp, long length);
/* Funnel.c */ /* Funnel.c */
NuError Nu_ProgressDataInit_Compress(NuArchive* pArchive, NuError Nu_ProgressDataInit_Compress(NuArchive* pArchive,
NuProgressData* pProgressData, const NuRecord* pRecord, NuProgressData* pProgressData, const NuRecord* pRecord,
const char* origPathname); const UNICHAR* origPathnameUNI, const UNICHAR* pathnameUNI);
NuError Nu_ProgressDataInit_Expand(NuArchive* pArchive, NuError Nu_ProgressDataInit_Expand(NuArchive* pArchive,
NuProgressData* pProgressData, const NuRecord* pRecord, NuProgressData* pProgressData, const NuRecord* pRecord,
const char* newPathname, char newFssep, NuValue convertEOL); const UNICHAR* newPathnameUNI, UNICHAR newFssep,
const UNICHAR* origPathnameUNI, NuValue convertEOL);
NuError Nu_SendInitialProgress(NuArchive* pArchive, NuProgressData* pProgress); NuError Nu_SendInitialProgress(NuArchive* pArchive, NuProgressData* pProgress);
NuError Nu_FunnelNew(NuArchive* pArchive, NuDataSink* pDataSink, NuError Nu_FunnelNew(NuArchive* pArchive, NuDataSink* pDataSink,
NuValue convertEOL, NuValue convertEOLTo, NuProgressData* pProgress, NuValue convertEOL, NuValue convertEOLTo, NuProgressData* pProgress,
NuFunnel** ppFunnel); NuFunnel** ppFunnel);
NuError Nu_FunnelFree(NuArchive* pArchive, NuFunnel* pFunnel); NuError Nu_FunnelFree(NuArchive* pArchive, NuFunnel* pFunnel);
/*void Nu_FunnelSetMaxOutput(NuFunnel* pFunnel, ulong maxBytes);*/ /*void Nu_FunnelSetMaxOutput(NuFunnel* pFunnel, uint32_t maxBytes);*/
NuError Nu_FunnelWrite(NuArchive* pArchive, NuFunnel* pFunnel, NuError Nu_FunnelWrite(NuArchive* pArchive, NuFunnel* pFunnel,
const uchar* buffer, ulong count); const uint8_t* buffer, uint32_t count);
NuError Nu_FunnelFlush(NuArchive* pArchive, NuFunnel* pFunnel); NuError Nu_FunnelFlush(NuArchive* pArchive, NuFunnel* pFunnel);
NuError Nu_ProgressDataCompressPrep(NuArchive* pArchive, NuStraw* pStraw, NuError Nu_ProgressDataCompressPrep(NuArchive* pArchive, NuStraw* pStraw,
NuThreadFormat threadFormat, ulong sourceLen); NuThreadFormat threadFormat, uint32_t sourceLen);
NuError Nu_ProgressDataExpandPrep(NuArchive* pArchive, NuFunnel* pFunnel, NuError Nu_ProgressDataExpandPrep(NuArchive* pArchive, NuFunnel* pFunnel,
const NuThread* pThread); const NuThread* pThread);
NuError Nu_FunnelSetProgressState(NuFunnel* pFunnel, NuProgressState state); NuError Nu_FunnelSetProgressState(NuFunnel* pFunnel, NuProgressState state);
@ -654,32 +657,34 @@ NuError Nu_StrawNew(NuArchive* pArchive, NuDataSource* pDataSource,
NuError Nu_StrawFree(NuArchive* pArchive, NuStraw* pStraw); NuError Nu_StrawFree(NuArchive* pArchive, NuStraw* pStraw);
NuError Nu_StrawSetProgressState(NuStraw* pStraw, NuProgressState state); NuError Nu_StrawSetProgressState(NuStraw* pStraw, NuProgressState state);
NuError Nu_StrawSendProgressUpdate(NuArchive* pArchive, NuStraw* pStraw); NuError Nu_StrawSendProgressUpdate(NuArchive* pArchive, NuStraw* pStraw);
NuError Nu_StrawRead(NuArchive* pArchive, NuStraw* pStraw, uchar* buffer, NuError Nu_StrawRead(NuArchive* pArchive, NuStraw* pStraw, uint8_t* buffer,
long len); long len);
NuError Nu_StrawRewind(NuArchive* pArchive, NuStraw* pStraw); NuError Nu_StrawRewind(NuArchive* pArchive, NuStraw* pStraw);
/* Lzc.c */ /* Lzc.c */
NuError Nu_CompressLZC12(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, NuError Nu_CompressLZC12(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
ulong srcLen, ulong* pDstLen, ushort* pCrc); uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc);
NuError Nu_CompressLZC16(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, NuError Nu_CompressLZC16(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
ulong srcLen, ulong* pDstLen, ushort* pCrc); uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc);
NuError Nu_ExpandLZC(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_ExpandLZC(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc); const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc);
/* Lzw.c */ /* Lzw.c */
NuError Nu_CompressLZW1(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, NuError Nu_CompressLZW1(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
ulong srcLen, ulong* pDstLen, ushort* pCrc); uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc);
NuError Nu_CompressLZW2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, NuError Nu_CompressLZW2(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
ulong srcLen, ulong* pDstLen, ushort* pCrc); uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc);
NuError Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_ExpandLZW(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pThreadCrc); const NuThread* pThread, FILE* infp, NuFunnel* pFunnel,
uint16_t* pThreadCrc);
/* MiscUtils.c */ /* MiscUtils.c */
/*extern const char* kNufxLibName;*/ /*extern const char* kNufxLibName;*/
extern NuCallback gNuGlobalErrorMessageHandler; extern NuCallback gNuGlobalErrorMessageHandler;
const char* Nu_StrError(NuError err); const char* Nu_StrError(NuError err);
void Nu_ReportError(NuArchive* pArchive, const char* file, int line, void Nu_ReportError(NuArchive* pArchive, const char* file, int line,
const char* function, Boolean isDebug, NuError err, const char* format, ...) const char* function, Boolean isDebug, NuError err,
const UNICHAR* format, ...)
#if defined(__GNUC__) #if defined(__GNUC__)
__attribute__ ((format(printf, 7, 8))) __attribute__ ((format(printf, 7, 8)))
#endif #endif
@ -688,7 +693,7 @@ void Nu_ReportError(NuArchive* pArchive, const char* file, int line,
# define Nu_Malloc(archive, size) malloc(size) # define Nu_Malloc(archive, size) malloc(size)
# define Nu_Calloc(archive, size) calloc(1, size) # define Nu_Calloc(archive, size) calloc(1, size)
# define Nu_Realloc(archive, ptr, size) realloc(ptr, size) # define Nu_Realloc(archive, ptr, size) realloc(ptr, size)
# define Nu_Free(archive, ptr) (ptr != nil ? free(ptr) : (void)0) # define Nu_Free(archive, ptr) (ptr != NULL ? free(ptr) : (void)0)
#else #else
void* Nu_Malloc(NuArchive* pArchive, size_t size); void* Nu_Malloc(NuArchive* pArchive, size_t size);
void* Nu_Calloc(NuArchive* pArchive, size_t size); void* Nu_Calloc(NuArchive* pArchive, size_t size);
@ -701,8 +706,8 @@ NuResult Nu_InternalFreeCallback(NuArchive* pArchive, void* args);
void Nu_RecordAddThreadMod(NuRecord* pRecord, NuThreadMod* pThreadMod); void Nu_RecordAddThreadMod(NuRecord* pRecord, NuThreadMod* pThreadMod);
Boolean Nu_RecordIsEmpty(NuArchive* pArchive, const NuRecord* pRecord); Boolean Nu_RecordIsEmpty(NuArchive* pArchive, const NuRecord* pRecord);
Boolean Nu_RecordSet_GetLoaded(const NuRecordSet* pRecordSet); Boolean Nu_RecordSet_GetLoaded(const NuRecordSet* pRecordSet);
ulong Nu_RecordSet_GetNumRecords(const NuRecordSet* pRecordSet); uint32_t Nu_RecordSet_GetNumRecords(const NuRecordSet* pRecordSet);
void Nu_RecordSet_SetNumRecords(NuRecordSet* pRecordSet, ulong val); void Nu_RecordSet_SetNumRecords(NuRecordSet* pRecordSet, uint32_t val);
void Nu_RecordSet_IncNumRecords(NuRecordSet* pRecordSet); void Nu_RecordSet_IncNumRecords(NuRecordSet* pRecordSet);
NuRecord* Nu_RecordSet_GetListHead(const NuRecordSet* pRecordSet); NuRecord* Nu_RecordSet_GetListHead(const NuRecordSet* pRecordSet);
NuRecord** Nu_RecordSet_GetListHeadPtr(NuRecordSet* pRecordSet); NuRecord** Nu_RecordSet_GetListHeadPtr(NuRecordSet* pRecordSet);
@ -738,19 +743,19 @@ NuError Nu_Test(NuArchive* pArchive);
NuError Nu_TestRecord(NuArchive* pArchive, NuRecordIdx recIdx); NuError Nu_TestRecord(NuArchive* pArchive, NuRecordIdx recIdx);
NuError Nu_GetRecord(NuArchive* pArchive, NuRecordIdx recordIdx, NuError Nu_GetRecord(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecord** ppRecord); const NuRecord** ppRecord);
NuError Nu_GetRecordIdxByName(NuArchive* pArchive, const char* name, NuError Nu_GetRecordIdxByName(NuArchive* pArchive, const char* nameMOR,
NuRecordIdx* pRecordIdx); NuRecordIdx* pRecordIdx);
NuError Nu_GetRecordIdxByPosition(NuArchive* pArchive, ulong position, NuError Nu_GetRecordIdxByPosition(NuArchive* pArchive, uint32_t position,
NuRecordIdx* pRecordIdx); NuRecordIdx* pRecordIdx);
NuError Nu_FindRecordForWriteByIdx(NuArchive* pArchive, NuRecordIdx recIdx, NuError Nu_FindRecordForWriteByIdx(NuArchive* pArchive, NuRecordIdx recIdx,
NuRecord** ppFoundRecord); NuRecord** ppFoundRecord);
NuError Nu_AddFile(NuArchive* pArchive, const char* pathname, NuError Nu_AddFile(NuArchive* pArchive, const UNICHAR* pathnameUNI,
const NuFileDetails* pFileDetails, Boolean fromRsrcFork, const NuFileDetails* pFileDetails, Boolean fromRsrcFork,
NuRecordIdx* pRecordIdx); NuRecordIdx* pRecordIdx);
NuError Nu_AddRecord(NuArchive* pArchive, const NuFileDetails* pFileDetails, NuError Nu_AddRecord(NuArchive* pArchive, const NuFileDetails* pFileDetails,
NuRecordIdx* pRecordIdx, NuRecord** ppRecord); NuRecordIdx* pRecordIdx, NuRecord** ppRecord);
NuError Nu_Rename(NuArchive* pArchive, NuRecordIdx recIdx, NuError Nu_Rename(NuArchive* pArchive, NuRecordIdx recIdx,
const char* pathname, char fssep); const char* pathnameMOR, char fssepMOR);
NuError Nu_SetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx, NuError Nu_SetRecordAttr(NuArchive* pArchive, NuRecordIdx recordIdx,
const NuRecordAttr* pRecordAttr); const NuRecordAttr* pRecordAttr);
NuError Nu_Delete(NuArchive* pArchive); NuError Nu_Delete(NuArchive* pArchive);
@ -758,88 +763,74 @@ NuError Nu_DeleteRecord(NuArchive* pArchive, NuRecordIdx rec);
/* SourceSink.c */ /* SourceSink.c */
NuError Nu_DataSourceFile_New(NuThreadFormat threadFormat, NuError Nu_DataSourceFile_New(NuThreadFormat threadFormat,
ulong otherLen, const char* pathname, Boolean isFromRsrcFork, uint32_t otherLen, const UNICHAR* pathnameUNI, Boolean isFromRsrcFork,
NuDataSource** ppDataSource); NuDataSource** ppDataSource);
NuError Nu_DataSourceFP_New(NuThreadFormat threadFormat, NuError Nu_DataSourceFP_New(NuThreadFormat threadFormat,
ulong otherLen, FILE* fp, long offset, long length, uint32_t otherLen, FILE* fp, long offset, long length,
NuCallback fcloseFunc, NuDataSource** ppDataSource); NuCallback fcloseFunc, NuDataSource** ppDataSource);
NuError Nu_DataSourceBuffer_New(NuThreadFormat threadFormat, NuError Nu_DataSourceBuffer_New(NuThreadFormat threadFormat,
ulong otherLen, const uchar* buffer, long offset, long length, uint32_t otherLen, const uint8_t* buffer, long offset, long length,
NuCallback freeFunc, NuDataSource** ppDataSource); NuCallback freeFunc, NuDataSource** ppDataSource);
NuDataSource* Nu_DataSourceCopy(NuDataSource* pDataSource); NuDataSource* Nu_DataSourceCopy(NuDataSource* pDataSource);
NuError Nu_DataSourceFree(NuDataSource* pDataSource); NuError Nu_DataSourceFree(NuDataSource* pDataSource);
NuDataSourceType Nu_DataSourceGetType(const NuDataSource* pDataSource); NuDataSourceType Nu_DataSourceGetType(const NuDataSource* pDataSource);
NuThreadFormat Nu_DataSourceGetThreadFormat(const NuDataSource* pDataSource); NuThreadFormat Nu_DataSourceGetThreadFormat(const NuDataSource* pDataSource);
ulong Nu_DataSourceGetDataLen(const NuDataSource* pDataSource); uint32_t Nu_DataSourceGetDataLen(const NuDataSource* pDataSource);
ulong Nu_DataSourceGetOtherLen(const NuDataSource* pDataSource); uint32_t Nu_DataSourceGetOtherLen(const NuDataSource* pDataSource);
void Nu_DataSourceSetOtherLen(NuDataSource* pDataSource, long otherLen); void Nu_DataSourceSetOtherLen(NuDataSource* pDataSource, long otherLen);
ushort Nu_DataSourceGetRawCrc(const NuDataSource* pDataSource); uint16_t Nu_DataSourceGetRawCrc(const NuDataSource* pDataSource);
void Nu_DataSourceSetRawCrc(NuDataSource* pDataSource, ushort crc); void Nu_DataSourceSetRawCrc(NuDataSource* pDataSource, uint16_t crc);
NuError Nu_DataSourcePrepareInput(NuArchive* pArchive, NuError Nu_DataSourcePrepareInput(NuArchive* pArchive,
NuDataSource* pDataSource); NuDataSource* pDataSource);
void Nu_DataSourceUnPrepareInput(NuArchive* pArchive, void Nu_DataSourceUnPrepareInput(NuArchive* pArchive,
NuDataSource* pDataSource); NuDataSource* pDataSource);
const char* Nu_DataSourceFile_GetPathname(NuDataSource* pDataSource); const char* Nu_DataSourceFile_GetPathname(NuDataSource* pDataSource);
NuError Nu_DataSourceGetBlock(NuDataSource* pDataSource, uchar* buf, ulong len); NuError Nu_DataSourceGetBlock(NuDataSource* pDataSource, uint8_t* buf,
uint32_t len);
NuError Nu_DataSourceRewind(NuDataSource* pDataSource); NuError Nu_DataSourceRewind(NuDataSource* pDataSource);
NuError Nu_DataSinkFile_New(Boolean doExpand, NuValue convertEOL, NuError Nu_DataSinkFile_New(Boolean doExpand, NuValue convertEOL,
const char* pathname, char fssep, NuDataSink** ppDataSink); const UNICHAR* pathnameUNI, UNICHAR fssep, NuDataSink** ppDataSink);
NuError Nu_DataSinkFP_New(Boolean doExpand, NuValue convertEOL, FILE* fp, NuError Nu_DataSinkFP_New(Boolean doExpand, NuValue convertEOL, FILE* fp,
NuDataSink** ppDataSink); NuDataSink** ppDataSink);
NuError Nu_DataSinkBuffer_New(Boolean doExpand, NuValue convertEOL, NuError Nu_DataSinkBuffer_New(Boolean doExpand, NuValue convertEOL,
uchar* buffer, ulong bufLen, NuDataSink** ppDataSink); uint8_t* buffer, uint32_t bufLen, NuDataSink** ppDataSink);
NuError Nu_DataSinkVoid_New(Boolean doExpand, NuValue convertEOL, NuError Nu_DataSinkVoid_New(Boolean doExpand, NuValue convertEOL,
NuDataSink** ppDataSink); NuDataSink** ppDataSink);
NuError Nu_DataSinkFree(NuDataSink* pDataSink); NuError Nu_DataSinkFree(NuDataSink* pDataSink);
NuDataSinkType Nu_DataSinkGetType(const NuDataSink* pDataSink); NuDataSinkType Nu_DataSinkGetType(const NuDataSink* pDataSink);
Boolean Nu_DataSinkGetDoExpand(const NuDataSink* pDataSink); Boolean Nu_DataSinkGetDoExpand(const NuDataSink* pDataSink);
NuValue Nu_DataSinkGetConvertEOL(const NuDataSink* pDataSink); NuValue Nu_DataSinkGetConvertEOL(const NuDataSink* pDataSink);
ulong Nu_DataSinkGetOutCount(const NuDataSink* pDataSink); uint32_t Nu_DataSinkGetOutCount(const NuDataSink* pDataSink);
const char* Nu_DataSinkFile_GetPathname(const NuDataSink* pDataSink); const char* Nu_DataSinkFile_GetPathname(const NuDataSink* pDataSink);
char Nu_DataSinkFile_GetFssep(const NuDataSink* pDataSink); UNICHAR Nu_DataSinkFile_GetFssep(const NuDataSink* pDataSink);
FILE* Nu_DataSinkFile_GetFP(const NuDataSink* pDataSink); FILE* Nu_DataSinkFile_GetFP(const NuDataSink* pDataSink);
void Nu_DataSinkFile_SetFP(NuDataSink* pDataSink, FILE* fp); void Nu_DataSinkFile_SetFP(NuDataSink* pDataSink, FILE* fp);
void Nu_DataSinkFile_Close(NuDataSink* pDataSink); void Nu_DataSinkFile_Close(NuDataSink* pDataSink);
NuError Nu_DataSinkPutBlock(NuDataSink* pDataSink, const uchar* buf, ulong len); NuError Nu_DataSinkPutBlock(NuDataSink* pDataSink, const uint8_t* buf,
uint32_t len);
NuError Nu_DataSinkGetError(NuDataSink* pDataSink); NuError Nu_DataSinkGetError(NuDataSink* pDataSink);
/* Squeeze.c */ /* Squeeze.c */
NuError Nu_CompressHuffmanSQ(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, NuError Nu_CompressHuffmanSQ(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
ulong srcLen, ulong* pDstLen, ushort* pCrc); uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc);
NuError Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc); const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc);
/* Thread.c */ /* Thread.c */
#ifdef __Thread_c__
#define THREAD_INLINE /**/
#else
#define THREAD_INLINE extern inline
#endif
#if defined(inline) && !defined(__Thread_c__) /* somebody ovrd inline def? */
NuThread* Nu_GetThread(const NuRecord* pRecord, int idx); NuThread* Nu_GetThread(const NuRecord* pRecord, int idx);
#else
THREAD_INLINE NuThread*
Nu_GetThread(const NuRecord* pRecord, int idx)
{
if (idx >= (int)pRecord->recTotalThreads)
return nil;
else
return &pRecord->pThreads[idx];
}
#endif
void Nu_StripHiIfAllSet(char* str); void Nu_StripHiIfAllSet(char* str);
Boolean Nu_IsPresizedThreadID(NuThreadID threadID); Boolean Nu_IsPresizedThreadID(NuThreadID threadID);
Boolean Nu_IsCompressibleThreadID(NuThreadID threadID); Boolean Nu_IsCompressibleThreadID(NuThreadID threadID);
Boolean Nu_ThreadHasCRC(long recordVersion, NuThreadID threadID); Boolean Nu_ThreadHasCRC(uint16_t recordVersion, NuThreadID threadID);
NuError Nu_FindThreadByIdx(const NuRecord* pRecord, NuThreadIdx thread, NuError Nu_FindThreadByIdx(const NuRecord* pRecord, NuThreadIdx thread,
NuThread** ppThread); NuThread** ppThread);
NuError Nu_FindThreadByID(const NuRecord* pRecord, NuThreadID threadID, NuError Nu_FindThreadByID(const NuRecord* pRecord, NuThreadID threadID,
NuThread** ppThread); NuThread** ppThread);
void Nu_CopyThreadContents(NuThread* pDstThread, const NuThread* pSrcThread); void Nu_CopyThreadContents(NuThread* pDstThread, const NuThread* pSrcThread);
NuError Nu_ReadThreadHeaders(NuArchive* pArchive, NuRecord* pRecord, NuError Nu_ReadThreadHeaders(NuArchive* pArchive, NuRecord* pRecord,
ushort* pCrc); uint16_t* pCrc);
NuError Nu_WriteThreadHeaders(NuArchive* pArchive, NuRecord* pRecord, FILE* fp, NuError Nu_WriteThreadHeaders(NuArchive* pArchive, NuRecord* pRecord, FILE* fp,
ushort* pCrc); uint16_t* pCrc);
NuError Nu_ComputeThreadData(NuArchive* pArchive, NuRecord* pRecord); NuError Nu_ComputeThreadData(NuArchive* pArchive, NuRecord* pRecord);
NuError Nu_ScanThreads(NuArchive* pArchive, NuRecord* pRecord,long numThreads); NuError Nu_ScanThreads(NuArchive* pArchive, NuRecord* pRecord,long numThreads);
NuError Nu_ExtractThreadBulk(NuArchive* pArchive, const NuRecord* pRecord, NuError Nu_ExtractThreadBulk(NuArchive* pArchive, const NuRecord* pRecord,
@ -853,7 +844,7 @@ NuError Nu_OkayToAddThread(NuArchive* pArchive, const NuRecord* pRecord,
NuError Nu_AddThread(NuArchive* pArchive, NuRecordIdx rec, NuThreadID threadID, NuError Nu_AddThread(NuArchive* pArchive, NuRecordIdx rec, NuThreadID threadID,
NuDataSource* pDataSource, NuThreadIdx* pThreadIdx); NuDataSource* pDataSource, NuThreadIdx* pThreadIdx);
NuError Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx, NuError Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx,
NuDataSource* pDataSource, long* pMaxLen); NuDataSource* pDataSource, int32_t* pMaxLen);
NuError Nu_DeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx); NuError Nu_DeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx);
/* Value.c */ /* Value.c */
@ -864,7 +855,7 @@ NuThreadFormat Nu_ConvertCompressValToFormat(NuArchive* pArchive,
NuValue compValue); NuValue compValue);
/* Version.c */ /* Version.c */
NuError Nu_GetVersion(long* pMajorVersion, long* pMinorVersion, NuError Nu_GetVersion(int32_t* pMajorVersion, int32_t* pMinorVersion,
long* pBugVersion, const char** ppBuildDate, const char** ppBuildFlags); int32_t* pBugVersion, const char** ppBuildDate, const char** ppBuildFlags);
#endif /*__NufxLibPriv__*/ #endif /*NUFXLIB_NUFXLIBPRIV_H*/

View File

@ -1,4 +1,4 @@
NufxLib README, updated 2004/03/18 NufxLib README, updated 2014/12/23
http://www.nulib.com/ http://www.nulib.com/
See "COPYING-LIB" for distribution restrictions. See "COPYING-LIB" for distribution restrictions.
@ -42,11 +42,8 @@ for @CFLAGS@ is "-g -O2".
(Implicitly sets DEBUG_MSGS.) Spray lots of debugging output. (Implicitly sets DEBUG_MSGS.) Spray lots of debugging output.
If you want to do benchmarks, use "-O2 -DNDEBUG". The recommended If you want to do benchmarks, use "-O2 -DNDEBUG". The recommended
configuration during testing is "-g -O2 -DDEBUG_MSGS", so that verbose configuration is "-g -O2 -DDEBUG_MSGS", so that verbose debug output is
debug output is available when errors occur. available when errors occur.
The flags are stuffed into Version.c, so the application program can
examine and display the flags that were used to build the library.
BeOS BeOS
@ -67,14 +64,10 @@ If you're using BeOS/PPC, it will also do:
Mac OS X Mac OS X
======== ========
This works just like the UNIX version, with the exception that when you link This works just like the UNIX version, but includes support for resource
against nufxlib, your project must also link against the Carbon framework. forks and Finder file/aux types.
This can be done in ProjectBuilder by using the Add Framework option in the
Project menu, or by adding "-framework Carbon" to the gcc command line.
You'll see some warnings due to some namespace collisions between nufxlib and Tested with Xcode v5.1.1 and Mac OS 10.8.5.
Carbon, but everything will work fine. Carbon is used to provide support for
file types and resource forks.
Win32 Win32
@ -83,29 +76,24 @@ Win32
If you're using an environment that supports "configure" scripts, such as If you're using an environment that supports "configure" scripts, such as
DJGPP, follow the UNIX instructions. DJGPP, follow the UNIX instructions.
NufxLib has been tested with Microsoft Visual C++ 6.0. To build NufxLib, NufxLib has been tested with Microsoft Visual C++ 12 (Visual Studio 2013).
start up a DOS shell and run vcvars32.bat to set your environment. Run: To build NufxLib, run the "Visual Studio 2013 x86 Native Tools Command
Prompt" shortcut to get a shell. Change to the nufxlib directory, then:
nmake -f makefile.msc nmake -f makefile.msc
to build with debugging info, or
nmake -f makefile.msc nodebug=1
to build optimized.
See the makefile for comments about including zlib or libbz2. These When the build finishes, run "test-basic.exe" to confirm things are working.
need to be enabled at compile time and linked into the sample apps.
Once the library has been built, "cd samples" and run the same command there. If you want to have zlib support enabled, you will need to have zlib.h,
When it finishes, run "test-basic.exe". zconf.h, and zlib.lib copied into the directory. See "makefile.msc" for
more details.
If you want to build NufxLib as a DLL, use "makefile.dll" instead. The makefile builds NufxLib as a static library and as a DLL.
If you're using zlib or libbz2, these will need to be linked into the DLL.
The makefile currently assumes that you will want to use zlib.dll.
Other Notes Other Notes
=========== ===========
All of the source code is now formatted with spaces instead of tabs.
If you want to use the library in a multithreaded application, you should If you want to use the library in a multithreaded application, you should
define "USE_REENTRANT_CALLS" to tell it to use reentrant versions of define "USE_REENTRANT_CALLS" to tell it to use reentrant versions of
certain library calls. This defines _REENTRANT, which causes Solaris to certain library calls. This defines _REENTRANT, which causes Solaris to
@ -113,12 +101,19 @@ add the appropriate goodies. (Seems to me you'd always want this on, but
for some reason Solaris makes you take an extra step, so I'm not going to for some reason Solaris makes you take an extra step, so I'm not going to
define it by default.) define it by default.)
Originally, NufxLib / NuLib2 were intended to be usable natively on the
Apple IIgs, so some of the design decisions were influenced by the need
to minimize memory usage (e.g. being able to get a directory listing
without holding the entire directory in memory) and interact with GS/OS
(forked files have a single filename, files have type/auxtype). The IIgs
port was never started.
Legalese Legalese
======== ========
NufxLib, a NuFX archive manipulation library. NufxLib, a NuFX archive manipulation library.
Copyright (C) 2000-2007 by Andy McFadden, All Rights Reserved. Copyright (C) 2000-2014 by Andy McFadden, All Rights Reserved.
See COPYING for license. See COPYING for license.

File diff suppressed because it is too large Load Diff

View File

@ -19,13 +19,12 @@
/* /*
* Allocate a new DataSource structure. * Allocate a new DataSource structure.
*/ */
static NuError static NuError Nu_DataSourceNew(NuDataSource** ppDataSource)
Nu_DataSourceNew(NuDataSource** ppDataSource)
{ {
Assert(ppDataSource != nil); Assert(ppDataSource != NULL);
*ppDataSource = Nu_Malloc(nil, sizeof(**ppDataSource)); *ppDataSource = Nu_Malloc(NULL, sizeof(**ppDataSource));
if (*ppDataSource == nil) if (*ppDataSource == NULL)
return kNuErrMalloc; return kNuErrMalloc;
(*ppDataSource)->sourceType = kNuDataSourceUnknown; (*ppDataSource)->sourceType = kNuDataSourceUnknown;
@ -47,10 +46,9 @@ Nu_DataSourceNew(NuDataSource** ppDataSource)
* needed in the first place.) Buffer sources are a little scary since * needed in the first place.) Buffer sources are a little scary since
* they include a "curOffset" value. * they include a "curOffset" value.
* *
* Returns nil on error. * Returns NULL on error.
*/ */
NuDataSource* NuDataSource* Nu_DataSourceCopy(NuDataSource* pDataSource)
Nu_DataSourceCopy(NuDataSource* pDataSource)
{ {
Assert(pDataSource->common.refCount >= 1); Assert(pDataSource->common.refCount >= 1);
pDataSource->common.refCount++; pDataSource->common.refCount++;
@ -59,18 +57,18 @@ Nu_DataSourceCopy(NuDataSource* pDataSource)
#if 0 /* we used to copy them -- very bad idea */ #if 0 /* we used to copy them -- very bad idea */
NuDataSource* pNewDataSource; NuDataSource* pNewDataSource;
Assert(pDataSource != nil); Assert(pDataSource != NULL);
if (Nu_DataSourceNew(&pNewDataSource) != kNuErrNone) if (Nu_DataSourceNew(&pNewDataSource) != kNuErrNone)
return nil; return NULL;
Assert(pNewDataSource != nil); Assert(pNewDataSource != NULL);
/* this gets most of it */ /* this gets most of it */
memcpy(pNewDataSource, pDataSource, sizeof(*pNewDataSource)); memcpy(pNewDataSource, pDataSource, sizeof(*pNewDataSource));
/* copy anything we're sure to free up */ /* copy anything we're sure to free up */
if (pDataSource->sourceType == kNuDataSourceFromFile) { if (pDataSource->sourceType == kNuDataSourceFromFile) {
Assert(pDataSource->fromFile.fp == nil); /* does this matter? */ Assert(pDataSource->fromFile.fp == NULL); /* does this matter? */
pNewDataSource->fromFile.pathname = pNewDataSource->fromFile.pathname =
strdup(pDataSource->fromFile.pathname); strdup(pDataSource->fromFile.pathname);
} }
@ -89,10 +87,9 @@ Nu_DataSourceCopy(NuDataSource* pDataSource)
/* /*
* Free a data source structure, and any type-specific elements. * Free a data source structure, and any type-specific elements.
*/ */
NuError NuError Nu_DataSourceFree(NuDataSource* pDataSource)
Nu_DataSourceFree(NuDataSource* pDataSource)
{ {
if (pDataSource == nil) if (pDataSource == NULL)
return kNuErrNone; return kNuErrNone;
Assert(pDataSource->common.refCount > 0); Assert(pDataSource->common.refCount > 0);
@ -103,25 +100,25 @@ Nu_DataSourceFree(NuDataSource* pDataSource)
switch (pDataSource->sourceType) { switch (pDataSource->sourceType) {
case kNuDataSourceFromFile: case kNuDataSourceFromFile:
Nu_Free(nil, pDataSource->fromFile.pathname); Nu_Free(NULL, pDataSource->fromFile.pathnameUNI);
if (pDataSource->fromFile.fp != nil) { if (pDataSource->fromFile.fp != NULL) {
fclose(pDataSource->fromFile.fp); fclose(pDataSource->fromFile.fp);
pDataSource->fromFile.fp = nil; pDataSource->fromFile.fp = NULL;
} }
break; break;
case kNuDataSourceFromFP: case kNuDataSourceFromFP:
if (pDataSource->fromFP.fcloseFunc != nil && if (pDataSource->fromFP.fcloseFunc != NULL &&
pDataSource->fromFP.fp != nil) pDataSource->fromFP.fp != NULL)
{ {
(*pDataSource->fromFP.fcloseFunc)(nil, pDataSource->fromFP.fp); (*pDataSource->fromFP.fcloseFunc)(NULL, pDataSource->fromFP.fp);
pDataSource->fromFP.fp = nil; pDataSource->fromFP.fp = NULL;
} }
break; break;
case kNuDataSourceFromBuffer: case kNuDataSourceFromBuffer:
if (pDataSource->fromBuffer.freeFunc != nil) { if (pDataSource->fromBuffer.freeFunc != NULL) {
(*pDataSource->fromBuffer.freeFunc)(nil, (*pDataSource->fromBuffer.freeFunc)(NULL,
(void*)pDataSource->fromBuffer.buffer); (void*)pDataSource->fromBuffer.buffer);
pDataSource->fromBuffer.buffer = nil; pDataSource->fromBuffer.buffer = NULL;
} }
break; break;
case kNuDataSourceUnknown: case kNuDataSourceUnknown:
@ -131,7 +128,7 @@ Nu_DataSourceFree(NuDataSource* pDataSource)
return kNuErrInternal; return kNuErrInternal;
} }
Nu_Free(nil, pDataSource); Nu_Free(NULL, pDataSource);
return kNuErrNone; return kNuErrNone;
} }
@ -139,15 +136,15 @@ Nu_DataSourceFree(NuDataSource* pDataSource)
/* /*
* Create a data source for an unopened file. * Create a data source for an unopened file.
*/ */
NuError NuError Nu_DataSourceFile_New(NuThreadFormat threadFormat, uint32_t otherLen,
Nu_DataSourceFile_New(NuThreadFormat threadFormat, ulong otherLen, const UNICHAR* pathnameUNI, Boolean isFromRsrcFork,
const char* pathname, Boolean isFromRsrcFork, NuDataSource** ppDataSource) NuDataSource** ppDataSource)
{ {
NuError err; NuError err;
if (pathname == nil || if (pathnameUNI == NULL ||
!(isFromRsrcFork == true || isFromRsrcFork == false) || !(isFromRsrcFork == true || isFromRsrcFork == false) ||
ppDataSource == nil) ppDataSource == NULL)
{ {
return kNuErrInvalidArg; return kNuErrInvalidArg;
} }
@ -162,9 +159,9 @@ Nu_DataSourceFile_New(NuThreadFormat threadFormat, ulong otherLen,
(*ppDataSource)->common.otherLen = otherLen; (*ppDataSource)->common.otherLen = otherLen;
(*ppDataSource)->common.refCount = 1; (*ppDataSource)->common.refCount = 1;
(*ppDataSource)->fromFile.pathname = strdup(pathname); (*ppDataSource)->fromFile.pathnameUNI = strdup(pathnameUNI);
(*ppDataSource)->fromFile.fromRsrcFork = isFromRsrcFork; (*ppDataSource)->fromFile.fromRsrcFork = isFromRsrcFork;
(*ppDataSource)->fromFile.fp = nil; /* to be filled in later */ (*ppDataSource)->fromFile.fp = NULL; /* to be filled in later */
bail: bail:
return err; return err;
@ -175,20 +172,19 @@ bail:
* Create a data source for an open file at a specific offset. The FILE* * Create a data source for an open file at a specific offset. The FILE*
* must be seekable. * must be seekable.
*/ */
NuError NuError Nu_DataSourceFP_New(NuThreadFormat threadFormat, uint32_t otherLen,
Nu_DataSourceFP_New(NuThreadFormat threadFormat, ulong otherLen,
FILE* fp, long offset, long length, NuCallback fcloseFunc, FILE* fp, long offset, long length, NuCallback fcloseFunc,
NuDataSource** ppDataSource) NuDataSource** ppDataSource)
{ {
NuError err; NuError err;
if (fp == nil || offset < 0 || length < 0 || if (fp == NULL || offset < 0 || length < 0 ||
ppDataSource == nil) ppDataSource == NULL)
{ {
return kNuErrInvalidArg; return kNuErrInvalidArg;
} }
if (otherLen && otherLen < (ulong)length) { if (otherLen && otherLen < (uint32_t)length) {
DBUG(("--- rejecting FP len=%ld other=%ld\n", length, otherLen)); DBUG(("--- rejecting FP len=%ld other=%ld\n", length, otherLen));
err = kNuErrPreSizeOverflow; err = kNuErrPreSizeOverflow;
goto bail; goto bail;
@ -216,28 +212,27 @@ bail:
/* /*
* Create a data source for a buffer. * Create a data source for a buffer.
* *
* We allow "buffer" to be nil so long as "offset" and "length" are also * We allow "buffer" to be NULL so long as "offset" and "length" are also
* nil. This is useful for creating empty pre-sized buffers, such as * NULL. This is useful for creating empty pre-sized buffers, such as
* blank comment fields. * blank comment fields.
*/ */
NuError NuError Nu_DataSourceBuffer_New(NuThreadFormat threadFormat, uint32_t otherLen,
Nu_DataSourceBuffer_New(NuThreadFormat threadFormat, ulong otherLen, const uint8_t* buffer, long offset, long length, NuCallback freeFunc,
const uchar* buffer, long offset, long length, NuCallback freeFunc,
NuDataSource** ppDataSource) NuDataSource** ppDataSource)
{ {
NuError err; NuError err;
if (offset < 0 || length < 0 || ppDataSource == nil) if (offset < 0 || length < 0 || ppDataSource == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
if (buffer == nil && (offset != 0 || length != 0)) if (buffer == NULL && (offset != 0 || length != 0))
return kNuErrInvalidArg; return kNuErrInvalidArg;
if (buffer == nil) { if (buffer == NULL) {
DBUG(("+++ zeroing freeFunc for empty-buffer DataSource\n")); DBUG(("+++ zeroing freeFunc for empty-buffer DataSource\n"));
freeFunc = nil; freeFunc = NULL;
} }
if (otherLen && otherLen < (ulong)length) { if (otherLen && otherLen < (uint32_t)length) {
DBUG(("--- rejecting buffer len=%ld other=%ld\n", length, otherLen)); DBUG(("--- rejecting buffer len=%ld other=%ld\n", length, otherLen));
err = kNuErrPreSizeOverflow; err = kNuErrPreSizeOverflow;
goto bail; goto bail;
@ -267,34 +262,31 @@ bail:
/* /*
* Get the type of a NuDataSource. * Get the type of a NuDataSource.
*/ */
NuDataSourceType NuDataSourceType Nu_DataSourceGetType(const NuDataSource* pDataSource)
Nu_DataSourceGetType(const NuDataSource* pDataSource)
{ {
Assert(pDataSource != nil); Assert(pDataSource != NULL);
return pDataSource->sourceType; return pDataSource->sourceType;
} }
/* /*
* Get the threadFormat for a data source. * Get the threadFormat for a data source.
*/ */
NuThreadFormat NuThreadFormat Nu_DataSourceGetThreadFormat(const NuDataSource* pDataSource)
Nu_DataSourceGetThreadFormat(const NuDataSource* pDataSource)
{ {
Assert(pDataSource != nil); Assert(pDataSource != NULL);
return pDataSource->common.threadFormat; return pDataSource->common.threadFormat;
} }
/* /*
* Get "dataLen" from a dataSource. * Get "dataLen" from a dataSource.
*/ */
ulong uint32_t Nu_DataSourceGetDataLen(const NuDataSource* pDataSource)
Nu_DataSourceGetDataLen(const NuDataSource* pDataSource)
{ {
Assert(pDataSource != nil); Assert(pDataSource != NULL);
if (pDataSource->sourceType == kNuDataSourceFromFile) { if (pDataSource->sourceType == kNuDataSourceFromFile) {
/* dataLen can only be valid if file has been opened */ /* dataLen can only be valid if file has been opened */
Assert(pDataSource->fromFile.fp != nil); Assert(pDataSource->fromFile.fp != NULL);
} }
return pDataSource->common.dataLen; return pDataSource->common.dataLen;
@ -303,20 +295,18 @@ Nu_DataSourceGetDataLen(const NuDataSource* pDataSource)
/* /*
* Get "otherLen" from a dataSource. * Get "otherLen" from a dataSource.
*/ */
ulong uint32_t Nu_DataSourceGetOtherLen(const NuDataSource* pDataSource)
Nu_DataSourceGetOtherLen(const NuDataSource* pDataSource)
{ {
Assert(pDataSource != nil); Assert(pDataSource != NULL);
return pDataSource->common.otherLen; return pDataSource->common.otherLen;
} }
/* /*
* Change the "otherLen" value. * Change the "otherLen" value.
*/ */
void void Nu_DataSourceSetOtherLen(NuDataSource* pDataSource, long otherLen)
Nu_DataSourceSetOtherLen(NuDataSource* pDataSource, long otherLen)
{ {
Assert(pDataSource != nil && otherLen > 0); Assert(pDataSource != NULL && otherLen > 0);
pDataSource->common.otherLen = otherLen; pDataSource->common.otherLen = otherLen;
} }
@ -324,10 +314,9 @@ Nu_DataSourceSetOtherLen(NuDataSource* pDataSource, long otherLen)
/* /*
* Get the "raw CRC" value. * Get the "raw CRC" value.
*/ */
ushort uint16_t Nu_DataSourceGetRawCrc(const NuDataSource* pDataSource)
Nu_DataSourceGetRawCrc(const NuDataSource* pDataSource)
{ {
Assert(pDataSource != nil); Assert(pDataSource != NULL);
return pDataSource->common.rawCrc; return pDataSource->common.rawCrc;
} }
@ -335,10 +324,9 @@ Nu_DataSourceGetRawCrc(const NuDataSource* pDataSource)
* Set the "raw CRC" value. You would want to do this if the input was * Set the "raw CRC" value. You would want to do this if the input was
* already-compressed data, and you wanted to propagate the thread CRC. * already-compressed data, and you wanted to propagate the thread CRC.
*/ */
void void Nu_DataSourceSetRawCrc(NuDataSource* pDataSource, uint16_t crc)
Nu_DataSourceSetRawCrc(NuDataSource* pDataSource, ushort crc)
{ {
Assert(pDataSource != nil); Assert(pDataSource != NULL);
pDataSource->common.rawCrc = crc; pDataSource->common.rawCrc = crc;
} }
@ -346,11 +334,11 @@ Nu_DataSourceSetRawCrc(NuDataSource* pDataSource, ushort crc)
/* /*
* Prepare a data source for action. * Prepare a data source for action.
*/ */
NuError NuError Nu_DataSourcePrepareInput(NuArchive* pArchive,
Nu_DataSourcePrepareInput(NuArchive* pArchive, NuDataSource* pDataSource) NuDataSource* pDataSource)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
FILE* fileFp = nil; FILE* fileFp = NULL;
/* /*
* Doesn't apply to buffer sources. * Doesn't apply to buffer sources.
@ -372,11 +360,11 @@ Nu_DataSourcePrepareInput(NuArchive* pArchive, NuDataSource* pDataSource)
* We're adding from a file on disk. Open it. * We're adding from a file on disk. Open it.
*/ */
err = Nu_OpenInputFile(pArchive, err = Nu_OpenInputFile(pArchive,
pDataSource->fromFile.pathname, pDataSource->fromFile.fromRsrcFork, pDataSource->fromFile.pathnameUNI,
&fileFp); pDataSource->fromFile.fromRsrcFork, &fileFp);
BailError(err); BailError(err);
Assert(fileFp != nil); Assert(fileFp != NULL);
pDataSource->fromFile.fp = fileFp; pDataSource->fromFile.fp = fileFp;
err = Nu_GetFileLength(pArchive, fileFp, err = Nu_GetFileLength(pArchive, fileFp,
(long*)&pDataSource->common.dataLen); (long*)&pDataSource->common.dataLen);
@ -403,49 +391,47 @@ bail:
* call will take care of this eventually -- but for normal operation on * call will take care of this eventually -- but for normal operation on
* a large number of files, it's vital. * a large number of files, it's vital.
*/ */
void void Nu_DataSourceUnPrepareInput(NuArchive* pArchive, NuDataSource* pDataSource)
Nu_DataSourceUnPrepareInput(NuArchive* pArchive, NuDataSource* pDataSource)
{ {
if (Nu_DataSourceGetType(pDataSource) != kNuDataSourceFromFile) if (Nu_DataSourceGetType(pDataSource) != kNuDataSourceFromFile)
return; return;
if (pDataSource->fromFile.fp != nil) { if (pDataSource->fromFile.fp != NULL) {
fclose(pDataSource->fromFile.fp); fclose(pDataSource->fromFile.fp);
pDataSource->fromFile.fp = nil; pDataSource->fromFile.fp = NULL;
pDataSource->common.dataLen = 0; pDataSource->common.dataLen = 0;
} }
} }
/* /*
* Get the pathname from a "from-file" dataSource. * Get the pathname from a "from-file" dataSource. Returned string is UTF-8.
*/ */
const char* const char* Nu_DataSourceFile_GetPathname(NuDataSource* pDataSource)
Nu_DataSourceFile_GetPathname(NuDataSource* pDataSource)
{ {
Assert(pDataSource != nil); Assert(pDataSource != NULL);
Assert(pDataSource->sourceType == kNuDataSourceFromFile); Assert(pDataSource->sourceType == kNuDataSourceFromFile);
Assert(pDataSource->fromFile.pathname != nil); Assert(pDataSource->fromFile.pathnameUNI != NULL);
return pDataSource->fromFile.pathname; return pDataSource->fromFile.pathnameUNI;
} }
/* /*
* Read a block of data from a dataSource. * Read a block of data from a dataSource.
*/ */
NuError NuError Nu_DataSourceGetBlock(NuDataSource* pDataSource, uint8_t* buf,
Nu_DataSourceGetBlock(NuDataSource* pDataSource, uchar* buf, ulong len) uint32_t len)
{ {
NuError err; NuError err;
Assert(pDataSource != nil); Assert(pDataSource != NULL);
Assert(buf != nil); Assert(buf != NULL);
Assert(len > 0); Assert(len > 0);
switch (pDataSource->sourceType) { switch (pDataSource->sourceType) {
case kNuDataSourceFromFile: case kNuDataSourceFromFile:
Assert(pDataSource->fromFile.fp != nil); Assert(pDataSource->fromFile.fp != NULL);
err = Nu_FRead(pDataSource->fromFile.fp, buf, len); err = Nu_FRead(pDataSource->fromFile.fp, buf, len);
if (feof(pDataSource->fromFile.fp)) if (feof(pDataSource->fromFile.fp))
Nu_ReportError(NU_NILBLOB, err, "EOF hit unexpectedly"); Nu_ReportError(NU_NILBLOB, err, "EOF hit unexpectedly");
@ -479,16 +465,15 @@ Nu_DataSourceGetBlock(NuDataSource* pDataSource, uchar* buf, ulong len)
/* /*
* Rewind a data source to the start of its input. * Rewind a data source to the start of its input.
*/ */
NuError NuError Nu_DataSourceRewind(NuDataSource* pDataSource)
Nu_DataSourceRewind(NuDataSource* pDataSource)
{ {
NuError err; NuError err;
Assert(pDataSource != nil); Assert(pDataSource != NULL);
switch (pDataSource->sourceType) { switch (pDataSource->sourceType) {
case kNuDataSourceFromFile: case kNuDataSourceFromFile:
Assert(pDataSource->fromFile.fp != nil); Assert(pDataSource->fromFile.fp != NULL);
err = Nu_FSeek(pDataSource->fromFile.fp, 0, SEEK_SET); err = Nu_FSeek(pDataSource->fromFile.fp, 0, SEEK_SET);
break; /* fall through with error */ break; /* fall through with error */
case kNuDataSourceFromFP: case kNuDataSourceFromFP:
@ -518,13 +503,12 @@ Nu_DataSourceRewind(NuDataSource* pDataSource)
/* /*
* Allocate a new DataSink structure. * Allocate a new DataSink structure.
*/ */
static NuError static NuError Nu_DataSinkNew(NuDataSink** ppDataSink)
Nu_DataSinkNew(NuDataSink** ppDataSink)
{ {
Assert(ppDataSink != nil); Assert(ppDataSink != NULL);
*ppDataSink = Nu_Malloc(nil, sizeof(**ppDataSink)); *ppDataSink = Nu_Malloc(NULL, sizeof(**ppDataSink));
if (*ppDataSink == nil) if (*ppDataSink == NULL)
return kNuErrMalloc; return kNuErrMalloc;
(*ppDataSink)->sinkType = kNuDataSinkUnknown; (*ppDataSink)->sinkType = kNuDataSinkUnknown;
@ -536,16 +520,15 @@ Nu_DataSinkNew(NuDataSink** ppDataSink)
/* /*
* Free a data sink structure, and any type-specific elements. * Free a data sink structure, and any type-specific elements.
*/ */
NuError NuError Nu_DataSinkFree(NuDataSink* pDataSink)
Nu_DataSinkFree(NuDataSink* pDataSink)
{ {
if (pDataSink == nil) if (pDataSink == NULL)
return kNuErrNone; return kNuErrNone;
switch (pDataSink->sinkType) { switch (pDataSink->sinkType) {
case kNuDataSinkToFile: case kNuDataSinkToFile:
Nu_DataSinkFile_Close(pDataSink); Nu_DataSinkFile_Close(pDataSink);
Nu_Free(nil, pDataSink->toFile.pathname); Nu_Free(NULL, pDataSink->toFile.pathnameUNI);
break; break;
case kNuDataSinkToFP: case kNuDataSinkToFP:
break; break;
@ -560,7 +543,7 @@ Nu_DataSinkFree(NuDataSink* pDataSink)
return kNuErrInternal; return kNuErrInternal;
} }
Nu_Free(nil, pDataSink); Nu_Free(NULL, pDataSink);
return kNuErrNone; return kNuErrNone;
} }
@ -568,18 +551,17 @@ Nu_DataSinkFree(NuDataSink* pDataSink)
/* /*
* Create a data sink for an unopened file. * Create a data sink for an unopened file.
*/ */
NuError NuError Nu_DataSinkFile_New(Boolean doExpand, NuValue convertEOL,
Nu_DataSinkFile_New(Boolean doExpand, NuValue convertEOL, const char* pathname, const UNICHAR* pathnameUNI, UNICHAR fssep, NuDataSink** ppDataSink)
char fssep, NuDataSink** ppDataSink)
{ {
NuError err; NuError err;
if ((doExpand != true && doExpand != false) || if ((doExpand != true && doExpand != false) ||
(convertEOL != kNuConvertOff && convertEOL != kNuConvertOn && (convertEOL != kNuConvertOff && convertEOL != kNuConvertOn &&
convertEOL != kNuConvertAuto) || convertEOL != kNuConvertAuto) ||
pathname == nil || pathnameUNI == NULL ||
fssep == 0 || fssep == 0 ||
ppDataSink == nil) ppDataSink == NULL)
{ {
return kNuErrInvalidArg; return kNuErrInvalidArg;
} }
@ -594,10 +576,10 @@ Nu_DataSinkFile_New(Boolean doExpand, NuValue convertEOL, const char* pathname,
else else
(*ppDataSink)->common.convertEOL = kNuConvertOff; (*ppDataSink)->common.convertEOL = kNuConvertOff;
(*ppDataSink)->common.outCount = 0; (*ppDataSink)->common.outCount = 0;
(*ppDataSink)->toFile.pathname = strdup(pathname); (*ppDataSink)->toFile.pathnameUNI = strdup(pathnameUNI);
(*ppDataSink)->toFile.fssep = fssep; (*ppDataSink)->toFile.fssep = fssep;
(*ppDataSink)->toFile.fp = nil; (*ppDataSink)->toFile.fp = NULL;
bail: bail:
return err; return err;
@ -607,8 +589,7 @@ bail:
/* /*
* Create a data sink based on a file pointer. * Create a data sink based on a file pointer.
*/ */
NuError NuError Nu_DataSinkFP_New(Boolean doExpand, NuValue convertEOL, FILE* fp,
Nu_DataSinkFP_New(Boolean doExpand, NuValue convertEOL, FILE* fp,
NuDataSink** ppDataSink) NuDataSink** ppDataSink)
{ {
NuError err; NuError err;
@ -616,8 +597,8 @@ Nu_DataSinkFP_New(Boolean doExpand, NuValue convertEOL, FILE* fp,
if ((doExpand != true && doExpand != false) || if ((doExpand != true && doExpand != false) ||
(convertEOL != kNuConvertOff && convertEOL != kNuConvertOn && (convertEOL != kNuConvertOff && convertEOL != kNuConvertOn &&
convertEOL != kNuConvertAuto) || convertEOL != kNuConvertAuto) ||
fp == nil || fp == NULL ||
ppDataSink == nil) ppDataSink == NULL)
{ {
return kNuErrInvalidArg; return kNuErrInvalidArg;
} }
@ -642,18 +623,17 @@ bail:
/* /*
* Create a data sink for a buffer in memory. * Create a data sink for a buffer in memory.
*/ */
NuError NuError Nu_DataSinkBuffer_New(Boolean doExpand, NuValue convertEOL,
Nu_DataSinkBuffer_New(Boolean doExpand, NuValue convertEOL, uchar* buffer, uint8_t* buffer, uint32_t bufLen, NuDataSink** ppDataSink)
ulong bufLen, NuDataSink** ppDataSink)
{ {
NuError err; NuError err;
if ((doExpand != true && doExpand != false) || if ((doExpand != true && doExpand != false) ||
(convertEOL != kNuConvertOff && convertEOL != kNuConvertOn && (convertEOL != kNuConvertOff && convertEOL != kNuConvertOn &&
convertEOL != kNuConvertAuto) || convertEOL != kNuConvertAuto) ||
buffer == nil || buffer == NULL ||
bufLen == 0 || bufLen == 0 ||
ppDataSink == nil) ppDataSink == NULL)
{ {
return kNuErrInvalidArg; return kNuErrInvalidArg;
} }
@ -681,14 +661,13 @@ bail:
/* /*
* Create a data sink that goes nowhere. * Create a data sink that goes nowhere.
*/ */
NuError NuError Nu_DataSinkVoid_New(Boolean doExpand, NuValue convertEOL,
Nu_DataSinkVoid_New(Boolean doExpand, NuValue convertEOL,
NuDataSink** ppDataSink) NuDataSink** ppDataSink)
{ {
NuError err; NuError err;
Assert(doExpand == true || doExpand == false); Assert(doExpand == true || doExpand == false);
Assert(ppDataSink != nil); Assert(ppDataSink != NULL);
err = Nu_DataSinkNew(ppDataSink); err = Nu_DataSinkNew(ppDataSink);
BailErrorQuiet(err); BailErrorQuiet(err);
@ -706,10 +685,9 @@ bail:
/* /*
* Get the type of a NuDataSink. * Get the type of a NuDataSink.
*/ */
NuDataSinkType NuDataSinkType Nu_DataSinkGetType(const NuDataSink* pDataSink)
Nu_DataSinkGetType(const NuDataSink* pDataSink)
{ {
Assert(pDataSink != nil); Assert(pDataSink != NULL);
return pDataSink->sinkType; return pDataSink->sinkType;
} }
@ -717,8 +695,7 @@ Nu_DataSinkGetType(const NuDataSink* pDataSink)
/* /*
* Return the "doExpand" parameter from any kind of sink. * Return the "doExpand" parameter from any kind of sink.
*/ */
Boolean Boolean Nu_DataSinkGetDoExpand(const NuDataSink* pDataSink)
Nu_DataSinkGetDoExpand(const NuDataSink* pDataSink)
{ {
return pDataSink->common.doExpand; return pDataSink->common.doExpand;
} }
@ -726,8 +703,7 @@ Nu_DataSinkGetDoExpand(const NuDataSink* pDataSink)
/* /*
* Return the "convertEOL" parameter from any kind of sink. * Return the "convertEOL" parameter from any kind of sink.
*/ */
NuValue NuValue Nu_DataSinkGetConvertEOL(const NuDataSink* pDataSink)
Nu_DataSinkGetConvertEOL(const NuDataSink* pDataSink)
{ {
return pDataSink->common.convertEOL; return pDataSink->common.convertEOL;
} }
@ -735,32 +711,29 @@ Nu_DataSinkGetConvertEOL(const NuDataSink* pDataSink)
/* /*
* Return the #of bytes written to the sink. * Return the #of bytes written to the sink.
*/ */
ulong uint32_t Nu_DataSinkGetOutCount(const NuDataSink* pDataSink)
Nu_DataSinkGetOutCount(const NuDataSink* pDataSink)
{ {
return pDataSink->common.outCount; return pDataSink->common.outCount;
} }
/* /*
* Get "pathname" from a to-file sink. * Get "pathname" from a to-file sink. Returned string is UTF-8.
*/ */
const char* const char* Nu_DataSinkFile_GetPathname(const NuDataSink* pDataSink)
Nu_DataSinkFile_GetPathname(const NuDataSink* pDataSink)
{ {
Assert(pDataSink != nil); Assert(pDataSink != NULL);
Assert(pDataSink->sinkType == kNuDataSinkToFile); Assert(pDataSink->sinkType == kNuDataSinkToFile);
return pDataSink->toFile.pathname; return pDataSink->toFile.pathnameUNI;
} }
/* /*
* Get "fssep" from a to-file sink. * Get "fssep" from a to-file sink.
*/ */
char UNICHAR Nu_DataSinkFile_GetFssep(const NuDataSink* pDataSink)
Nu_DataSinkFile_GetFssep(const NuDataSink* pDataSink)
{ {
Assert(pDataSink != nil); Assert(pDataSink != NULL);
Assert(pDataSink->sinkType == kNuDataSinkToFile); Assert(pDataSink->sinkType == kNuDataSinkToFile);
return pDataSink->toFile.fssep; return pDataSink->toFile.fssep;
@ -769,10 +742,9 @@ Nu_DataSinkFile_GetFssep(const NuDataSink* pDataSink)
/* /*
* Get the "fp" for a file sink. * Get the "fp" for a file sink.
*/ */
FILE* FILE* Nu_DataSinkFile_GetFP(const NuDataSink* pDataSink)
Nu_DataSinkFile_GetFP(const NuDataSink* pDataSink)
{ {
Assert(pDataSink != nil); Assert(pDataSink != NULL);
Assert(pDataSink->sinkType == kNuDataSinkToFile); Assert(pDataSink->sinkType == kNuDataSinkToFile);
return pDataSink->toFile.fp; return pDataSink->toFile.fp;
@ -781,10 +753,9 @@ Nu_DataSinkFile_GetFP(const NuDataSink* pDataSink)
/* /*
* Set the "fp" for a file sink. * Set the "fp" for a file sink.
*/ */
void void Nu_DataSinkFile_SetFP(NuDataSink* pDataSink, FILE* fp)
Nu_DataSinkFile_SetFP(NuDataSink* pDataSink, FILE* fp)
{ {
Assert(pDataSink != nil); Assert(pDataSink != NULL);
Assert(pDataSink->sinkType == kNuDataSinkToFile); Assert(pDataSink->sinkType == kNuDataSinkToFile);
pDataSink->toFile.fp = fp; pDataSink->toFile.fp = fp;
@ -793,14 +764,13 @@ Nu_DataSinkFile_SetFP(NuDataSink* pDataSink, FILE* fp)
/* /*
* Close a to-file sink. * Close a to-file sink.
*/ */
void void Nu_DataSinkFile_Close(NuDataSink* pDataSink)
Nu_DataSinkFile_Close(NuDataSink* pDataSink)
{ {
Assert(pDataSink != nil); Assert(pDataSink != NULL);
if (pDataSink->toFile.fp != nil) { if (pDataSink->toFile.fp != NULL) {
fclose(pDataSink->toFile.fp); fclose(pDataSink->toFile.fp);
pDataSink->toFile.fp = nil; pDataSink->toFile.fp = NULL;
} }
} }
@ -808,24 +778,24 @@ Nu_DataSinkFile_Close(NuDataSink* pDataSink)
/* /*
* Write a block of data to a DataSink. * Write a block of data to a DataSink.
*/ */
NuError NuError Nu_DataSinkPutBlock(NuDataSink* pDataSink, const uint8_t* buf,
Nu_DataSinkPutBlock(NuDataSink* pDataSink, const uchar* buf, ulong len) uint32_t len)
{ {
NuError err; NuError err;
Assert(pDataSink != nil); Assert(pDataSink != NULL);
Assert(buf != nil); Assert(buf != NULL);
Assert(len > 0); Assert(len > 0);
switch (pDataSink->sinkType) { switch (pDataSink->sinkType) {
case kNuDataSinkToFile: case kNuDataSinkToFile:
Assert(pDataSink->toFile.fp != nil); Assert(pDataSink->toFile.fp != NULL);
err = Nu_FWrite(pDataSink->toFile.fp, buf, len); err = Nu_FWrite(pDataSink->toFile.fp, buf, len);
if (err != kNuErrNone) if (err != kNuErrNone)
return err; return err;
break; break;
case kNuDataSinkToFP: case kNuDataSinkToFP:
Assert(pDataSink->toFP.fp != nil); Assert(pDataSink->toFP.fp != NULL);
err = Nu_FWrite(pDataSink->toFP.fp, buf, len); err = Nu_FWrite(pDataSink->toFP.fp, buf, len);
if (err != kNuErrNone) if (err != kNuErrNone)
return err; return err;
@ -856,12 +826,11 @@ Nu_DataSinkPutBlock(NuDataSink* pDataSink, const uchar* buf, ulong len)
/* /*
* Figure out if one of our earlier writes has failed. * Figure out if one of our earlier writes has failed.
*/ */
NuError NuError Nu_DataSinkGetError(NuDataSink* pDataSink)
Nu_DataSinkGetError(NuDataSink* pDataSink)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
Assert(pDataSink != nil); Assert(pDataSink != NULL);
switch (pDataSink->sinkType) { switch (pDataSink->sinkType) {
case kNuDataSinkToFile: case kNuDataSinkToFile:

View File

@ -77,13 +77,13 @@ typedef struct EncTreeNode {
typedef struct SQState { typedef struct SQState {
NuArchive* pArchive; NuArchive* pArchive;
int doCalcCRC; /* boolean; if set, compute CRC on input */ int doCalcCRC; /* boolean; if set, compute CRC on input */
ushort crc; uint16_t crc;
NuStraw* pStraw; NuStraw* pStraw;
long uncompRemaining; long uncompRemaining;
#ifdef FULL_SQ_HEADER #ifdef FULL_SQ_HEADER
ushort checksum; uint16_t checksum;
#endif #endif
/* /*
@ -98,12 +98,12 @@ typedef struct SQState {
*/ */
EncTreeNode node[kNuSQNumNodes]; EncTreeNode node[kNuSQNumNodes];
int treeHead; /* index to head node of final tree */ int treeHead; /* index to head node of final tree */
/* encoding table */ /* encoding table */
int codeLen[kNuSQNumVals]; /* number of bits in code for symbol N */ int codeLen[kNuSQNumVals]; /* number of bits in code for symbol N */
ushort code[kNuSQNumVals]; /* bits for symbol N (first bit in lsb) */ uint16_t code[kNuSQNumVals]; /* bits for symbol N (first bit in lsb) */
ushort tmpCode; /* temporary code value */ uint16_t tmpCode; /* temporary code value */
} SQState; } SQState;
@ -117,11 +117,10 @@ typedef struct SQState {
* *
* Returns kNuSQEOFToken as the value when we're out of data. * Returns kNuSQEOFToken as the value when we're out of data.
*/ */
static NuError static NuError Nu_SQGetcCRC(SQState* pSqState, int* pSym)
Nu_SQGetcCRC(SQState* pSqState, int* pSym)
{ {
NuError err; NuError err;
uchar c; uint8_t c;
if (!pSqState->uncompRemaining) { if (!pSqState->uncompRemaining) {
*pSym = kNuSQEOFToken; *pSym = kNuSQEOFToken;
@ -148,8 +147,7 @@ Nu_SQGetcCRC(SQState* pSqState, int* pSym)
* *
* Returns kNuSQEOFToken in "*pSum" when we reach the end of the input. * Returns kNuSQEOFToken in "*pSum" when we reach the end of the input.
*/ */
static NuError static NuError Nu_SQGetcRLE(SQState* pSqState, int* pSym)
Nu_SQGetcRLE(SQState* pSqState, int* pSym)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
int likeCount, newSym; int likeCount, newSym;
@ -275,8 +273,7 @@ bail:
/* /*
* Return the greater of two integers. * Return the greater of two integers.
*/ */
static int static int Nu_SQMax(int a, int b)
Nu_SQMax(int a, int b)
{ {
if (a > b) if (a > b)
return a; return a;
@ -289,8 +286,7 @@ Nu_SQMax(int a, int b)
* Priority is given to weight, then depth. "a" and "b" are heaps, * Priority is given to weight, then depth. "a" and "b" are heaps,
* so we only need to look at the root element. * so we only need to look at the root element.
*/ */
static int static int Nu_SQCmpTrees(SQState* pSqState, int a, int b)
Nu_SQCmpTrees(SQState* pSqState, int a, int b)
{ {
if (pSqState->node[a].weight > pSqState->node[b].weight) if (pSqState->node[a].weight > pSqState->node[b].weight)
return true; return true;
@ -312,8 +308,7 @@ Nu_SQCmpTrees(SQState* pSqState, int a, int b)
/* /*
* Recursively make a heap from a heap with a new top. * Recursively make a heap from a heap with a new top.
*/ */
static void static void Nu_SQHeapAdjust(SQState* pSqState, int list[], int top, int bottom)
Nu_SQHeapAdjust(SQState* pSqState, int list[], int top, int bottom)
{ {
int k, temp; int k, temp;
@ -337,8 +332,7 @@ Nu_SQHeapAdjust(SQState* pSqState, int list[], int top, int bottom)
/* /*
* Create a heap. * Create a heap.
*/ */
static void static void Nu_SQHeap(SQState* pSqState, int list[], int length)
Nu_SQHeap(SQState* pSqState, int list[], int length)
{ {
int i; int i;
@ -365,8 +359,7 @@ Nu_SQHeap(SQState* pSqState, int list[], int length)
* moving the last element over the top element and * moving the last element over the top element and
* reheaping the shorter list. * reheaping the shorter list.
*/ */
static void static void Nu_SQBuildTree(SQState* pSqState, int list[], int len)
Nu_SQBuildTree(SQState* pSqState, int list[], int len)
{ {
int freenode; /* next free node in tree */ int freenode; /* next free node in tree */
EncTreeNode* frnp; /* free node pointer */ EncTreeNode* frnp; /* free node pointer */
@ -422,8 +415,7 @@ Nu_SQBuildTree(SQState* pSqState, int list[], int len)
* *
* Returns zero on success, nonzero if codes are too long. * Returns zero on success, nonzero if codes are too long.
*/ */
static int static int Nu_SQBuildEncTable(SQState* pSqState, int level, int root)
Nu_SQBuildEncTable(SQState* pSqState, int level, int root)
{ {
int l, r; int l, r;
@ -437,7 +429,7 @@ Nu_SQBuildEncTable(SQState* pSqState, int level, int root)
*/ */
pSqState->codeLen[root] = level; pSqState->codeLen[root] = level;
pSqState->code[root] = pSqState->code[root] =
pSqState->tmpCode & (((ushort)~0) >> (16 - level)); pSqState->tmpCode & (((uint16_t)~0) >> (16 - level));
return (level > 16) ? -1 : 0; return (level > 16) ? -1 : 0;
} else { } else {
if (l != kNuSQNoChild) { if (l != kNuSQNoChild) {
@ -470,12 +462,11 @@ Nu_SQBuildEncTable(SQState* pSqState, int level, int root)
* the codes will fit in an unsigned integer. Rescaling is * the codes will fit in an unsigned integer. Rescaling is
* used if necessary to limit the code length. * used if necessary to limit the code length.
*/ */
static void static void Nu_SQScale(SQState* pSqState, int ceiling)
Nu_SQScale(SQState* pSqState, int ceiling)
{ {
int i; int i;
int wt, ovflw, divisor; int wt, ovflw, divisor;
ushort sum; uint16_t sum;
int increased; /* flag */ int increased; /* flag */
do { do {
@ -510,8 +501,7 @@ Nu_SQScale(SQState* pSqState, int ceiling)
* Build a frequency table from the post-RLE input stream, then generate * Build a frequency table from the post-RLE input stream, then generate
* an encoding tree from the results. * an encoding tree from the results.
*/ */
static NuError static NuError Nu_SQComputeHuffTree(SQState* pSqState)
Nu_SQComputeHuffTree(SQState* pSqState)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
int btreeList[kNuSQNumVals]; /* list of intermediate binary trees */ int btreeList[kNuSQNumVals]; /* list of intermediate binary trees */
@ -610,12 +600,12 @@ bail:
* Compress data from input to output, using the values in the "code" * Compress data from input to output, using the values in the "code"
* and "codeLen" arrays. * and "codeLen" arrays.
*/ */
static NuError static NuError Nu_SQCompressInput(SQState* pSqState, FILE* fp,
Nu_SQCompressInput(SQState* pSqState, FILE* fp, long* pCompressedLen) long* pCompressedLen)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
int sym = kNuSQEOFToken-1; int sym = kNuSQEOFToken-1;
unsigned long bits, code; /* must hold at least 23 bits */ uint32_t bits, code; /* must hold at least 23 bits */
int codeLen, gotbits; int codeLen, gotbits;
long compressedLen; long compressedLen;
@ -661,11 +651,10 @@ bail:
/* /*
* Write a 16-bit value in little-endian order. * Write a 16-bit value in little-endian order.
*/ */
static NuError static NuError Nu_SQWriteShort(FILE* outfp, short val)
Nu_SQWriteShort(FILE* outfp, short val)
{ {
NuError err; NuError err;
uchar tmpc; uint8_t tmpc;
tmpc = val & 0xff; tmpc = val & 0xff;
err = Nu_FWrite(outfp, &tmpc, 1); err = Nu_FWrite(outfp, &tmpc, 1);
@ -689,9 +678,8 @@ bail:
* it an empty file. "xsq" works fine, creating an empty tree that * it an empty file. "xsq" works fine, creating an empty tree that
* "xusq" unpacks. * "xusq" unpacks.
*/ */
NuError NuError Nu_CompressHuffmanSQ(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
Nu_CompressHuffmanSQ(NuArchive* pArchive, NuStraw* pStraw, FILE* fp, uint32_t srcLen, uint32_t* pDstLen, uint16_t* pCrc)
ulong srcLen, ulong* pDstLen, ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
SQState sqState; SQState sqState;
@ -704,7 +692,7 @@ Nu_CompressHuffmanSQ(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
sqState.pArchive = pArchive; sqState.pArchive = pArchive;
sqState.crc = 0; sqState.crc = 0;
if (pCrc == nil) { if (pCrc == NULL) {
sqState.doCalcCRC = false; sqState.doCalcCRC = false;
} else { } else {
sqState.doCalcCRC = true; sqState.doCalcCRC = true;
@ -727,7 +715,7 @@ Nu_CompressHuffmanSQ(NuArchive* pArchive, NuStraw* pStraw, FILE* fp,
err = Nu_SQComputeHuffTree(&sqState); err = Nu_SQComputeHuffTree(&sqState);
BailError(err); BailError(err);
if (pCrc != nil) if (pCrc != NULL)
*pCrc = sqState.crc; *pCrc = sqState.crc;
/* /*
@ -822,8 +810,8 @@ bail:
* State during uncompression. * State during uncompression.
*/ */
typedef struct USQState { typedef struct USQState {
ulong dataInBuffer; uint32_t dataInBuffer;
uchar* dataPtr; uint8_t* dataPtr;
int bitPosn; int bitPosn;
int bits; int bits;
@ -842,8 +830,7 @@ typedef struct USQState {
/* /*
* Decode the next symbol from the Huffman stream. * Decode the next symbol from the Huffman stream.
*/ */
static NuError static NuError Nu_USQDecodeHuffSymbol(USQState* pUsqState, int* pVal)
Nu_USQDecodeHuffSymbol(USQState* pUsqState, int* pVal)
{ {
short val = 0; short val = 0;
int bits, bitPosn; int bits, bitPosn;
@ -879,8 +866,7 @@ Nu_USQDecodeHuffSymbol(USQState* pUsqState, int* pVal)
/* /*
* Read two bytes of signed data out of the buffer. * Read two bytes of signed data out of the buffer.
*/ */
static inline NuError static inline NuError Nu_USQReadShort(USQState* pUsqState, short* pShort)
Nu_USQReadShort(USQState* pUsqState, short* pShort)
{ {
if (pUsqState->dataInBuffer < 2) if (pUsqState->dataInBuffer < 2)
return kNuErrBufferUnderrun; return kNuErrBufferUnderrun;
@ -898,24 +884,23 @@ Nu_USQReadShort(USQState* pUsqState, short* pShort)
* Because we have a stop symbol, knowing the uncompressed length of * Because we have a stop symbol, knowing the uncompressed length of
* the file is not essential. * the file is not essential.
*/ */
NuError NuError Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord,
Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord, const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, uint16_t* pCrc)
const NuThread* pThread, FILE* infp, NuFunnel* pFunnel, ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
USQState usqState; USQState usqState;
ulong compRemaining, getSize; uint32_t compRemaining, getSize;
#ifdef FULL_SQ_HEADER #ifdef FULL_SQ_HEADER
ushort magic, fileChecksum, checksum; uint16_t magic, fileChecksum, checksum;
#endif #endif
short nodeCount; short nodeCount;
int i, inrep; int i, inrep;
uchar lastc = 0; uint8_t lastc = 0;
err = Nu_AllocCompressionBufferIFN(pArchive); err = Nu_AllocCompressionBufferIFN(pArchive);
if (err != kNuErrNone) if (err != kNuErrNone)
return err; return err;
Assert(pArchive->compBuf != nil); Assert(pArchive->compBuf != NULL);
usqState.dataInBuffer = 0; usqState.dataInBuffer = 0;
usqState.dataPtr = pArchive->compBuf; usqState.dataPtr = pArchive->compBuf;
@ -945,7 +930,7 @@ Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord,
err = Nu_FRead(infp, usqState.dataPtr, getSize); err = Nu_FRead(infp, usqState.dataPtr, getSize);
if (err != kNuErrNone) { if (err != kNuErrNone) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"failed reading compressed data (%ld bytes)", getSize); "failed reading compressed data (%u bytes)", getSize);
goto bail; goto bail;
} }
usqState.dataInBuffer += getSize; usqState.dataInBuffer += getSize;
@ -1046,7 +1031,7 @@ Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord,
getSize); getSize);
if (err != kNuErrNone) { if (err != kNuErrNone) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"failed reading compressed data (%ld bytes)", getSize); "failed reading compressed data (%u bytes)", getSize);
goto bail; goto bail;
} }
usqState.dataInBuffer += getSize; usqState.dataInBuffer += getSize;
@ -1080,7 +1065,7 @@ Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord,
val = 2; val = 2;
} }
while (--val) { while (--val) {
if (pCrc != nil) if (pCrc != NULL)
*pCrc = Nu_CalcCRC16(*pCrc, &lastc, 1); *pCrc = Nu_CalcCRC16(*pCrc, &lastc, 1);
err = Nu_FunnelWrite(pArchive, pFunnel, &lastc, 1); err = Nu_FunnelWrite(pArchive, pFunnel, &lastc, 1);
#ifdef FULL_SQ_HEADER #ifdef FULL_SQ_HEADER
@ -1095,7 +1080,7 @@ Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord,
inrep = true; inrep = true;
} else { } else {
lastc = val; lastc = val;
if (pCrc != nil) if (pCrc != NULL)
*pCrc = Nu_CalcCRC16(*pCrc, &lastc, 1); *pCrc = Nu_CalcCRC16(*pCrc, &lastc, 1);
err = Nu_FunnelWrite(pArchive, pFunnel, &lastc, 1); err = Nu_FunnelWrite(pArchive, pFunnel, &lastc, 1);
#ifdef FULL_SQ_HEADER #ifdef FULL_SQ_HEADER
@ -1135,7 +1120,7 @@ Nu_ExpandHuffmanSQ(NuArchive* pArchive, const NuRecord* pRecord,
if (usqState.dataInBuffer > 1) { if (usqState.dataInBuffer > 1) {
DBUG(("--- Found %ld bytes following compressed data (compRem=%ld)\n", DBUG(("--- Found %ld bytes following compressed data (compRem=%ld)\n",
usqState.dataInBuffer, compRemaining)); usqState.dataInBuffer, compRemaining));
Nu_ReportError(NU_BLOB, kNuErrNone, "(Warning) unexpected fluff (%ld)", Nu_ReportError(NU_BLOB, kNuErrNone, "(Warning) unexpected fluff (%u)",
usqState.dataInBuffer); usqState.dataInBuffer);
} }

View File

@ -1,46 +0,0 @@
/*
* Copyright (C) 2000-2007 by Andy McFadden, All Rights Reserved.
* This is free software; you can redistribute it and/or modify it under the
* terms of the BSD License, see the file COPYING-LIB.
*
* This file was adapted from Devin Reade's "sunos4.h" in NuLib 3.2.5.
* It is provided for compilation under SunOS 4.x, when an ANSI compiler
* (such as gcc) is used. The system header files aren't quite sufficient
* to eliminate hordes of warnings.
*/
#ifndef __SunOS4__
#define __SunOS4__
#ifdef __GNUC__
extern int _flsbuf(int, FILE*);
extern int _filbuf(FILE*);
#endif
extern void bcopy(char*, char*, int);
extern int fclose(FILE*);
extern int fflush(FILE*);
extern int fprintf(FILE*, const char*, ...);
extern int fread(char*, int, int, FILE *);
extern int fseek(FILE*, long, int);
extern int ftruncate(int, off_t);
extern int fwrite(const char*, int, int, FILE*);
extern char* mktemp(char *template);
extern time_t mktime(struct tm*);
extern int perror(const char*);
extern int printf(const char*, ...);
extern int remove(const char*);
extern int rename(const char*, const char*);
extern int tolower(int);
extern int setvbuf(FILE*, char*, int, int);
extern int sscanf(char*, const char*, ...);
extern int strcasecmp(const char*, const char*);
extern int strncasecmp(const char*, const char*, size_t);
extern long strtol(const char *, char **, int);
extern int system(const char*);
extern time_t timelocal(struct tm*);
extern time_t time(time_t*);
extern int toupper(int);
extern int vfprintf(FILE*, const char *, va_list);
extern char* vsprintf(char *str, const char *format, va_list ap);
#endif /*__SunOS4__*/

View File

@ -6,8 +6,8 @@
* *
* External type definitions and function prototypes. * External type definitions and function prototypes.
*/ */
#ifndef __SysDefs__ #ifndef NUFXLIB_SYSDEFS_H
#define __SysDefs__ #define NUFXLIB_SYSDEFS_H
#ifdef HAVE_CONFIG_H #ifdef HAVE_CONFIG_H
# include <config.h> # include <config.h>
@ -18,7 +18,6 @@
#endif #endif
/* these should exist everywhere */ /* these should exist everywhere */
#include <stdio.h>
#include <stdarg.h> #include <stdarg.h>
#include <string.h> #include <string.h>
#include <memory.h> #include <memory.h>
@ -55,10 +54,6 @@
# define SNPRINTF_DECLARED # define SNPRINTF_DECLARED
# define VSNPRINTF_DECLARED # define VSNPRINTF_DECLARED
# define SPRINTF_RETURNS_INT # define SPRINTF_RETURNS_INT
# define uchar unsigned char
# define ushort unsigned short
# define uint unsigned int
# define ulong unsigned long
# define inline /*Visual C++6.0 can't inline ".c" files*/ # define inline /*Visual C++6.0 can't inline ".c" files*/
# define mode_t int # define mode_t int
# define ENABLE_SQ # define ENABLE_SQ
@ -74,6 +69,7 @@
# define HAVE_CHSIZE # define HAVE_CHSIZE
# define snprintf _snprintf # define snprintf _snprintf
# define vsnprintf _vsnprintf # define vsnprintf _vsnprintf
#endif #endif
#ifdef HAVE_MALLOC_H #ifdef HAVE_MALLOC_H
@ -123,26 +119,18 @@
# endif # endif
#endif #endif
/* resource forks on UFS filesystem under Mac OS X are a kluge */ /* not currently using filesystem resource forks */
/*#ifdef MAC*/ //#if defined(__ORCAC__) || defined(MAC_LIKE)
/*# define HAS_RESOURCE_FORKS*/ //# define HAS_RESOURCE_FORKS
/*#endif*/ //#endif
#if defined(__ORCAC__) || defined(MAC_LIKE)
# define HAS_RESOURCE_FORKS
#endif
/* __FUNCTION__ was missing from BeOS __MWERKS__, and might be gcc-only */ /* __FUNCTION__ was missing from BeOS __MWERKS__, and might be gcc-only */
#ifdef __GNUC__ #ifdef __GNUC__
# define HAS__FUNCTION__ # define HAS__FUNCTION__
#endif #endif
#if defined(__sun__) && !defined(__SVR4)
# include "SunOS4.h"
#endif
#if defined(__linux__) #if defined(__linux__)
# define HAS_MALLOC_CHECK_ # define HAS_MALLOC_CHECK_
#endif #endif
#endif /*__SysDefs__*/ #endif /*NUFXLIB_SYSDEFS_H*/

View File

@ -6,7 +6,6 @@
* *
* Thread-level operations. * Thread-level operations.
*/ */
#define __Thread_c__ 1
#include "NufxLibPriv.h" #include "NufxLibPriv.h"
@ -16,6 +15,17 @@
* =========================================================================== * ===========================================================================
*/ */
/*
* Returns thread N, or NULL if the index is invalid.
*/
NuThread* Nu_GetThread(const NuRecord* pRecord, int idx)
{
if (idx >= (int)pRecord->recTotalThreads)
return NULL;
else
return &pRecord->pThreads[idx];
}
/* /*
* ShrinkIt v3.0.0 had a bug where the filename thread would get created * ShrinkIt v3.0.0 had a bug where the filename thread would get created
* with the high bits set. We want to undo that without stomping on * with the high bits set. We want to undo that without stomping on
@ -26,16 +36,15 @@
* This high-bit-ism was also done for disk archives by most older versions * This high-bit-ism was also done for disk archives by most older versions
* of ShrinkIt. * of ShrinkIt.
*/ */
void void Nu_StripHiIfAllSet(char* str)
Nu_StripHiIfAllSet(char* str)
{ {
uchar* cp; uint8_t* cp;
for (cp = (uchar*)str; *cp != '\0'; cp++) for (cp = (uint8_t*)str; *cp != '\0'; cp++)
if (!(*cp & 0x80)) if (!(*cp & 0x80))
return; return;
for (cp = (uchar*)str; *cp != '\0'; cp++) for (cp = (uint8_t*)str; *cp != '\0'; cp++)
*cp &= 0x7f; *cp &= 0x7f;
} }
@ -44,8 +53,7 @@ Nu_StripHiIfAllSet(char* str)
* Decide if a thread is pre-sized (i.e. has a fixed maximum size with a * Decide if a thread is pre-sized (i.e. has a fixed maximum size with a
* lesser amount of uncompressed data within) based on the threadID. * lesser amount of uncompressed data within) based on the threadID.
*/ */
Boolean Boolean Nu_IsPresizedThreadID(NuThreadID threadID)
Nu_IsPresizedThreadID(NuThreadID threadID)
{ {
if (threadID == kNuThreadIDFilename || threadID == kNuThreadIDComment) if (threadID == kNuThreadIDFilename || threadID == kNuThreadIDComment)
return true; return true;
@ -58,8 +66,7 @@ Nu_IsPresizedThreadID(NuThreadID threadID)
* Return an indication of whether the type of thread specified by ThreadID * Return an indication of whether the type of thread specified by ThreadID
* should ever be compressed. Right now, that's only data-class threads. * should ever be compressed. Right now, that's only data-class threads.
*/ */
Boolean Boolean Nu_IsCompressibleThreadID(NuThreadID threadID)
Nu_IsCompressibleThreadID(NuThreadID threadID)
{ {
if (NuThreadIDGetClass(threadID) == kNuThreadClassData) if (NuThreadIDGetClass(threadID) == kNuThreadClassData)
return true; return true;
@ -72,8 +79,7 @@ Nu_IsCompressibleThreadID(NuThreadID threadID)
* Decide if the thread has a CRC, based on the record version and the * Decide if the thread has a CRC, based on the record version and the
* threadID. * threadID.
*/ */
Boolean Boolean Nu_ThreadHasCRC(uint16_t recordVersion, NuThreadID threadID)
Nu_ThreadHasCRC(long recordVersion, NuThreadID threadID)
{ {
return recordVersion >= 3 && return recordVersion >= 3 &&
NuThreadIDGetClass(threadID) == kNuThreadClassData; NuThreadIDGetClass(threadID) == kNuThreadClassData;
@ -83,8 +89,7 @@ Nu_ThreadHasCRC(long recordVersion, NuThreadID threadID)
/* /*
* Search through a given NuRecord for the specified thread. * Search through a given NuRecord for the specified thread.
*/ */
NuError NuError Nu_FindThreadByIdx(const NuRecord* pRecord, NuThreadIdx thread,
Nu_FindThreadByIdx(const NuRecord* pRecord, NuThreadIdx thread,
NuThread** ppThread) NuThread** ppThread)
{ {
NuThread* pThread; NuThread* pThread;
@ -92,7 +97,7 @@ Nu_FindThreadByIdx(const NuRecord* pRecord, NuThreadIdx thread,
for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) { for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) {
pThread = Nu_GetThread(pRecord, idx); pThread = Nu_GetThread(pRecord, idx);
Assert(pThread != nil); Assert(pThread != NULL);
if (pThread->threadIdx == thread) { if (pThread->threadIdx == thread) {
*ppThread = pThread; *ppThread = pThread;
@ -108,8 +113,7 @@ Nu_FindThreadByIdx(const NuRecord* pRecord, NuThreadIdx thread,
* Search through a given NuRecord for the first thread with a matching * Search through a given NuRecord for the first thread with a matching
* threadID. * threadID.
*/ */
NuError NuError Nu_FindThreadByID(const NuRecord* pRecord, NuThreadID threadID,
Nu_FindThreadByID(const NuRecord* pRecord, NuThreadID threadID,
NuThread** ppThread) NuThread** ppThread)
{ {
NuThread* pThread; NuThread* pThread;
@ -117,7 +121,7 @@ Nu_FindThreadByID(const NuRecord* pRecord, NuThreadID threadID,
for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) { for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) {
pThread = Nu_GetThread(pRecord, idx); pThread = Nu_GetThread(pRecord, idx);
Assert(pThread != nil); Assert(pThread != NULL);
if (NuGetThreadID(pThread) == threadID) { if (NuGetThreadID(pThread) == threadID) {
*ppThread = pThread; *ppThread = pThread;
@ -132,11 +136,10 @@ Nu_FindThreadByID(const NuRecord* pRecord, NuThreadID threadID,
/* /*
* Copy the contents of a NuThread. * Copy the contents of a NuThread.
*/ */
void void Nu_CopyThreadContents(NuThread* pDstThread, const NuThread* pSrcThread)
Nu_CopyThreadContents(NuThread* pDstThread, const NuThread* pSrcThread)
{ {
Assert(pDstThread != nil); Assert(pDstThread != NULL);
Assert(pSrcThread != nil); Assert(pSrcThread != NULL);
memcpy(pDstThread, pSrcThread, sizeof(*pDstThread)); memcpy(pDstThread, pSrcThread, sizeof(*pDstThread));
} }
@ -151,14 +154,14 @@ Nu_CopyThreadContents(NuThread* pDstThread, const NuThread* pSrcThread)
/* /*
* Read a single thread header from the archive. * Read a single thread header from the archive.
*/ */
static NuError static NuError Nu_ReadThreadHeader(NuArchive* pArchive, NuThread* pThread,
Nu_ReadThreadHeader(NuArchive* pArchive, NuThread* pThread, ushort* pCrc) uint16_t* pCrc)
{ {
FILE* fp; FILE* fp;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
fp = pArchive->archiveFp; fp = pArchive->archiveFp;
@ -184,17 +187,17 @@ Nu_ReadThreadHeader(NuArchive* pArchive, NuThread* pThread, ushort* pCrc)
* have used a linked list like NuLib, but that doesn't really provide any * have used a linked list like NuLib, but that doesn't really provide any
* benefit for us, and adds complexity. * benefit for us, and adds complexity.
*/ */
NuError NuError Nu_ReadThreadHeaders(NuArchive* pArchive, NuRecord* pRecord,
Nu_ReadThreadHeaders(NuArchive* pArchive, NuRecord* pRecord, ushort* pCrc) uint16_t* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuThread* pThread; NuThread* pThread;
long count; long count;
Boolean hasData = false; Boolean hasData = false;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pRecord != nil); Assert(pRecord != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
if (!pRecord->recTotalThreads) { if (!pRecord->recTotalThreads) {
/* not sure if this is reasonable, but we can handle it */ /* not sure if this is reasonable, but we can handle it */
@ -306,17 +309,16 @@ bail:
/* /*
* Write a single thread header to the archive. * Write a single thread header to the archive.
*/ */
static NuError static NuError Nu_WriteThreadHeader(NuArchive* pArchive,
Nu_WriteThreadHeader(NuArchive* pArchive, const NuThread* pThread, FILE* fp, const NuThread* pThread, FILE* fp, uint16_t* pCrc)
ushort* pCrc)
{ {
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(fp != nil); Assert(fp != NULL);
Assert(pCrc != nil); Assert(pCrc != NULL);
Nu_WriteTwoC(pArchive, fp, pThread->thThreadClass, pCrc); Nu_WriteTwoC(pArchive, fp, pThread->thThreadClass, pCrc);
Nu_WriteTwoC(pArchive, fp, (ushort)pThread->thThreadFormat, pCrc); Nu_WriteTwoC(pArchive, fp, (uint16_t)pThread->thThreadFormat, pCrc);
Nu_WriteTwoC(pArchive, fp, pThread->thThreadKind, pCrc); Nu_WriteTwoC(pArchive, fp, pThread->thThreadKind, pCrc);
Nu_WriteTwoC(pArchive, fp, pThread->thThreadCRC, pCrc); Nu_WriteTwoC(pArchive, fp, pThread->thThreadCRC, pCrc);
Nu_WriteFourC(pArchive, fp, pThread->thThreadEOF, pCrc); Nu_WriteFourC(pArchive, fp, pThread->thThreadEOF, pCrc);
@ -332,9 +334,8 @@ Nu_WriteThreadHeader(NuArchive* pArchive, const NuThread* pThread, FILE* fp,
* effect, we promote all threads to "real" status. We update the * effect, we promote all threads to "real" status. We update the
* "fake" count in pRecord accordingly. * "fake" count in pRecord accordingly.
*/ */
NuError NuError Nu_WriteThreadHeaders(NuArchive* pArchive, NuRecord* pRecord, FILE* fp,
Nu_WriteThreadHeaders(NuArchive* pArchive, NuRecord* pRecord, FILE* fp, uint16_t* pCrc)
ushort* pCrc)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuThread* pThread; NuThread* pThread;
@ -342,7 +343,7 @@ Nu_WriteThreadHeaders(NuArchive* pArchive, NuRecord* pRecord, FILE* fp,
for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) { for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) {
pThread = Nu_GetThread(pRecord, idx); pThread = Nu_GetThread(pRecord, idx);
Assert(pThread != nil); Assert(pThread != NULL);
err = Nu_WriteThreadHeader(pArchive, pThread, fp, pCrc); err = Nu_WriteThreadHeader(pArchive, pThread, fp, pCrc);
BailError(err); BailError(err);
@ -366,14 +367,13 @@ bail:
* Requires that the pArchive->currentOffset be set to the offset * Requires that the pArchive->currentOffset be set to the offset
* immediately after the last of the thread headers. * immediately after the last of the thread headers.
*/ */
NuError NuError Nu_ComputeThreadData(NuArchive* pArchive, NuRecord* pRecord)
Nu_ComputeThreadData(NuArchive* pArchive, NuRecord* pRecord)
{ {
NuThread* pThread; NuThread* pThread;
long fileOffset, count; long fileOffset, count;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pRecord != nil); Assert(pRecord != NULL);
/*pRecord->totalLength = 0;*/ /*pRecord->totalLength = 0;*/
pRecord->totalCompLength = 0; pRecord->totalCompLength = 0;
@ -407,15 +407,14 @@ Nu_ComputeThreadData(NuArchive* pArchive, NuRecord* pRecord)
* show to the application. (Someday I'll get AndyN for putting me * show to the application. (Someday I'll get AndyN for putting me
* through this...) * through this...)
*/ */
NuError NuError Nu_ScanThreads(NuArchive* pArchive, NuRecord* pRecord, long numThreads)
Nu_ScanThreads(NuArchive* pArchive, NuRecord* pRecord, long numThreads)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuThread* pThread; NuThread* pThread;
FILE* fp; FILE* fp;
Assert(pArchive != nil); Assert(pArchive != NULL);
Assert(pRecord != nil); Assert(pRecord != NULL);
fp = pArchive->archiveFp; fp = pArchive->archiveFp;
@ -423,23 +422,23 @@ Nu_ScanThreads(NuArchive* pArchive, NuRecord* pRecord, long numThreads)
pThread = pRecord->pThreads; pThread = pRecord->pThreads;
while (numThreads--) { while (numThreads--) {
if (pRecord->threadFilename == nil && if (pRecord->threadFilenameMOR == NULL &&
NuMakeThreadID(pThread->thThreadClass, pThread->thThreadKind) == NuMakeThreadID(pThread->thThreadClass, pThread->thThreadKind) ==
kNuThreadIDFilename) kNuThreadIDFilename)
{ {
/* it's the first filename thread, read the whole thing */ /* it's the first filename thread, read the whole thing */
if (pThread->thCompThreadEOF > kNuReasonableFilenameLen) { if (pThread->thCompThreadEOF > kNuReasonableFilenameLen) {
err = kNuErrBadRecord; err = kNuErrBadRecord;
Nu_ReportError(NU_BLOB, err, "Bad thread filename len (%lu)", Nu_ReportError(NU_BLOB, err, "Bad thread filename len (%u)",
pThread->thCompThreadEOF); pThread->thCompThreadEOF);
goto bail; goto bail;
} }
pRecord->threadFilename = Nu_Malloc(pArchive, pRecord->threadFilenameMOR = Nu_Malloc(pArchive,
pThread->thCompThreadEOF +1); pThread->thCompThreadEOF +1);
BailAlloc(pRecord->threadFilename); BailAlloc(pRecord->threadFilenameMOR);
/* note there is no CRC on a filename thread */ /* note there is no CRC on a filename thread */
(void) Nu_ReadBytes(pArchive, fp, pRecord->threadFilename, (void) Nu_ReadBytes(pArchive, fp, pRecord->threadFilenameMOR,
pThread->thCompThreadEOF); pThread->thCompThreadEOF);
if ((err = Nu_HeaderIOFailed(pArchive, fp)) != kNuErrNone) { if ((err = Nu_HeaderIOFailed(pArchive, fp)) != kNuErrNone) {
Nu_ReportError(NU_BLOB, err, "Failed reading filename thread"); Nu_ReportError(NU_BLOB, err, "Failed reading filename thread");
@ -447,15 +446,15 @@ Nu_ScanThreads(NuArchive* pArchive, NuRecord* pRecord, long numThreads)
} }
/* null-terminate on the actual len, not the buffer len */ /* null-terminate on the actual len, not the buffer len */
pRecord->threadFilename[pThread->thThreadEOF] = '\0'; pRecord->threadFilenameMOR[pThread->thThreadEOF] = '\0';
Nu_StripHiIfAllSet(pRecord->threadFilename); Nu_StripHiIfAllSet(pRecord->threadFilenameMOR);
/* prefer this one over the record one, but only one should exist */ /* prefer this one over the record one, but only one should exist */
if (pRecord->filename != nil) { if (pRecord->filenameMOR != NULL) {
DBUG(("--- HEY: got record filename and thread filename\n")); DBUG(("--- HEY: got record filename and thread filename\n"));
} }
pRecord->filename = pRecord->threadFilename; pRecord->filenameMOR = pRecord->threadFilenameMOR;
} else { } else {
/* not a filename (or not first filename), skip past it */ /* not a filename (or not first filename), skip past it */
@ -473,9 +472,9 @@ Nu_ScanThreads(NuArchive* pArchive, NuRecord* pRecord, long numThreads)
* end up with a disk image that had no name attached. This will tend * end up with a disk image that had no name attached. This will tend
* to confuse things, so we go ahead and give it a name. * to confuse things, so we go ahead and give it a name.
*/ */
if (pRecord->filename == nil) { if (pRecord->filenameMOR == NULL) {
DBUG(("+++ no filename found, using default record name\n")); DBUG(("+++ no filename found, using default record name\n"));
pRecord->filename = kNuDefaultRecordName; pRecord->filenameMOR = kNuDefaultRecordName;
} }
pArchive->currentOffset += pRecord->totalCompLength; pArchive->currentOffset += pRecord->totalCompLength;
@ -494,8 +493,7 @@ bail:
* assumes that the file pointer is set to the start of the thread's data * assumes that the file pointer is set to the start of the thread's data
* already. * already.
*/ */
NuError NuError Nu_SkipThread(NuArchive* pArchive, const NuRecord* pRecord,
Nu_SkipThread(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread) const NuThread* pThread)
{ {
NuError err; NuError err;
@ -522,12 +520,12 @@ Nu_SkipThread(NuArchive* pArchive, const NuRecord* pRecord,
* If the archive is a stream, the stream must be positioned at the * If the archive is a stream, the stream must be positioned at the
* start of pThread's data. If not, it will be seeked first. * start of pThread's data. If not, it will be seeked first.
*/ */
static NuError static NuError Nu_ExtractThreadToDataSink(NuArchive* pArchive,
Nu_ExtractThreadToDataSink(NuArchive* pArchive, const NuRecord* pRecord, const NuRecord* pRecord, const NuThread* pThread,
const NuThread* pThread, NuProgressData* pProgress, NuDataSink* pDataSink) NuProgressData* pProgress, NuDataSink* pDataSink)
{ {
NuError err; NuError err;
NuFunnel* pFunnel = nil; NuFunnel* pFunnel = NULL;
/* if it's not a stream, seek to the appropriate spot in the file */ /* if it's not a stream, seek to the appropriate spot in the file */
if (!Nu_IsStreaming(pArchive)) { if (!Nu_IsStreaming(pArchive)) {
@ -576,9 +574,8 @@ bail:
* filters for every thread, which means we can reject specific kinds * filters for every thread, which means we can reject specific kinds
* of forks and/or give them different names. This is a good thing. * of forks and/or give them different names. This is a good thing.
*/ */
static NuError static NuError Nu_ExtractThreadCommon(NuArchive* pArchive,
Nu_ExtractThreadCommon(NuArchive* pArchive, const NuRecord* pRecord, const NuRecord* pRecord, const NuThread* pThread, NuDataSink* pDataSink)
const NuThread* pThread, NuDataSink* pDataSink)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuSelectionProposal selProposal; NuSelectionProposal selProposal;
@ -586,18 +583,19 @@ Nu_ExtractThreadCommon(NuArchive* pArchive, const NuRecord* pRecord,
NuProgressData progressData; NuProgressData progressData;
NuProgressData* pProgressData; NuProgressData* pProgressData;
NuDataSink* pOrigDataSink; NuDataSink* pOrigDataSink;
char* newPathStorage = nil; UNICHAR* newPathStorageUNI = NULL;
const char* newPathname; UNICHAR* recFilenameStorageUNI = NULL;
const UNICHAR* newPathnameUNI;
NuResult result; NuResult result;
uchar newFssep; uint8_t newFssep;
Boolean doFreeSink = false; Boolean doFreeSink = false;
Assert(pRecord != nil); Assert(pRecord != NULL);
Assert(pThread != nil); Assert(pThread != NULL);
Assert(pDataSink != nil); Assert(pDataSink != NULL);
memset(&progressData, 0, sizeof(progressData)); memset(&progressData, 0, sizeof(progressData));
pProgressData = nil; pProgressData = NULL;
/* /*
* If we're just trying to verify the archive contents, create a * If we're just trying to verify the archive contents, create a
@ -619,7 +617,7 @@ Nu_ExtractThreadCommon(NuArchive* pArchive, const NuRecord* pRecord,
* use by the "bulk" extract, not the per-thread extract, but it * use by the "bulk" extract, not the per-thread extract, but it
* still applies if they so desire. * still applies if they so desire.
*/ */
if (pArchive->selectionFilterFunc != nil) { if (pArchive->selectionFilterFunc != NULL) {
selProposal.pRecord = pRecord; selProposal.pRecord = pRecord;
selProposal.pThread = pThread; selProposal.pThread = pThread;
result = (*pArchive->selectionFilterFunc)(pArchive, &selProposal); result = (*pArchive->selectionFilterFunc)(pArchive, &selProposal);
@ -632,9 +630,11 @@ Nu_ExtractThreadCommon(NuArchive* pArchive, const NuRecord* pRecord,
} }
} }
newPathname = nil; newPathnameUNI = NULL;
newFssep = 0; newFssep = 0;
recFilenameStorageUNI = Nu_CopyMORToUNI(pRecord->filenameMOR);
retry_name: retry_name:
if (Nu_DataSinkGetType(pDataSink) == kNuDataSinkToFile) { if (Nu_DataSinkGetType(pDataSink) == kNuDataSinkToFile) {
/* /*
@ -645,21 +645,21 @@ retry_name:
* Start by resetting everything to defaults, in case this isn't * Start by resetting everything to defaults, in case this isn't
* our first time through the "rename" loop. * our first time through the "rename" loop.
*/ */
newPathname = Nu_DataSinkFile_GetPathname(pDataSink); newPathnameUNI = Nu_DataSinkFile_GetPathname(pDataSink);
newFssep = Nu_DataSinkFile_GetFssep(pDataSink); newFssep = Nu_DataSinkFile_GetFssep(pDataSink);
pDataSink = pOrigDataSink; pDataSink = pOrigDataSink;
/* if they don't have a pathname func defined, we just use default */ /* if they don't have a pathname func defined, we just use default */
if (pArchive->outputPathnameFunc != nil) { if (pArchive->outputPathnameFunc != NULL) {
pathProposal.pathname = pRecord->filename; pathProposal.pathnameUNI = recFilenameStorageUNI;
pathProposal.filenameSeparator = pathProposal.filenameSeparator =
NuGetSepFromSysInfo(pRecord->recFileSysInfo); NuGetSepFromSysInfo(pRecord->recFileSysInfo);
pathProposal.pRecord = pRecord; pathProposal.pRecord = pRecord;
pathProposal.pThread = pThread; pathProposal.pThread = pThread;
pathProposal.newPathname = nil; pathProposal.newPathnameUNI = NULL;
pathProposal.newFilenameSeparator = '\0'; pathProposal.newFilenameSeparator = '\0';
/*pathProposal.newStorage = (NuThreadID)-1;*/ /*pathProposal.newStorage = (NuThreadID)-1;*/
pathProposal.newDataSink = nil; pathProposal.newDataSink = NULL;
result = (*pArchive->outputPathnameFunc)(pArchive, &pathProposal); result = (*pArchive->outputPathnameFunc)(pArchive, &pathProposal);
@ -671,35 +671,38 @@ retry_name:
} }
/* we don't own this string, so make a copy */ /* we don't own this string, so make a copy */
if (pathProposal.newPathname != nil) { if (pathProposal.newPathnameUNI != NULL) {
newPathStorage = strdup(pathProposal.newPathname); Nu_Free(pArchive, newPathStorageUNI);
newPathname = newPathStorage; newPathStorageUNI = strdup(pathProposal.newPathnameUNI);
} else newPathnameUNI = newPathStorageUNI;
newPathname = nil; } else {
newPathnameUNI = NULL;
}
if (pathProposal.newFilenameSeparator != '\0') if (pathProposal.newFilenameSeparator != '\0')
newFssep = pathProposal.newFilenameSeparator; newFssep = pathProposal.newFilenameSeparator;
/* if they want to send this somewhere else, let them */ /* if they want to send this somewhere else, let them */
if (pathProposal.newDataSink != nil) if (pathProposal.newDataSink != NULL)
pDataSink = pathProposal.newDataSink; pDataSink = pathProposal.newDataSink;
} }
/* at least one of these must be set */ /* at least one of these must be set */
Assert(!(newPathname == nil && pathProposal.newDataSink == nil)); Assert(!(newPathnameUNI == NULL && pathProposal.newDataSink == NULL));
} }
/* /*
* Prepare the progress data if this is a data thread. * Prepare the progress data if this is a data thread.
*/ */
if (newPathname == nil) { if (newPathnameUNI == NULL) {
/* using a data sink; get the pathname out of the record */ /* using a data sink; get the pathname out of the record */
newPathname = pRecord->filename; newPathnameUNI = recFilenameStorageUNI;
newFssep = NuGetSepFromSysInfo(pRecord->recFileSysInfo); newFssep = NuGetSepFromSysInfo(pRecord->recFileSysInfo);
} }
if (pThread->thThreadClass == kNuThreadClassData) { if (pThread->thThreadClass == kNuThreadClassData) {
pProgressData = &progressData; pProgressData = &progressData;
err = Nu_ProgressDataInit_Expand(pArchive, pProgressData, pRecord, err = Nu_ProgressDataInit_Expand(pArchive, pProgressData, pRecord,
newPathname, newFssep, Nu_DataSinkGetConvertEOL(pOrigDataSink)); newPathnameUNI, newFssep, recFilenameStorageUNI,
Nu_DataSinkGetConvertEOL(pOrigDataSink));
BailError(err); BailError(err);
/* send initial progress so they see the right name if "open" fails */ /* send initial progress so they see the right name if "open" fails */
@ -713,23 +716,23 @@ retry_name:
* We're extracting to a file. Open it, creating it if necessary and * We're extracting to a file. Open it, creating it if necessary and
* allowed. * allowed.
*/ */
FILE* fileFp = nil; FILE* fileFp = NULL;
err = Nu_OpenOutputFile(pArchive, pRecord, pThread, newPathname, err = Nu_OpenOutputFile(pArchive, pRecord, pThread, newPathnameUNI,
newFssep, &fileFp); newFssep, &fileFp);
if (err == kNuErrRename) { if (err == kNuErrRename) {
/* they want to rename; the OutputPathname callback handles this */ /* they want to rename; the OutputPathname callback handles this */
Nu_Free(pArchive, newPathStorage); Nu_Free(pArchive, newPathStorageUNI);
newPathStorage = nil; newPathStorageUNI = NULL;
/* reset these just to be careful */ /* reset these just to be careful */
newPathname = nil; newPathnameUNI = NULL;
fileFp = nil; fileFp = NULL;
goto retry_name; goto retry_name;
} else if (err != kNuErrNone) { } else if (err != kNuErrNone) {
goto bail; goto bail;
} }
Assert(fileFp != nil); Assert(fileFp != NULL);
(void) Nu_DataSinkFile_SetFP(pDataSink, fileFp); (void) Nu_DataSinkFile_SetFP(pDataSink, fileFp);
DBUG(("+++ EXTRACTING 0x%08lx from '%s' at offset %0ld to '%s'\n", DBUG(("+++ EXTRACTING 0x%08lx from '%s' at offset %0ld to '%s'\n",
@ -752,13 +755,13 @@ retry_name:
* permissions as appropriate. * permissions as appropriate.
*/ */
err = Nu_CloseOutputFile(pArchive, pRecord, err = Nu_CloseOutputFile(pArchive, pRecord,
Nu_DataSinkFile_GetFP(pDataSink), newPathname); Nu_DataSinkFile_GetFP(pDataSink), newPathnameUNI);
Nu_DataSinkFile_SetFP(pDataSink, nil); Nu_DataSinkFile_SetFP(pDataSink, NULL);
BailError(err); BailError(err);
} }
bail: bail:
if (err != kNuErrNone && pProgressData != nil) { if (err != kNuErrNone && pProgressData != NULL) {
/* send a final progress message, indicating failure */ /* send a final progress message, indicating failure */
if (err == kNuErrSkipped) if (err == kNuErrSkipped)
pProgressData->state = kNuProgressSkipped; pProgressData->state = kNuProgressSkipped;
@ -773,7 +776,8 @@ bail:
if (Nu_DataSinkGetType(pDataSink) == kNuDataSinkToFile) if (Nu_DataSinkGetType(pDataSink) == kNuDataSinkToFile)
Nu_DataSinkFile_Close(pDataSink); Nu_DataSinkFile_Close(pDataSink);
Nu_Free(pArchive, newPathStorage); Nu_Free(pArchive, newPathStorageUNI);
Nu_Free(pArchive, recFilenameStorageUNI);
if (doFreeSink) if (doFreeSink)
Nu_DataSinkFree(pDataSink); Nu_DataSinkFree(pDataSink);
@ -785,12 +789,12 @@ bail:
* *
* Streaming archives must be properly positioned. * Streaming archives must be properly positioned.
*/ */
NuError NuError Nu_ExtractThreadBulk(NuArchive* pArchive, const NuRecord* pRecord,
Nu_ExtractThreadBulk(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread) const NuThread* pThread)
{ {
NuError err; NuError err;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
UNICHAR* recFilenameStorageUNI = NULL;
NuValue eolConv; NuValue eolConv;
/* /*
@ -806,7 +810,8 @@ Nu_ExtractThreadBulk(NuArchive* pArchive, const NuRecord* pRecord,
eolConv = pArchive->valConvertExtractedEOL; eolConv = pArchive->valConvertExtractedEOL;
if (NuGetThreadID(pThread) == kNuThreadIDDiskImage) if (NuGetThreadID(pThread) == kNuThreadIDDiskImage)
eolConv = kNuConvertOff; eolConv = kNuConvertOff;
err = Nu_DataSinkFile_New(true, eolConv, pRecord->filename, recFilenameStorageUNI = Nu_CopyMORToUNI(pRecord->filenameMOR);
err = Nu_DataSinkFile_New(true, eolConv, recFilenameStorageUNI,
NuGetSepFromSysInfo(pRecord->recFileSysInfo), &pDataSink); NuGetSepFromSysInfo(pRecord->recFileSysInfo), &pDataSink);
BailError(err); BailError(err);
@ -814,11 +819,12 @@ Nu_ExtractThreadBulk(NuArchive* pArchive, const NuRecord* pRecord,
BailError(err); BailError(err);
bail: bail:
if (pDataSink != nil) { if (pDataSink != NULL) {
NuError err2 = Nu_DataSinkFree(pDataSink); NuError err2 = Nu_DataSinkFree(pDataSink);
if (err == kNuErrNone) if (err == kNuErrNone)
err = err2; err = err2;
} }
Nu_Free(pArchive, recFilenameStorageUNI);
return err; return err;
} }
@ -827,8 +833,7 @@ bail:
/* /*
* Extract a thread, given the IDs and a data sink. * Extract a thread, given the IDs and a data sink.
*/ */
NuError NuError Nu_ExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
Nu_ExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
NuDataSink* pDataSink) NuDataSink* pDataSink)
{ {
NuError err; NuError err;
@ -837,7 +842,7 @@ Nu_ExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
if (Nu_IsStreaming(pArchive)) if (Nu_IsStreaming(pArchive))
return kNuErrUsage; return kNuErrUsage;
if (threadIdx == 0 || pDataSink == nil) if (threadIdx == 0 || pDataSink == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
err = Nu_GetTOCIfNeeded(pArchive); err = Nu_GetTOCIfNeeded(pArchive);
BailError(err); BailError(err);
@ -846,7 +851,7 @@ Nu_ExtractThread(NuArchive* pArchive, NuThreadIdx threadIdx,
err = Nu_RecordSet_FindByThreadIdx(&pArchive->origRecordSet, threadIdx, err = Nu_RecordSet_FindByThreadIdx(&pArchive->origRecordSet, threadIdx,
&pRecord, &pThread); &pRecord, &pThread);
BailError(err); BailError(err);
Assert(pRecord != nil); Assert(pRecord != NULL);
/* extract away */ /* extract away */
err = Nu_ExtractThreadCommon(pArchive, pRecord, pThread, pDataSink); err = Nu_ExtractThreadCommon(pArchive, pRecord, pThread, pDataSink);
@ -872,9 +877,8 @@ bail:
* *
* If a matching threadID is found, this returns an error. * If a matching threadID is found, this returns an error.
*/ */
static NuError static NuError Nu_FindNoFutureThread(NuArchive* pArchive,
Nu_FindNoFutureThread(NuArchive* pArchive, const NuRecord* pRecord, const NuRecord* pRecord, NuThreadID threadID)
NuThreadID threadID)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
const NuThread* pThread; const NuThread* pThread;
@ -886,13 +890,13 @@ Nu_FindNoFutureThread(NuArchive* pArchive, const NuRecord* pRecord,
*/ */
for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) { for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) {
pThread = Nu_GetThread(pRecord, idx); pThread = Nu_GetThread(pRecord, idx);
Assert(pThread != nil); Assert(pThread != NULL);
if (NuGetThreadID(pThread) == threadID) { if (NuGetThreadID(pThread) == threadID) {
/* found a match, see if it has been deleted */ /* found a match, see if it has been deleted */
pThreadMod = Nu_ThreadMod_FindByThreadIdx(pRecord, pThreadMod = Nu_ThreadMod_FindByThreadIdx(pRecord,
pThread->threadIdx); pThread->threadIdx);
if (pThreadMod != nil && if (pThreadMod != NULL &&
pThreadMod->entry.kind == kNuThreadModDelete) pThreadMod->entry.kind == kNuThreadModDelete)
{ {
/* it's deleted, ignore it */ /* it's deleted, ignore it */
@ -908,7 +912,7 @@ Nu_FindNoFutureThread(NuArchive* pArchive, const NuRecord* pRecord,
* Now look for "add" threadMods with a matching threadID. * Now look for "add" threadMods with a matching threadID.
*/ */
pThreadMod = pRecord->pThreadMods; pThreadMod = pRecord->pThreadMods;
while (pThreadMod != nil) { while (pThreadMod != NULL) {
if (pThreadMod->entry.kind == kNuThreadModAdd && if (pThreadMod->entry.kind == kNuThreadModAdd &&
pThreadMod->entry.add.threadID == threadID) pThreadMod->entry.add.threadID == threadID)
{ {
@ -927,9 +931,8 @@ bail:
/* /*
* Like Nu_FindNoFutureThread, but tests against a whole class. * Like Nu_FindNoFutureThread, but tests against a whole class.
*/ */
static NuError static NuError Nu_FindNoFutureThreadClass(NuArchive* pArchive,
Nu_FindNoFutureThreadClass(NuArchive* pArchive, const NuRecord* pRecord, const NuRecord* pRecord, long threadClass)
long threadClass)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
const NuThread* pThread; const NuThread* pThread;
@ -941,13 +944,13 @@ Nu_FindNoFutureThreadClass(NuArchive* pArchive, const NuRecord* pRecord,
*/ */
for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) { for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) {
pThread = Nu_GetThread(pRecord, idx); pThread = Nu_GetThread(pRecord, idx);
Assert(pThread != nil); Assert(pThread != NULL);
if (pThread->thThreadClass == threadClass) { if (pThread->thThreadClass == threadClass) {
/* found a match, see if it has been deleted */ /* found a match, see if it has been deleted */
pThreadMod = Nu_ThreadMod_FindByThreadIdx(pRecord, pThreadMod = Nu_ThreadMod_FindByThreadIdx(pRecord,
pThread->threadIdx); pThread->threadIdx);
if (pThreadMod != nil && if (pThreadMod != NULL &&
pThreadMod->entry.kind == kNuThreadModDelete) pThreadMod->entry.kind == kNuThreadModDelete)
{ {
/* it's deleted, ignore it */ /* it's deleted, ignore it */
@ -963,7 +966,7 @@ Nu_FindNoFutureThreadClass(NuArchive* pArchive, const NuRecord* pRecord,
* Now look for "add" threadMods with a matching threadClass. * Now look for "add" threadMods with a matching threadClass.
*/ */
pThreadMod = pRecord->pThreadMods; pThreadMod = pRecord->pThreadMods;
while (pThreadMod != nil) { while (pThreadMod != NULL) {
if (pThreadMod->entry.kind == kNuThreadModAdd && if (pThreadMod->entry.kind == kNuThreadModAdd &&
NuThreadIDGetClass(pThreadMod->entry.add.threadID) == threadClass) NuThreadIDGetClass(pThreadMod->entry.add.threadID) == threadClass)
{ {
@ -988,9 +991,8 @@ bail:
* The record and thread returned will always be from the "copy" set. An * The record and thread returned will always be from the "copy" set. An
* error result is returned if the record and thread aren't found. * error result is returned if the record and thread aren't found.
*/ */
static NuError static NuError Nu_FindThreadForWriteByIdx(NuArchive* pArchive,
Nu_FindThreadForWriteByIdx(NuArchive* pArchive, NuThreadIdx threadIdx, NuThreadIdx threadIdx, NuRecord** ppFoundRecord, NuThread** ppFoundThread)
NuRecord** ppFoundRecord, NuThread** ppFoundThread)
{ {
NuError err; NuError err;
@ -1001,7 +1003,7 @@ Nu_FindThreadForWriteByIdx(NuArchive* pArchive, NuThreadIdx threadIdx,
Assert(Nu_RecordSet_GetLoaded(&pArchive->origRecordSet)); Assert(Nu_RecordSet_GetLoaded(&pArchive->origRecordSet));
err = Nu_RecordSet_FindByThreadIdx(&pArchive->origRecordSet, threadIdx, err = Nu_RecordSet_FindByThreadIdx(&pArchive->origRecordSet, threadIdx,
ppFoundRecord, ppFoundThread); ppFoundRecord, ppFoundThread);
*ppFoundThread = nil; /* can't delete from here, wipe ptr */ *ppFoundThread = NULL; /* can't delete from here, wipe ptr */
} }
BailError(err); BailError(err);
@ -1009,13 +1011,13 @@ Nu_FindThreadForWriteByIdx(NuArchive* pArchive, NuThreadIdx threadIdx,
* The thread exists. If we were looking in the "orig" set, we have * The thread exists. If we were looking in the "orig" set, we have
* to create a "copy" set, and delete it from that. * to create a "copy" set, and delete it from that.
*/ */
if (*ppFoundThread == nil) { if (*ppFoundThread == NULL) {
err = Nu_RecordSet_Clone(pArchive, &pArchive->copyRecordSet, err = Nu_RecordSet_Clone(pArchive, &pArchive->copyRecordSet,
&pArchive->origRecordSet); &pArchive->origRecordSet);
BailError(err); BailError(err);
err = Nu_RecordSet_FindByThreadIdx(&pArchive->copyRecordSet, threadIdx, err = Nu_RecordSet_FindByThreadIdx(&pArchive->copyRecordSet, threadIdx,
ppFoundRecord, ppFoundThread); ppFoundRecord, ppFoundThread);
Assert(err == kNuErrNone && *ppFoundThread != nil); /* must succeed */ Assert(err == kNuErrNone && *ppFoundThread != NULL); /* must succeed */
BailError(err); BailError(err);
} }
@ -1029,8 +1031,7 @@ bail:
* *
* Returns with an error (kNuErrThreadAdd) if it's not okay. * Returns with an error (kNuErrThreadAdd) if it's not okay.
*/ */
NuError NuError Nu_OkayToAddThread(NuArchive* pArchive, const NuRecord* pRecord,
Nu_OkayToAddThread(NuArchive* pArchive, const NuRecord* pRecord,
NuThreadID threadID) NuThreadID threadID)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
@ -1094,17 +1095,16 @@ bail:
* On success, the NuThreadIdx of the newly-created record will be placed * On success, the NuThreadIdx of the newly-created record will be placed
* in "*pThreadIdx", and "pDataSource" will be owned by NufxLib. * in "*pThreadIdx", and "pDataSource" will be owned by NufxLib.
*/ */
NuError NuError Nu_AddThread(NuArchive* pArchive, NuRecordIdx recIdx,
Nu_AddThread(NuArchive* pArchive, NuRecordIdx recIdx, NuThreadID threadID, NuThreadID threadID, NuDataSource* pDataSource, NuThreadIdx* pThreadIdx)
NuDataSource* pDataSource, NuThreadIdx* pThreadIdx)
{ {
NuError err; NuError err;
NuRecord* pRecord; NuRecord* pRecord;
NuThreadMod* pThreadMod = nil; NuThreadMod* pThreadMod = NULL;
NuThreadFormat threadFormat; NuThreadFormat threadFormat;
/* okay for pThreadIdx to be nil */ /* okay for pThreadIdx to be NULL */
if (recIdx == 0 || pDataSource == nil) if (recIdx == 0 || pDataSource == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
if (Nu_IsReadOnly(pArchive)) if (Nu_IsReadOnly(pArchive))
@ -1123,7 +1123,7 @@ Nu_AddThread(NuArchive* pArchive, NuRecordIdx recIdx, NuThreadID threadID,
err = Nu_RecordSet_FindByIdx(&pArchive->newRecordSet, recIdx, &pRecord); err = Nu_RecordSet_FindByIdx(&pArchive->newRecordSet, recIdx, &pRecord);
} }
BailError(err); BailError(err);
Assert(pRecord != nil); Assert(pRecord != NULL);
/* /*
* Do some tests, looking for specific types of threads that conflict * Do some tests, looking for specific types of threads that conflict
@ -1153,13 +1153,13 @@ Nu_AddThread(NuArchive* pArchive, NuRecordIdx recIdx, NuThreadID threadID,
err = Nu_ThreadModAdd_New(pArchive, threadID, threadFormat, pDataSource, err = Nu_ThreadModAdd_New(pArchive, threadID, threadFormat, pDataSource,
&pThreadMod); &pThreadMod);
BailError(err); BailError(err);
Assert(pThreadMod != nil); Assert(pThreadMod != NULL);
/* add the thread mod to the record */ /* add the thread mod to the record */
Nu_RecordAddThreadMod(pRecord, pThreadMod); Nu_RecordAddThreadMod(pRecord, pThreadMod);
if (pThreadIdx != nil) if (pThreadIdx != NULL)
*pThreadIdx = pThreadMod->entry.add.threadIdx; *pThreadIdx = pThreadMod->entry.add.threadIdx;
pThreadMod = nil; /* successful, don't free */ pThreadMod = NULL; /* successful, don't free */
/* /*
* If we've got a header filename and we're adding a filename thread, * If we've got a header filename and we're adding a filename thread,
@ -1172,9 +1172,9 @@ Nu_AddThread(NuArchive* pArchive, NuRecordIdx recIdx, NuThreadID threadID,
} }
bail: bail:
if (pThreadMod != nil) if (pThreadMod != NULL)
Nu_ThreadModFree(pArchive, pThreadMod); Nu_ThreadModFree(pArchive, pThreadMod);
if (err == kNuErrNone && pDataSource != nil) { if (err == kNuErrNone && pDataSource != NULL) {
/* on success, we have ownership of the data source. ThreadMod /* on success, we have ownership of the data source. ThreadMod
made its own copy, so get rid of this one */ made its own copy, so get rid of this one */
Nu_DataSourceFree(pDataSource); Nu_DataSourceFree(pDataSource);
@ -1194,16 +1194,15 @@ bail:
* You aren't allowed to update threads that have been deleted. Updating * You aren't allowed to update threads that have been deleted. Updating
* newly-added threads isn't possible, since they aren't really threads yet. * newly-added threads isn't possible, since they aren't really threads yet.
*/ */
NuError NuError Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx,
Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx, NuDataSource* pDataSource, int32_t* pMaxLen)
NuDataSource* pDataSource, long* pMaxLen)
{ {
NuError err; NuError err;
NuThreadMod* pThreadMod = nil; NuThreadMod* pThreadMod = NULL;
NuRecord* pFoundRecord; NuRecord* pFoundRecord;
NuThread* pFoundThread; NuThread* pFoundThread;
if (pDataSource == nil) { if (pDataSource == NULL) {
err = kNuErrInvalidArg; err = kNuErrInvalidArg;
goto bail; goto bail;
} }
@ -1239,14 +1238,14 @@ Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx,
goto bail; goto bail;
} }
if (pMaxLen != nil) if (pMaxLen != NULL)
*pMaxLen = pFoundThread->thCompThreadEOF; *pMaxLen = pFoundThread->thCompThreadEOF;
/* /*
* Check to see if somebody is trying to delete this, or has already * Check to see if somebody is trying to delete this, or has already
* updated it. * updated it.
*/ */
if (Nu_ThreadMod_FindByThreadIdx(pFoundRecord, threadIdx) != nil) { if (Nu_ThreadMod_FindByThreadIdx(pFoundRecord, threadIdx) != NULL) {
DBUG(("--- Tried to modify a deleted or modified thread\n")); DBUG(("--- Tried to modify a deleted or modified thread\n"));
err = kNuErrModThreadChange; err = kNuErrModThreadChange;
goto bail; goto bail;
@ -1269,7 +1268,7 @@ Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx,
Nu_DataSourceGetOtherLen(pDataSource)) Nu_DataSourceGetOtherLen(pDataSource))
{ {
err = kNuErrPreSizeOverflow; err = kNuErrPreSizeOverflow;
Nu_ReportError(NU_BLOB, err, "can't put %ld bytes into %ld", Nu_ReportError(NU_BLOB, err, "can't put %u bytes into %u",
Nu_DataSourceGetOtherLen(pDataSource), Nu_DataSourceGetOtherLen(pDataSource),
pFoundThread->thCompThreadEOF); pFoundThread->thCompThreadEOF);
goto bail; goto bail;
@ -1281,7 +1280,7 @@ Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx,
Nu_DataSourceGetOtherLen(pDataSource) > kNuReasonableFilenameLen)) Nu_DataSourceGetOtherLen(pDataSource) > kNuReasonableFilenameLen))
{ {
err = kNuErrInvalidFilename; err = kNuErrInvalidFilename;
Nu_ReportError(NU_BLOB, err, "invalid filename (%ld bytes)", Nu_ReportError(NU_BLOB, err, "invalid filename (%u bytes)",
Nu_DataSourceGetOtherLen(pDataSource)); Nu_DataSourceGetOtherLen(pDataSource));
goto bail; goto bail;
} }
@ -1294,7 +1293,7 @@ Nu_UpdatePresizedThread(NuArchive* pArchive, NuThreadIdx threadIdx,
Assert(pFoundThread->thThreadFormat == kNuThreadFormatUncompressed); Assert(pFoundThread->thThreadFormat == kNuThreadFormatUncompressed);
err = Nu_ThreadModUpdate_New(pArchive, threadIdx, pDataSource, &pThreadMod); err = Nu_ThreadModUpdate_New(pArchive, threadIdx, pDataSource, &pThreadMod);
BailError(err); BailError(err);
Assert(pThreadMod != nil); Assert(pThreadMod != NULL);
/* add the thread mod to the record */ /* add the thread mod to the record */
Nu_RecordAddThreadMod(pFoundRecord, pThreadMod); Nu_RecordAddThreadMod(pFoundRecord, pThreadMod);
@ -1322,11 +1321,10 @@ bail:
* later on. Besides, it's sort of handy to hang on to the filename for * later on. Besides, it's sort of handy to hang on to the filename for
* as long as possible. * as long as possible.
*/ */
NuError NuError Nu_DeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx)
Nu_DeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx)
{ {
NuError err; NuError err;
NuThreadMod* pThreadMod = nil; NuThreadMod* pThreadMod = NULL;
NuRecord* pFoundRecord; NuRecord* pFoundRecord;
NuThread* pFoundThread; NuThread* pFoundThread;
@ -1348,7 +1346,7 @@ Nu_DeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx)
* allowed. Deletion of threads from deleted records can't happen, * allowed. Deletion of threads from deleted records can't happen,
* because deleted records are completely removed from the "copy" set. * because deleted records are completely removed from the "copy" set.
*/ */
if (Nu_ThreadMod_FindByThreadIdx(pFoundRecord, threadIdx) != nil) { if (Nu_ThreadMod_FindByThreadIdx(pFoundRecord, threadIdx) != NULL) {
DBUG(("--- Tried to delete a deleted or modified thread\n")); DBUG(("--- Tried to delete a deleted or modified thread\n"));
err = kNuErrModThreadChange; err = kNuErrModThreadChange;
goto bail; goto bail;
@ -1361,7 +1359,7 @@ Nu_DeleteThread(NuArchive* pArchive, NuThreadIdx threadIdx)
NuGetThreadID(pFoundThread), &pThreadMod); NuGetThreadID(pFoundThread), &pThreadMod);
BailError(err); BailError(err);
Nu_RecordAddThreadMod(pFoundRecord, pThreadMod); Nu_RecordAddThreadMod(pFoundRecord, pThreadMod);
pThreadMod = nil; /* successful, don't free */ pThreadMod = NULL; /* successful, don't free */
bail: bail:
Nu_ThreadModFree(pArchive, pThreadMod); Nu_ThreadModFree(pArchive, pThreadMod);

View File

@ -14,12 +14,11 @@
/* /*
* Get a configurable parameter. * Get a configurable parameter.
*/ */
NuError NuError Nu_GetValue(NuArchive* pArchive, NuValueID ident, NuValue* pValue)
Nu_GetValue(NuArchive* pArchive, NuValueID ident, NuValue* pValue)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
if (pValue == nil) if (pValue == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
switch (ident) { switch (ident) {
@ -82,8 +81,7 @@ bail:
/* /*
* Set a configurable parameter. * Set a configurable parameter.
*/ */
NuError NuError Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
{ {
NuError err = kNuErrInvalidArg; NuError err = kNuErrInvalidArg;
@ -91,7 +89,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueAllowDuplicates: case kNuValueAllowDuplicates:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueAllowDuplicates value %ld", value); "Invalid kNuValueAllowDuplicates value %u", value);
goto bail; goto bail;
} }
pArchive->valAllowDuplicates = value; pArchive->valAllowDuplicates = value;
@ -99,7 +97,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueConvertExtractedEOL: case kNuValueConvertExtractedEOL:
if (value < kNuConvertOff || value > kNuConvertAuto) { if (value < kNuConvertOff || value > kNuConvertAuto) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueConvertExtractedEOL value %ld", value); "Invalid kNuValueConvertExtractedEOL value %u", value);
goto bail; goto bail;
} }
pArchive->valConvertExtractedEOL = value; pArchive->valConvertExtractedEOL = value;
@ -107,7 +105,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueDataCompression: case kNuValueDataCompression:
if (value < kNuCompressNone || value > kNuCompressBzip2) { if (value < kNuCompressNone || value > kNuCompressBzip2) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueDataCompression value %ld", value); "Invalid kNuValueDataCompression value %u", value);
goto bail; goto bail;
} }
pArchive->valDataCompression = value; pArchive->valDataCompression = value;
@ -115,7 +113,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueDiscardWrapper: case kNuValueDiscardWrapper:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueDiscardWrapper value %ld", value); "Invalid kNuValueDiscardWrapper value %u", value);
goto bail; goto bail;
} }
pArchive->valDiscardWrapper = value; pArchive->valDiscardWrapper = value;
@ -123,7 +121,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueEOL: case kNuValueEOL:
if (value < kNuEOLUnknown || value > kNuEOLCRLF) { if (value < kNuEOLUnknown || value > kNuEOLCRLF) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueEOL value %ld", value); "Invalid kNuValueEOL value %u", value);
goto bail; goto bail;
} }
pArchive->valEOL = value; pArchive->valEOL = value;
@ -131,7 +129,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueHandleExisting: case kNuValueHandleExisting:
if (value < kNuMaybeOverwrite || value > kNuMustOverwrite) { if (value < kNuMaybeOverwrite || value > kNuMustOverwrite) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueHandleExisting value %ld", value); "Invalid kNuValueHandleExisting value %u", value);
goto bail; goto bail;
} }
pArchive->valHandleExisting = value; pArchive->valHandleExisting = value;
@ -139,7 +137,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueIgnoreCRC: case kNuValueIgnoreCRC:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueIgnoreCRC value %ld", value); "Invalid kNuValueIgnoreCRC value %u", value);
goto bail; goto bail;
} }
pArchive->valIgnoreCRC = value; pArchive->valIgnoreCRC = value;
@ -147,7 +145,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueMaskDataless: case kNuValueMaskDataless:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueMaskDataless value %ld", value); "Invalid kNuValueMaskDataless value %u", value);
goto bail; goto bail;
} }
pArchive->valMaskDataless = value; pArchive->valMaskDataless = value;
@ -155,7 +153,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueMimicSHK: case kNuValueMimicSHK:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueMimicSHK value %ld", value); "Invalid kNuValueMimicSHK value %u", value);
goto bail; goto bail;
} }
pArchive->valMimicSHK = value; pArchive->valMimicSHK = value;
@ -163,7 +161,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueModifyOrig: case kNuValueModifyOrig:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueModifyOrig value %ld", value); "Invalid kNuValueModifyOrig value %u", value);
goto bail; goto bail;
} }
pArchive->valModifyOrig = value; pArchive->valModifyOrig = value;
@ -171,7 +169,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueOnlyUpdateOlder: case kNuValueOnlyUpdateOlder:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueOnlyUpdateOlder value %ld", value); "Invalid kNuValueOnlyUpdateOlder value %u", value);
goto bail; goto bail;
} }
pArchive->valOnlyUpdateOlder = value; pArchive->valOnlyUpdateOlder = value;
@ -179,7 +177,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueStripHighASCII: case kNuValueStripHighASCII:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueStripHighASCII value %ld", value); "Invalid kNuValueStripHighASCII value %u", value);
goto bail; goto bail;
} }
pArchive->valStripHighASCII = value; pArchive->valStripHighASCII = value;
@ -187,7 +185,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueJunkSkipMax: case kNuValueJunkSkipMax:
if (value > kMaxJunkSkipMax) { if (value > kMaxJunkSkipMax) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueJunkSkipMax value %ld", value); "Invalid kNuValueJunkSkipMax value %u", value);
goto bail; goto bail;
} }
pArchive->valJunkSkipMax = value; pArchive->valJunkSkipMax = value;
@ -195,7 +193,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueIgnoreLZW2Len: case kNuValueIgnoreLZW2Len:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueIgnoreLZW2Len value %ld", value); "Invalid kNuValueIgnoreLZW2Len value %u", value);
goto bail; goto bail;
} }
pArchive->valIgnoreLZW2Len = value; pArchive->valIgnoreLZW2Len = value;
@ -203,7 +201,7 @@ Nu_SetValue(NuArchive* pArchive, NuValueID ident, NuValue value)
case kNuValueHandleBadMac: case kNuValueHandleBadMac:
if (value != true && value != false) { if (value != true && value != false) {
Nu_ReportError(NU_BLOB, err, Nu_ReportError(NU_BLOB, err,
"Invalid kNuValueHandleBadMac value %ld", value); "Invalid kNuValueHandleBadMac value %u", value);
goto bail; goto bail;
} }
pArchive->valHandleBadMac = value; pArchive->valHandleBadMac = value;
@ -225,11 +223,10 @@ bail:
* pry into pArchive to get at (like the archive type) or get the master * pry into pArchive to get at (like the archive type) or get the master
* header (like the number of records). * header (like the number of records).
*/ */
NuError NuError Nu_GetAttr(NuArchive* pArchive, NuAttrID ident, NuAttr* pAttr)
Nu_GetAttr(NuArchive* pArchive, NuAttrID ident, NuAttr* pAttr)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
if (pAttr == nil) if (pAttr == NULL)
return kNuErrInvalidArg; return kNuErrInvalidArg;
switch (ident) { switch (ident) {
@ -260,8 +257,8 @@ bail:
* *
* Unsupported compression types cause a warning to be flagged. * Unsupported compression types cause a warning to be flagged.
*/ */
NuThreadFormat NuThreadFormat Nu_ConvertCompressValToFormat(NuArchive* pArchive,
Nu_ConvertCompressValToFormat(NuArchive* pArchive, NuValue compValue) NuValue compValue)
{ {
NuThreadFormat threadFormat; NuThreadFormat threadFormat;
Boolean unsup = false; Boolean unsup = false;
@ -312,14 +309,14 @@ Nu_ConvertCompressValToFormat(NuArchive* pArchive, NuValue compValue)
default: default:
Nu_ReportError(NU_BLOB, kNuErrInvalidArg, Nu_ReportError(NU_BLOB, kNuErrInvalidArg,
"Unknown compress value %ld", compValue); "Unknown compress value %u", compValue);
Assert(false); Assert(false);
return kNuThreadFormatUncompressed; return kNuThreadFormatUncompressed;
} }
if (unsup) { if (unsup) {
Nu_ReportError(NU_BLOB, kNuErrNone, Nu_ReportError(NU_BLOB, kNuErrNone,
"Unsupported compression 0x%04x requested (%ld), storing", "Unsupported compression 0x%04x requested (%u), storing",
threadFormat, compValue); threadFormat, compValue);
return kNuThreadFormatUncompressed; return kNuThreadFormatUncompressed;
} }

View File

@ -23,19 +23,18 @@ static const char gNuBuildFlags[] = "-";
/* /*
* Return the version number, date built, and build flags. * Return the version number, date built, and build flags.
*/ */
NuError NuError Nu_GetVersion(int32_t* pMajorVersion, int32_t* pMinorVersion,
Nu_GetVersion(long* pMajorVersion, long* pMinorVersion, long* pBugVersion, int32_t* pBugVersion, const char** ppBuildDate, const char** ppBuildFlags)
const char** ppBuildDate, const char** ppBuildFlags)
{ {
if (pMajorVersion != nil) if (pMajorVersion != NULL)
*pMajorVersion = kNuVersionMajor; *pMajorVersion = kNuVersionMajor;
if (pMinorVersion != nil) if (pMinorVersion != NULL)
*pMinorVersion = kNuVersionMinor; *pMinorVersion = kNuVersionMinor;
if (pBugVersion != nil) if (pBugVersion != NULL)
*pBugVersion = kNuVersionBug; *pBugVersion = kNuVersionBug;
if (ppBuildDate != nil) if (ppBuildDate != NULL)
*ppBuildDate = gNuBuildDate; *ppBuildDate = gNuBuildDate;
if (ppBuildFlags != nil) if (ppBuildFlags != NULL)
*ppBuildFlags = gNuBuildFlags; *ppBuildFlags = gNuBuildFlags;
return kNuErrNone; return kNuErrNone;
} }

View File

@ -27,18 +27,6 @@
/* Define if your <sys/time.h> declares struct tm. */ /* Define if your <sys/time.h> declares struct tm. */
#undef TM_IN_SYS_TIME #undef TM_IN_SYS_TIME
/* Define to `unsigned char' if <sys/types.h> doesn't define. */
#undef uchar
/* Define to `unsigned short' if <sys/types.h> doesn't define. */
#undef ushort
/* Define to `unsigned int' if <sys/types.h> doesn't define. */
#undef uint
/* Define to `unsigned long' if <sys/types.h> doesn't define. */
#undef ulong
/* Define to `int' if <sys/types.h> doesn't define. */ /* Define to `int' if <sys/types.h> doesn't define. */
#undef mode_t #undef mode_t

49
nufxlib/configure vendored
View File

@ -3879,50 +3879,6 @@ $as_echo "#define TM_IN_SYS_TIME 1" >>confdefs.h
fi fi
ac_fn_c_check_type "$LINENO" "uchar" "ac_cv_type_uchar" "$ac_includes_default"
if test "x$ac_cv_type_uchar" = xyes; then :
else
cat >>confdefs.h <<_ACEOF
#define uchar unsigned char
_ACEOF
fi
ac_fn_c_check_type "$LINENO" "ushort" "ac_cv_type_ushort" "$ac_includes_default"
if test "x$ac_cv_type_ushort" = xyes; then :
else
cat >>confdefs.h <<_ACEOF
#define ushort unsigned short
_ACEOF
fi
ac_fn_c_check_type "$LINENO" "uint" "ac_cv_type_uint" "$ac_includes_default"
if test "x$ac_cv_type_uint" = xyes; then :
else
cat >>confdefs.h <<_ACEOF
#define uint unsigned int
_ACEOF
fi
ac_fn_c_check_type "$LINENO" "ulong" "ac_cv_type_ulong" "$ac_includes_default"
if test "x$ac_cv_type_ulong" = xyes; then :
else
cat >>confdefs.h <<_ACEOF
#define ulong unsigned long
_ACEOF
fi
for ac_func in fdopen ftruncate memmove mkdir mkstemp mktime timelocal \ for ac_func in fdopen ftruncate memmove mkdir mkstemp mktime timelocal \
localtime_r snprintf strcasecmp strncasecmp strtoul strerror vsnprintf localtime_r snprintf strcasecmp strncasecmp strtoul strerror vsnprintf
@ -4014,11 +3970,6 @@ elif test "$host_os" = "beos"; then
SHARE_FLAGS='-nostartfiles -Xlinker -soname="$@"' SHARE_FLAGS='-nostartfiles -Xlinker -soname="$@"'
fi fi
if test "$host_vendor" = "apple" -a ${host_os:0:6} = "darwin"; then
echo "checking for Mac OS X... yes, adding -framework Carbon"
LIBS="$LIBS -framework Carbon"
fi

View File

@ -29,10 +29,6 @@ AC_TYPE_MODE_T
AC_TYPE_OFF_T AC_TYPE_OFF_T
AC_TYPE_SIZE_T AC_TYPE_SIZE_T
AC_STRUCT_TM AC_STRUCT_TM
AC_CHECK_TYPE(uchar, unsigned char)
AC_CHECK_TYPE(ushort, unsigned short)
AC_CHECK_TYPE(uint, unsigned int)
AC_CHECK_TYPE(ulong, unsigned long)
dnl Checks for library functions. dnl Checks for library functions.
AC_CHECK_FUNCS(fdopen ftruncate memmove mkdir mkstemp mktime timelocal \ AC_CHECK_FUNCS(fdopen ftruncate memmove mkdir mkstemp mktime timelocal \
@ -94,12 +90,6 @@ elif test "$host_os" = "beos"; then
SHARE_FLAGS='-nostartfiles -Xlinker -soname="$@"' SHARE_FLAGS='-nostartfiles -Xlinker -soname="$@"'
fi fi
dnl Mac OS X (powerpc-apple-darwin6.6) needs an extra flag.
if test "$host_vendor" = "apple" -a ${host_os:0:6} = "darwin"; then
echo "checking for Mac OS X... yes, adding -framework Carbon"
LIBS="$LIBS -framework Carbon"
fi
AC_SUBST(BUILD_FLAGS) AC_SUBST(BUILD_FLAGS)
AC_SUBST(SHARE_FLAGS) AC_SUBST(SHARE_FLAGS)

View File

@ -16,6 +16,8 @@ EXPORTS
NuAddThread NuAddThread
NuClose NuClose
NuContents NuContents
NuConvertMORToUNI
NuConvertUNIToMOR
NuCreateDataSinkForBuffer NuCreateDataSinkForBuffer
NuCreateDataSinkForFP NuCreateDataSinkForFP
NuCreateDataSinkForFile NuCreateDataSinkForFile

View File

@ -85,6 +85,7 @@
<ClCompile Include="Archive.c" /> <ClCompile Include="Archive.c" />
<ClCompile Include="ArchiveIO.c" /> <ClCompile Include="ArchiveIO.c" />
<ClCompile Include="Bzip2.c" /> <ClCompile Include="Bzip2.c" />
<ClCompile Include="Charset.c" />
<ClCompile Include="Compress.c" /> <ClCompile Include="Compress.c" />
<ClCompile Include="Crc16.c" /> <ClCompile Include="Crc16.c" />
<ClCompile Include="Debug.c" /> <ClCompile Include="Debug.c" />

View File

@ -95,5 +95,8 @@
<ClCompile Include="Version.c"> <ClCompile Include="Version.c">
<Filter>Source Files</Filter> <Filter>Source Files</Filter>
</ClCompile> </ClCompile>
<ClCompile Include="Charset.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup> </ItemGroup>
</Project> </Project>

View File

@ -6,8 +6,8 @@
* *
* Common functions for NuLib tests. * Common functions for NuLib tests.
*/ */
#ifndef __Common__ #ifndef NUFXLIB_SAMPLES_COMMON_H
#define __Common__ #define NUFXLIB_SAMPLES_COMMON_H
#include "SysDefs.h" /* might as well draft off the autoconf */ #include "SysDefs.h" /* might as well draft off the autoconf */
#include "NufxLib.h" #include "NufxLib.h"
@ -16,8 +16,6 @@
# include "dmalloc.h" # include "dmalloc.h"
#endif #endif
#define nil NULL /* this is seriously habit-forming */
#define NELEM(x) (sizeof(x) / sizeof((x)[0])) #define NELEM(x) (sizeof(x) / sizeof((x)[0]))
#ifndef __cplusplus #ifndef __cplusplus
@ -65,4 +63,4 @@
# define PATH_SEP '/' # define PATH_SEP '/'
#endif #endif
#endif /*__Common__*/ #endif /*NUFXLIB_SAMPLES_COMMON_H*/

File diff suppressed because it is too large Load Diff

View File

@ -51,35 +51,33 @@ strcasecmp(const char *str1, const char *str2)
typedef struct ImgHeader { typedef struct ImgHeader {
char magic[4]; char magic[4];
char creator[4]; char creator[4];
short headerLen; uint16_t headerLen;
short version; uint16_t version;
long imageFormat; uint32_t imageFormat;
unsigned long flags; uint32_t flags;
long numBlocks; uint32_t numBlocks;
long dataOffset; uint32_t dataOffset;
long dataLen; uint32_t dataLen;
long cmntOffset; uint32_t cmntOffset;
long cmntLen; uint32_t cmntLen;
long creatorOffset; uint32_t creatorOffset;
long creatorLen; uint32_t creatorLen;
long spare[4]; uint32_t spare[4];
} ImgHeader; } ImgHeader;
/* /*
* Read a two-byte little-endian value. * Read a two-byte little-endian value.
*/ */
void void ReadShortLE(FILE* fp, uint16_t* pBuf)
ReadShortLE(FILE* fp, short* pBuf)
{ {
*pBuf = getc(fp); *pBuf = getc(fp);
*pBuf += (short) getc(fp) << 8; *pBuf += (uint16_t) getc(fp) << 8;
} }
/* /*
* Write a two-byte little-endian value. * Write a two-byte little-endian value.
*/ */
void void WriteShortLE(FILE* fp, uint16_t val)
WriteShortLE(FILE* fp, unsigned short val)
{ {
putc(val, fp); putc(val, fp);
putc(val >> 8, fp); putc(val >> 8, fp);
@ -88,20 +86,18 @@ WriteShortLE(FILE* fp, unsigned short val)
/* /*
* Read a four-byte little-endian value. * Read a four-byte little-endian value.
*/ */
void void ReadLongLE(FILE* fp, uint32_t* pBuf)
ReadLongLE(FILE* fp, long* pBuf)
{ {
*pBuf = getc(fp); *pBuf = getc(fp);
*pBuf += (long) getc(fp) << 8; *pBuf += (uint32_t) getc(fp) << 8;
*pBuf += (long) getc(fp) << 16; *pBuf += (uint32_t) getc(fp) << 16;
*pBuf += (long) getc(fp) << 24; *pBuf += (uint32_t) getc(fp) << 24;
} }
/* /*
* Write a four-byte little-endian value. * Write a four-byte little-endian value.
*/ */
void void WriteLongLE(FILE* fp, uint32_t val)
WriteLongLE(FILE* fp, unsigned long val)
{ {
putc(val, fp); putc(val, fp);
putc(val >> 8, fp); putc(val >> 8, fp);
@ -112,8 +108,7 @@ WriteLongLE(FILE* fp, unsigned long val)
/* /*
* Read the header from a 2IMG file. * Read the header from a 2IMG file.
*/ */
int int ReadImgHeader(FILE* fp, ImgHeader* pHeader)
ReadImgHeader(FILE* fp, ImgHeader* pHeader)
{ {
size_t ignored; size_t ignored;
ignored = fread(pHeader->magic, 4, 1, fp); ignored = fread(pHeader->magic, 4, 1, fp);
@ -121,7 +116,7 @@ ReadImgHeader(FILE* fp, ImgHeader* pHeader)
ReadShortLE(fp, &pHeader->headerLen); ReadShortLE(fp, &pHeader->headerLen);
ReadShortLE(fp, &pHeader->version); ReadShortLE(fp, &pHeader->version);
ReadLongLE(fp, &pHeader->imageFormat); ReadLongLE(fp, &pHeader->imageFormat);
ReadLongLE(fp, (long*)&pHeader->flags); ReadLongLE(fp, &pHeader->flags);
ReadLongLE(fp, &pHeader->numBlocks); ReadLongLE(fp, &pHeader->numBlocks);
ReadLongLE(fp, &pHeader->dataOffset); ReadLongLE(fp, &pHeader->dataOffset);
ReadLongLE(fp, &pHeader->dataLen); ReadLongLE(fp, &pHeader->dataLen);
@ -154,8 +149,7 @@ ReadImgHeader(FILE* fp, ImgHeader* pHeader)
/* /*
* Write the header to a 2IMG file. * Write the header to a 2IMG file.
*/ */
int int WriteImgHeader(FILE* fp, ImgHeader* pHeader)
WriteImgHeader(FILE* fp, ImgHeader* pHeader)
{ {
fwrite(pHeader->magic, 4, 1, fp); fwrite(pHeader->magic, 4, 1, fp);
fwrite(pHeader->creator, 4, 1, fp); fwrite(pHeader->creator, 4, 1, fp);
@ -185,23 +179,22 @@ WriteImgHeader(FILE* fp, ImgHeader* pHeader)
/* /*
* Dump the contents of an ImgHeader. * Dump the contents of an ImgHeader.
*/ */
void void DumpImgHeader(ImgHeader* pHeader)
DumpImgHeader(ImgHeader* pHeader)
{ {
printf("--- header contents:\n"); printf("--- header contents:\n");
printf("\tmagic = '%.4s'\n", pHeader->magic); printf("\tmagic = '%.4s'\n", pHeader->magic);
printf("\tcreator = '%.4s'\n", pHeader->creator); printf("\tcreator = '%.4s'\n", pHeader->creator);
printf("\theaderLen = %d\n", pHeader->headerLen); printf("\theaderLen = %d\n", pHeader->headerLen);
printf("\tversion = %d\n", pHeader->version); printf("\tversion = %d\n", pHeader->version);
printf("\timageFormat = %ld\n", pHeader->imageFormat); printf("\timageFormat = %u\n", pHeader->imageFormat);
printf("\tflags = 0x%08lx\n", pHeader->flags); printf("\tflags = 0x%08x\n", pHeader->flags);
printf("\tnumBlocks = %ld\n", pHeader->numBlocks); printf("\tnumBlocks = %u\n", pHeader->numBlocks);
printf("\tdataOffset = %ld\n", pHeader->dataOffset); printf("\tdataOffset = %u\n", pHeader->dataOffset);
printf("\tdataLen = %ld\n", pHeader->dataLen); printf("\tdataLen = %u\n", pHeader->dataLen);
printf("\tcmntOffset = %ld\n", pHeader->cmntOffset); printf("\tcmntOffset = %u\n", pHeader->cmntOffset);
printf("\tcmntLen = %ld\n", pHeader->cmntLen); printf("\tcmntLen = %u\n", pHeader->cmntLen);
printf("\tcreatorOffset = %ld\n", pHeader->creatorOffset); printf("\tcreatorOffset = %u\n", pHeader->creatorOffset);
printf("\tcreatorLen = %ld\n", pHeader->creatorLen); printf("\tcreatorLen = %u\n", pHeader->creatorLen);
printf("\n"); printf("\n");
} }
@ -217,8 +210,7 @@ typedef enum ArchiveKind { kKindUnknown, kKindShk, kKindImg } ArchiveKind;
/* /*
* This gets called when a buffer DataSource is no longer needed. * This gets called when a buffer DataSource is no longer needed.
*/ */
NuResult NuResult FreeCallback(NuArchive* pArchive, void* args)
FreeCallback(NuArchive* pArchive, void* args)
{ {
free(args); free(args);
return kNuOK; return kNuOK;
@ -227,8 +219,7 @@ FreeCallback(NuArchive* pArchive, void* args)
/* /*
* This gets called when an "FP" DataSource is no longer needed. * This gets called when an "FP" DataSource is no longer needed.
*/ */
NuResult NuResult FcloseCallback(NuArchive* pArchive, void* args)
FcloseCallback(NuArchive* pArchive, void* args)
{ {
fclose((FILE*) args); fclose((FILE*) args);
return kNuOK; return kNuOK;
@ -242,8 +233,7 @@ FcloseCallback(NuArchive* pArchive, void* args)
* of NufxLib. We could just as easily not set it and call fclose() * of NufxLib. We could just as easily not set it and call fclose()
* ourselves, because the structure of this program is pretty simple. * ourselves, because the structure of this program is pretty simple.
*/ */
NuError NuError CreateProdosSource(const ImgHeader* pHeader, FILE* fp,
CreateProdosSource(const ImgHeader* pHeader, FILE* fp,
NuDataSource** ppDataSource) NuDataSource** ppDataSource)
{ {
return NuCreateDataSourceForFP(kNuThreadFormatUncompressed, 0, fp, return NuCreateDataSourceForFP(kNuThreadFormatUncompressed, 0, fp,
@ -254,17 +244,16 @@ CreateProdosSource(const ImgHeader* pHeader, FILE* fp,
* Create a data source for a DOS-ordered image. This is a little harder, * Create a data source for a DOS-ordered image. This is a little harder,
* since we have to reorder the blocks into ProDOS ordering for ShrinkIt. * since we have to reorder the blocks into ProDOS ordering for ShrinkIt.
*/ */
NuError NuError CreateDosSource(const ImgHeader* pHeader, FILE* fp,
CreateDosSource(const ImgHeader* pHeader, FILE* fp,
NuDataSource** ppDataSource) NuDataSource** ppDataSource)
{ {
NuError err; NuError err;
char* diskBuffer = nil; char* diskBuffer = NULL;
long offset; long offset;
if (pHeader->dataLen % 4096) { if (pHeader->dataLen % 4096) {
fprintf(stderr, fprintf(stderr,
"ERROR: image size must be multiple of 4096 (%ld isn't)\n", "ERROR: image size must be multiple of 4096 (%u isn't)\n",
pHeader->dataLen); pHeader->dataLen);
err = kNuErrGeneric; err = kNuErrGeneric;
goto bail; goto bail;
@ -277,8 +266,8 @@ CreateDosSource(const ImgHeader* pHeader, FILE* fp,
} }
diskBuffer = malloc(pHeader->dataLen); diskBuffer = malloc(pHeader->dataLen);
if (diskBuffer == nil) { if (diskBuffer == NULL) {
fprintf(stderr, "ERROR: malloc(%ld) failed\n", pHeader->dataLen); fprintf(stderr, "ERROR: malloc(%u) failed\n", pHeader->dataLen);
err = kNuErrMalloc; err = kNuErrMalloc;
goto bail; goto bail;
} }
@ -319,13 +308,13 @@ CreateDosSource(const ImgHeader* pHeader, FILE* fp,
* "true", so NufxLib will free the buffer for us. * "true", so NufxLib will free the buffer for us.
*/ */
err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed, 0, err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed, 0,
(const unsigned char*) diskBuffer, 0, pHeader->dataLen, (const uint8_t*) diskBuffer, 0, pHeader->dataLen,
FreeCallback, ppDataSource); FreeCallback, ppDataSource);
if (err == kNuErrNone) if (err == kNuErrNone)
diskBuffer = nil; diskBuffer = NULL;
bail: bail:
if (diskBuffer != nil) if (diskBuffer != NULL)
free(diskBuffer); free(diskBuffer);
return err; return err;
} }
@ -338,18 +327,17 @@ bail:
* This requires opening up the 2IMG file, verifying that it's okay, and * This requires opening up the 2IMG file, verifying that it's okay, and
* then creating a new disk image record and thread. * then creating a new disk image record and thread.
*/ */
int int ConvertFromImgToShk(const char* srcName, const char* dstName)
ConvertFromImgToShk(const char* srcName, const char* dstName)
{ {
NuError err; NuError err;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
NuDataSource* pDataSource = nil; NuDataSource* pDataSource = NULL;
NuRecordIdx recordIdx; NuRecordIdx recordIdx;
NuFileDetails fileDetails; NuFileDetails fileDetails;
ImgHeader header; ImgHeader header;
FILE* fp = nil; FILE* fp = NULL;
long flushStatus; uint32_t flushStatus;
char* storageName = nil; char* storageName = NULL;
char* cp; char* cp;
printf("Converting 2IMG file '%s' to ShrinkIt archive '%s'\n\n", printf("Converting 2IMG file '%s' to ShrinkIt archive '%s'\n\n",
@ -394,10 +382,10 @@ ConvertFromImgToShk(const char* srcName, const char* dstName)
/* create the name that will be stored in the archive */ /* create the name that will be stored in the archive */
storageName = strdup(dstName); storageName = strdup(dstName);
cp = strrchr(storageName, '.'); cp = strrchr(storageName, '.');
if (cp != nil) if (cp != NULL)
*cp = '\0'; *cp = '\0';
cp = strrchr(storageName, kLocalFssep); cp = strrchr(storageName, kLocalFssep);
if (cp != nil && *(cp+1) != '\0') if (cp != NULL && *(cp+1) != '\0')
cp++; cp++;
else else
cp = storageName; cp = storageName;
@ -410,7 +398,7 @@ ConvertFromImgToShk(const char* srcName, const char* dstName)
/* set up the contents of the NuFX Record */ /* set up the contents of the NuFX Record */
memset(&fileDetails, 0, sizeof(fileDetails)); memset(&fileDetails, 0, sizeof(fileDetails));
fileDetails.storageName = cp; fileDetails.storageNameMOR = cp;
fileDetails.fileSysID = kNuFileSysUnknown; /* DOS? ProDOS? */ fileDetails.fileSysID = kNuFileSysUnknown; /* DOS? ProDOS? */
fileDetails.fileSysInfo = kLocalFssep; fileDetails.fileSysInfo = kLocalFssep;
fileDetails.access = kNuAccessUnlocked; fileDetails.access = kNuAccessUnlocked;
@ -433,11 +421,11 @@ ConvertFromImgToShk(const char* srcName, const char* dstName)
switch (header.imageFormat) { switch (header.imageFormat) {
case kImageFormatDOS: case kImageFormatDOS:
err = CreateDosSource(&header, fp, &pDataSource); err = CreateDosSource(&header, fp, &pDataSource);
fp = nil; fp = NULL;
break; break;
case kImageFormatProDOS: case kImageFormatProDOS:
err = CreateProdosSource(&header, fp, &pDataSource); err = CreateProdosSource(&header, fp, &pDataSource);
fp = nil; fp = NULL;
break; break;
default: default:
fprintf(stderr, "How the heck did I get here?"); fprintf(stderr, "How the heck did I get here?");
@ -451,17 +439,17 @@ ConvertFromImgToShk(const char* srcName, const char* dstName)
/* add a disk image thread */ /* add a disk image thread */
err = NuAddThread(pArchive, recordIdx, kNuThreadIDDiskImage, pDataSource, err = NuAddThread(pArchive, recordIdx, kNuThreadIDDiskImage, pDataSource,
nil); NULL);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to create thread (err=%d)\n", err); fprintf(stderr, "ERROR: unable to create thread (err=%d)\n", err);
goto bail; goto bail;
} }
pDataSource = nil; /* library owns it now */ pDataSource = NULL; /* library owns it now */
/* nothing happens until we Flush */ /* nothing happens until we Flush */
err = NuFlush(pArchive, &flushStatus); err = NuFlush(pArchive, &flushStatus);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: flush failed (err=%d, status=0x%04lx)\n", fprintf(stderr, "ERROR: flush failed (err=%d, status=0x%04x)\n",
err, flushStatus); err, flushStatus);
goto bail; goto bail;
} }
@ -470,17 +458,17 @@ ConvertFromImgToShk(const char* srcName, const char* dstName)
fprintf(stderr, "ERROR: close failed (err=%d)\n", err); fprintf(stderr, "ERROR: close failed (err=%d)\n", err);
goto bail; goto bail;
} }
pArchive = nil; pArchive = NULL;
bail: bail:
if (pArchive != nil) { if (pArchive != NULL) {
(void)NuAbort(pArchive); (void)NuAbort(pArchive);
(void)NuClose(pArchive); (void)NuClose(pArchive);
} }
NuFreeDataSource(pDataSource); NuFreeDataSource(pDataSource);
if (storageName != nil) if (storageName != NULL)
free(storageName); free(storageName);
if (fp != nil) if (fp != NULL)
fclose(fp); fclose(fp);
return (err == kNuErrNone) ? 0 : -1; return (err == kNuErrNone) ? 0 : -1;
} }
@ -492,17 +480,16 @@ bail:
* This takes a simple-minded approach and assumes that the first record * This takes a simple-minded approach and assumes that the first record
* in the archive has the disk image in it. If it doesn't, we give up. * in the archive has the disk image in it. If it doesn't, we give up.
*/ */
int int ConvertFromShkToImg(const char* srcName, const char* dstName)
ConvertFromShkToImg(const char* srcName, const char* dstName)
{ {
NuError err; NuError err;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
NuRecordIdx recordIdx; NuRecordIdx recordIdx;
const NuRecord* pRecord; const NuRecord* pRecord;
const NuThread* pThread = nil; const NuThread* pThread = NULL;
ImgHeader header; ImgHeader header;
FILE* fp = nil; FILE* fp = NULL;
int idx; int idx;
printf("Converting ShrinkIt archive '%s' to 2IMG file '%s'\n\n", printf("Converting ShrinkIt archive '%s' to 2IMG file '%s'\n\n",
@ -592,10 +579,10 @@ ConvertFromShkToImg(const char* srcName, const char* dstName)
} }
bail: bail:
if (pArchive != nil) if (pArchive != NULL)
NuClose(pArchive); NuClose(pArchive);
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
if (fp != nil) if (fp != NULL)
fclose(fp); fclose(fp);
return (err == kNuErrNone) ? 0 : -1; return (err == kNuErrNone) ? 0 : -1;
} }
@ -604,13 +591,12 @@ bail:
/* /*
* Figure out what kind of archive this is by looking at the filename. * Figure out what kind of archive this is by looking at the filename.
*/ */
ArchiveKind ArchiveKind DetermineKind(const char* filename)
DetermineKind(const char* filename)
{ {
const char* dot; const char* dot;
dot = strrchr(filename, '.'); dot = strrchr(filename, '.');
if (dot == nil) if (dot == NULL)
return kKindUnknown; return kKindUnknown;
if (strcasecmp(dot, ".shk") == 0 || strcasecmp(dot, ".sdk") == 0) if (strcasecmp(dot, ".shk") == 0 || strcasecmp(dot, ".sdk") == 0)
@ -626,8 +612,7 @@ DetermineKind(const char* filename)
/* /*
* Figure out what we want to do. * Figure out what we want to do.
*/ */
int int main(int argc, char** argv)
main(int argc, char** argv)
{ {
ArchiveKind kind; ArchiveKind kind;
int cc; int cc;

View File

@ -47,8 +47,7 @@ char gSentRecordWarning = false;
/* /*
* This gets called when a buffer DataSource is no longer needed. * This gets called when a buffer DataSource is no longer needed.
*/ */
NuResult NuResult FreeCallback(NuArchive* pArchive, void* args)
FreeCallback(NuArchive* pArchive, void* args)
{ {
free(args); free(args);
return kNuOK; return kNuOK;
@ -60,14 +59,13 @@ FreeCallback(NuArchive* pArchive, void* args)
* This assumes the library is configured for compression (it defaults * This assumes the library is configured for compression (it defaults
* to LZW/2, so this is a reasonable assumption). * to LZW/2, so this is a reasonable assumption).
*/ */
NuError NuError CopyThreadRecompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
CopyThreadRecompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
long flags, const NuThread* pThread, long newRecordIdx) long flags, const NuThread* pThread, long newRecordIdx)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuDataSource* pDataSource = nil; NuDataSource* pDataSource = NULL;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
uchar* buffer = nil; uint8_t* buffer = NULL;
/* /*
* Allocate a buffer large enough to hold all the uncompressed data, and * Allocate a buffer large enough to hold all the uncompressed data, and
@ -77,7 +75,7 @@ CopyThreadRecompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
*/ */
if (pThread->actualThreadEOF) { if (pThread->actualThreadEOF) {
buffer = malloc(pThread->actualThreadEOF); buffer = malloc(pThread->actualThreadEOF);
if (buffer == nil) { if (buffer == NULL) {
err = kNuErrMalloc; err = kNuErrMalloc;
goto bail; goto bail;
} }
@ -95,7 +93,7 @@ CopyThreadRecompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
*/ */
err = NuExtractThread(pInArchive, pThread->threadIdx, pDataSink); err = NuExtractThread(pInArchive, pThread->threadIdx, pDataSink);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to extract thread %ld (err=%d)\n", fprintf(stderr, "ERROR: unable to extract thread %u (err=%d)\n",
pThread->threadIdx, err); pThread->threadIdx, err);
goto bail; goto bail;
} }
@ -111,7 +109,7 @@ CopyThreadRecompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
* We always use "actualThreadEOF" because "thThreadEOF" is broken * We always use "actualThreadEOF" because "thThreadEOF" is broken
* for disk archives created by certain versions of ShrinkIt. * for disk archives created by certain versions of ShrinkIt.
* *
* It's okay to pass in a nil value for "buffer", so long as the * It's okay to pass in a NULL value for "buffer", so long as the
* amount of data in the buffer is also zero. The library will do * amount of data in the buffer is also zero. The library will do
* the right thing. * the right thing.
*/ */
@ -134,25 +132,25 @@ CopyThreadRecompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
goto bail; goto bail;
} }
} }
buffer = nil; /* doClose was set, so it's owned by the data source */ buffer = NULL; /* doClose was set, so it's owned by the data source */
/* /*
* Schedule the data for addition to the record. * Schedule the data for addition to the record.
*/ */
err = NuAddThread(pOutArchive, newRecordIdx, NuGetThreadID(pThread), err = NuAddThread(pOutArchive, newRecordIdx, NuGetThreadID(pThread),
pDataSource, nil); pDataSource, NULL);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to add thread (err=%d)\n", err); fprintf(stderr, "ERROR: unable to add thread (err=%d)\n", err);
goto bail; goto bail;
} }
pDataSource = nil; /* library owns it now */ pDataSource = NULL; /* library owns it now */
bail: bail:
if (pDataSource != nil) if (pDataSource != NULL)
NuFreeDataSource(pDataSource); NuFreeDataSource(pDataSource);
if (pDataSink != nil) if (pDataSink != NULL)
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
if (buffer != nil) if (buffer != NULL)
free(buffer); free(buffer);
return err; return err;
} }
@ -174,14 +172,13 @@ bail:
* reliable but extracts a little more than we need on pre-sized * reliable but extracts a little more than we need on pre-sized
* threads (filenames, comments). * threads (filenames, comments).
*/ */
NuError NuError CopyThreadUncompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
CopyThreadUncompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
long flags, const NuThread* pThread, long newRecordIdx) long flags, const NuThread* pThread, long newRecordIdx)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuDataSource* pDataSource = nil; NuDataSource* pDataSource = NULL;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
uchar* buffer = nil; uint8_t* buffer = NULL;
/* /*
* If we have some data files that were left uncompressed, perhaps * If we have some data files that were left uncompressed, perhaps
@ -207,7 +204,7 @@ CopyThreadUncompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
* wrap a data sink around it. * wrap a data sink around it.
*/ */
buffer = malloc(pThread->thCompThreadEOF); buffer = malloc(pThread->thCompThreadEOF);
if (buffer == nil) { if (buffer == NULL) {
err = kNuErrMalloc; err = kNuErrMalloc;
goto bail; goto bail;
} }
@ -225,7 +222,7 @@ CopyThreadUncompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
*/ */
err = NuExtractThread(pInArchive, pThread->threadIdx, pDataSink); err = NuExtractThread(pInArchive, pThread->threadIdx, pDataSink);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to extract thread %ld (err=%d)\n", fprintf(stderr, "ERROR: unable to extract thread %u (err=%d)\n",
pThread->threadIdx, err); pThread->threadIdx, err);
goto bail; goto bail;
} }
@ -265,7 +262,7 @@ CopyThreadUncompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
goto bail; goto bail;
} }
} }
buffer = nil; /* doClose was set, so it's owned by the data source */ buffer = NULL; /* doClose was set, so it's owned by the data source */
/* yes, this is a kluge... sigh */ /* yes, this is a kluge... sigh */
err = NuDataSourceSetRawCrc(pDataSource, pThread->thThreadCRC); err = NuDataSourceSetRawCrc(pDataSource, pThread->thThreadCRC);
@ -281,19 +278,19 @@ CopyThreadUncompressed(NuArchive* pInArchive, NuArchive* pOutArchive,
* "doClose" on our copy, so we are free to dispose of pDataSource. * "doClose" on our copy, so we are free to dispose of pDataSource.
*/ */
err = NuAddThread(pOutArchive, newRecordIdx, NuGetThreadID(pThread), err = NuAddThread(pOutArchive, newRecordIdx, NuGetThreadID(pThread),
pDataSource, nil); pDataSource, NULL);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to add thread (err=%d)\n", err); fprintf(stderr, "ERROR: unable to add thread (err=%d)\n", err);
goto bail; goto bail;
} }
pDataSource = nil; /* library owns it now */ pDataSource = NULL; /* library owns it now */
bail: bail:
if (pDataSource != nil) if (pDataSource != NULL)
NuFreeDataSource(pDataSource); NuFreeDataSource(pDataSource);
if (pDataSink != nil) if (pDataSink != NULL)
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
if (buffer != nil) if (buffer != NULL)
free(buffer); free(buffer);
return err; return err;
} }
@ -305,8 +302,7 @@ bail:
* Depending on "flags", this will either copy it raw or uncompress and * Depending on "flags", this will either copy it raw or uncompress and
* recompress. * recompress.
*/ */
NuError NuError CopyThread(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
CopyThread(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
const NuThread* pThread, long newRecordIdx) const NuThread* pThread, long newRecordIdx)
{ {
if (flags & kFlagCopyOnly) { if (flags & kFlagCopyOnly) {
@ -327,8 +323,7 @@ CopyThread(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
* of which will not usually have any effect since NufxLib imposes a * of which will not usually have any effect since NufxLib imposes a
* specific thread ordering on most common types) depending on "flags". * specific thread ordering on most common types) depending on "flags".
*/ */
NuError NuError CopyRecord(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
CopyRecord(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
NuRecordIdx recordIdx) NuRecordIdx recordIdx)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
@ -344,7 +339,7 @@ CopyRecord(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
*/ */
err = NuGetRecord(pInArchive, recordIdx, &pRecord); err = NuGetRecord(pInArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to get recordIdx %ld\n", recordIdx); fprintf(stderr, "ERROR: unable to get recordIdx %u\n", recordIdx);
goto bail; goto bail;
} }
@ -362,7 +357,7 @@ CopyRecord(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
numThreads = NuRecordGetNumThreads(pRecord); numThreads = NuRecordGetNumThreads(pRecord);
if (!numThreads) { if (!numThreads) {
fprintf(stderr, "WARNING: recordIdx=%ld was empty\n", recordIdx); fprintf(stderr, "WARNING: recordIdx=%u was empty\n", recordIdx);
goto bail; goto bail;
} }
@ -370,7 +365,7 @@ CopyRecord(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
* Create a new record that looks just like the original. * Create a new record that looks just like the original.
*/ */
memset(&fileDetails, 0, sizeof(fileDetails)); memset(&fileDetails, 0, sizeof(fileDetails));
fileDetails.storageName = pRecord->filename; fileDetails.storageNameMOR = pRecord->filenameMOR;
fileDetails.fileSysID = pRecord->recFileSysID; fileDetails.fileSysID = pRecord->recFileSysID;
fileDetails.fileSysInfo = pRecord->recFileSysInfo; fileDetails.fileSysInfo = pRecord->recFileSysInfo;
fileDetails.access = pRecord->recAccess; fileDetails.access = pRecord->recAccess;
@ -393,7 +388,7 @@ CopyRecord(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
if (flags & kFlagReverseThreads) { if (flags & kFlagReverseThreads) {
for (idx = numThreads-1; idx >= 0; idx--) { for (idx = numThreads-1; idx >= 0; idx--) {
pThread = NuGetThread(pRecord, idx); pThread = NuGetThread(pRecord, idx);
assert(pThread != nil); assert(pThread != NULL);
err = CopyThread(pInArchive, pOutArchive, flags, pThread, err = CopyThread(pInArchive, pOutArchive, flags, pThread,
newRecordIdx); newRecordIdx);
@ -403,7 +398,7 @@ CopyRecord(NuArchive* pInArchive, NuArchive* pOutArchive, long flags,
} else { } else {
for (idx = 0; idx < numThreads; idx++) { for (idx = 0; idx < numThreads; idx++) {
pThread = NuGetThread(pRecord, idx); pThread = NuGetThread(pRecord, idx);
assert(pThread != nil); assert(pThread != NULL);
err = CopyThread(pInArchive, pOutArchive, flags, pThread, err = CopyThread(pInArchive, pOutArchive, flags, pThread,
newRecordIdx); newRecordIdx);
@ -422,16 +417,15 @@ bail:
* *
* Returns 0 on success, nonzero on failure. * Returns 0 on success, nonzero on failure.
*/ */
int int LaunderArchive(const char* inFile, const char* outFile,
LaunderArchive(const char* inFile, const char* outFile, NuValue compressMethod, NuValue compressMethod, long flags)
long flags)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuArchive* pInArchive = nil; NuArchive* pInArchive = NULL;
NuArchive* pOutArchive = nil; NuArchive* pOutArchive = NULL;
const NuMasterHeader* pMasterHeader; const NuMasterHeader* pMasterHeader;
NuRecordIdx recordIdx; NuRecordIdx recordIdx;
long idx, flushStatus; uint32_t idx, flushStatus;
err = NuOpenRO(inFile, &pInArchive); err = NuOpenRO(inFile, &pInArchive);
if (err != kNuErrNone) { if (err != kNuErrNone) {
@ -487,10 +481,10 @@ LaunderArchive(const char* inFile, const char* outFile, NuValue compressMethod,
/* /*
* Iterate through the set of records. * Iterate through the set of records.
*/ */
for (idx = 0; idx < (int)pMasterHeader->mhTotalRecords; idx++) { for (idx = 0; idx < pMasterHeader->mhTotalRecords; idx++) {
err = NuGetRecordIdxByPosition(pInArchive, idx, &recordIdx); err = NuGetRecordIdxByPosition(pInArchive, idx, &recordIdx);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record #%ld (err=%d)\n", fprintf(stderr, "ERROR: couldn't get record #%u (err=%d)\n",
idx, err); idx, err);
goto bail; goto bail;
} }
@ -525,7 +519,7 @@ LaunderArchive(const char* inFile, const char* outFile, NuValue compressMethod,
err = NuFlush(pOutArchive, &flushStatus); err = NuFlush(pOutArchive, &flushStatus);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, fprintf(stderr,
"ERROR: flush failed (err=%d, status=0x%04lx)\n", "ERROR: flush failed (err=%d, status=0x%04x)\n",
err, flushStatus); err, flushStatus);
goto bail; goto bail;
} }
@ -535,15 +529,15 @@ LaunderArchive(const char* inFile, const char* outFile, NuValue compressMethod,
/* first and only flush if frequent-flushing wasn't enabled */ /* first and only flush if frequent-flushing wasn't enabled */
err = NuFlush(pOutArchive, &flushStatus); err = NuFlush(pOutArchive, &flushStatus);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: flush failed (err=%d, status=0x%04lx)\n", fprintf(stderr, "ERROR: flush failed (err=%d, status=0x%04x)\n",
err, flushStatus); err, flushStatus);
goto bail; goto bail;
} }
bail: bail:
if (pInArchive != nil) if (pInArchive != NULL)
NuClose(pInArchive); NuClose(pInArchive);
if (pOutArchive != nil) { if (pOutArchive != NULL) {
if (err != kNuErrNone) if (err != kNuErrNone)
NuAbort(pOutArchive); NuAbort(pOutArchive);
NuClose(pOutArchive); /* flush pending changes and close */ NuClose(pOutArchive); /* flush pending changes and close */
@ -559,12 +553,11 @@ bail:
* does everything we need here. * does everything we need here.
*/ */
int myoptind = 0; int myoptind = 0;
char* myoptarg = nil; char* myoptarg = NULL;
const char* curchar = nil; const char* curchar = NULL;
int skipnext = false; int skipnext = false;
int int mygetopt(int argc, char** argv, const char* optstr)
mygetopt(int argc, char** argv, const char* optstr)
{ {
if (!myoptind) { if (!myoptind) {
myoptind = 1; myoptind = 1;
@ -609,8 +602,7 @@ mygetopt(int argc, char** argv, const char* optstr)
/* /*
* Print usage info. * Print usage info.
*/ */
void void Usage(const char* argv0)
Usage(const char* argv0)
{ {
fprintf(stderr, "Usage: %s [-crfat] [-m method] infile.shk outfile.shk\n", fprintf(stderr, "Usage: %s [-crfat] [-m method] infile.shk outfile.shk\n",
argv0); argv0);
@ -627,19 +619,18 @@ Usage(const char* argv0)
/* /*
* Grab the name of an archive to read. * Grab the name of an archive to read.
*/ */
int int main(int argc, char** argv)
main(int argc, char** argv)
{ {
NuValue compressMethod = kNuCompressLZW2; NuValue compressMethod = kNuCompressLZW2;
long major, minor, bug; int32_t major, minor, bug;
const char* pBuildDate; const char* pBuildDate;
long flags = 0; long flags = 0;
int errorFlag; int errorFlag;
int ic; int ic;
int cc; int cc;
(void) NuGetVersion(&major, &minor, &bug, &pBuildDate, nil); (void) NuGetVersion(&major, &minor, &bug, &pBuildDate, NULL);
printf("Using NuFX lib %ld.%ld.%ld built on or after %s\n", printf("Using NuFX lib %d.%d.%d built on or after %s\n",
major, minor, bug, pBuildDate); major, minor, bug, pBuildDate);
errorFlag = false; errorFlag = false;

View File

@ -28,49 +28,35 @@ ALL_SRCS = Exerciser.c ImgConv.c Launder.c TestBasic.c \
NUFXLIB = -L.. -lnufx NUFXLIB = -L.. -lnufx
PRODUCTS = exerciser imgconv launder test-basic test-extract test-simple \ PRODUCTS = exerciser imgconv launder test-basic test-extract test-names \
test-twirl test-simple test-twirl
#ifdef PURIFY_BUILD
# PURIFY = purify
# CFLAGS += -DPURIFY
#endif
#ifdef QUANTIFY_BUILD
# QUANTIFY = quantify
# CFLAGS += -DQUANTIFY
#endif
all: $(PRODUCTS) all: $(PRODUCTS)
@true @true
#quantify:
# -rm -f $(PRODUCT)
# @$(MAKE) QUANTIFY_BUILD=1
#
#purify:
# -rm -f $(PRODUCT)
# @$(MAKE) PURIFY_BUILD=1
exerciser: Exerciser.o $(LIB_PRODUCT) exerciser: Exerciser.o $(LIB_PRODUCT)
$(PURIFY) $(QUANTIFY) $(CC) -o $@ Exerciser.o $(NUFXLIB) @LIBS@ $(CC) -o $@ Exerciser.o $(NUFXLIB) @LIBS@
imgconv: ImgConv.o $(LIB_PRODUCT) imgconv: ImgConv.o $(LIB_PRODUCT)
$(PURIFY) $(QUANTIFY) $(CC) -o $@ ImgConv.o $(NUFXLIB) @LIBS@ $(CC) -o $@ ImgConv.o $(NUFXLIB) @LIBS@
launder: Launder.o $(LIB_PRODUCT) launder: Launder.o $(LIB_PRODUCT)
$(PURIFY) $(QUANTIFY) $(CC) -o $@ Launder.o $(NUFXLIB) @LIBS@ $(CC) -o $@ Launder.o $(NUFXLIB) @LIBS@
test-basic: TestBasic.o $(LIB_PRODUCT) test-basic: TestBasic.o $(LIB_PRODUCT)
$(PURIFY) $(QUANTIFY) $(CC) -o $@ TestBasic.o $(NUFXLIB) @LIBS@ $(CC) -o $@ TestBasic.o $(NUFXLIB) @LIBS@
test-simple: TestSimple.o $(LIB_PRODUCT)
$(PURIFY) $(QUANTIFY) $(CC) -o $@ TestSimple.o $(NUFXLIB) @LIBS@
test-extract: TestExtract.o $(LIB_PRODUCT) test-extract: TestExtract.o $(LIB_PRODUCT)
$(PURIFY) $(QUANTIFY) $(CC) -o $@ TestExtract.o $(NUFXLIB) @LIBS@ $(CC) -o $@ TestExtract.o $(NUFXLIB) @LIBS@
test-names: TestNames.o $(LIB_PRODUCT)
$(CC) -o $@ TestNames.o $(NUFXLIB) @LIBS@
test-simple: TestSimple.o $(LIB_PRODUCT)
$(CC) -o $@ TestSimple.o $(NUFXLIB) @LIBS@
test-twirl: TestTwirl.o $(LIB_PRODUCT) test-twirl: TestTwirl.o $(LIB_PRODUCT)
$(PURIFY) $(QUANTIFY) $(CC) -o $@ TestTwirl.o $(NUFXLIB) @LIBS@ $(CC) -o $@ TestTwirl.o $(NUFXLIB) @LIBS@
tags:: tags::
ctags --totals -R ../* ctags --totals -R ../*
@ -84,8 +70,12 @@ distclean: clean
-rm -f tags -rm -f tags
-rm -f Makefile Makefile.bak -rm -f Makefile Makefile.bak
depend: COMMON_HDRS = ../NufxLibPriv.h ../NufxLib.h ../MiscStuff.h ../SysDefs.h
makedepend -- $(CFLAGS) -I/usr/local/include -- $(ALL_SRCS) Exerciser.o: Exerciser.c $(COMMON_HDRS)
ImgConv.o: ImgConv.c $(COMMON_HDRS)
# DO NOT DELETE THIS LINE -- make depend depends on it. Launder.o: Launder.c $(COMMON_HDRS)
TestBasic.o: TestBasic.c $(COMMON_HDRS)
TestExtract.o: TestExtract.c $(COMMON_HDRS)
TestNames.o: TestNames.c $(COMMON_HDRS)
TestSimple.o: TestSimple.c $(COMMON_HDRS)
TestTwirl.o: TestTwirl.c $(COMMON_HDRS)

View File

@ -15,6 +15,8 @@
#define kTestTempFile "nlbt.tmp" #define kTestTempFile "nlbt.tmp"
#define kNumEntries 3 /* how many records are we going to add? */ #define kNumEntries 3 /* how many records are we going to add? */
/* stick to ASCII characters for these -- not doing conversions just yet */
#define kTestEntryBytes "bytes" #define kTestEntryBytes "bytes"
#define kTestEntryBytesUPPER "BYTES" #define kTestEntryBytesUPPER "BYTES"
#define kTestEntryEnglish "English" #define kTestEntryEnglish "English"
@ -39,12 +41,11 @@ char gSuppressError = false;
/* /*
* Get a single character of input from the user. * Get a single character of input from the user.
*/ */
static char static char TGetReplyChar(char defaultReply)
TGetReplyChar(char defaultReply)
{ {
char tmpBuf[32]; char tmpBuf[32];
if (fgets(tmpBuf, sizeof(tmpBuf), stdin) == nil) if (fgets(tmpBuf, sizeof(tmpBuf), stdin) == NULL)
return defaultReply; return defaultReply;
if (tmpBuf[0] == '\n' || tmpBuf[0] == '\r') if (tmpBuf[0] == '\n' || tmpBuf[0] == '\r')
return defaultReply; return defaultReply;
@ -52,14 +53,13 @@ TGetReplyChar(char defaultReply)
return tmpBuf[0]; return tmpBuf[0];
} }
NuError NuError AddSimpleRecord(NuArchive* pArchive, const char* filenameMOR,
AddSimpleRecord(NuArchive* pArchive, const char* filename,
NuRecordIdx* pRecordIdx) NuRecordIdx* pRecordIdx)
{ {
NuFileDetails fileDetails; NuFileDetails fileDetails;
memset(&fileDetails, 0, sizeof(fileDetails)); memset(&fileDetails, 0, sizeof(fileDetails));
fileDetails.storageName = filename; fileDetails.storageNameMOR = filenameMOR;
fileDetails.fileSysInfo = kLocalFssep; fileDetails.fileSysInfo = kLocalFssep;
fileDetails.access = kNuAccessUnlocked; fileDetails.access = kNuAccessUnlocked;
@ -70,8 +70,7 @@ AddSimpleRecord(NuArchive* pArchive, const char* filename,
/* /*
* Display error messages... or not. * Display error messages... or not.
*/ */
NuResult NuResult ErrorMessageHandler(NuArchive* pArchive, void* vErrorMessage)
ErrorMessageHandler(NuArchive* pArchive, void* vErrorMessage)
{ {
const NuErrorMessage* pErrorMessage = (const NuErrorMessage*) vErrorMessage; const NuErrorMessage* pErrorMessage = (const NuErrorMessage*) vErrorMessage;
@ -80,12 +79,12 @@ ErrorMessageHandler(NuArchive* pArchive, void* vErrorMessage)
if (pErrorMessage->isDebug) { if (pErrorMessage->isDebug) {
fprintf(stderr, "%sNufxLib says: [%s:%d %s] %s\n", fprintf(stderr, "%sNufxLib says: [%s:%d %s] %s\n",
pArchive == nil ? "GLOBAL>" : "", pArchive == NULL ? "GLOBAL>" : "",
pErrorMessage->file, pErrorMessage->line, pErrorMessage->function, pErrorMessage->file, pErrorMessage->line, pErrorMessage->function,
pErrorMessage->message); pErrorMessage->message);
} else { } else {
fprintf(stderr, "%sNufxLib says: %s\n", fprintf(stderr, "%sNufxLib says: %s\n",
pArchive == nil ? "GLOBAL>" : "", pArchive == NULL ? "GLOBAL>" : "",
pErrorMessage->message); pErrorMessage->message);
} }
@ -95,13 +94,37 @@ ErrorMessageHandler(NuArchive* pArchive, void* vErrorMessage)
/* /*
* This gets called when a buffer DataSource is no longer needed. * This gets called when a buffer DataSource is no longer needed.
*/ */
NuResult NuResult FreeCallback(NuArchive* pArchive, void* args)
FreeCallback(NuArchive* pArchive, void* args)
{ {
free(args); free(args);
return kNuOK; return kNuOK;
} }
/*
* If the test file currently exists, ask the user if it's okay to remove
* it.
*
* Returns 0 if the file was successfully removed, -1 if the file could not
* be removed (because the unlink failed, or the user refused).
*/
int RemoveTestFile(const char* title, const char* fileName)
{
char answer;
if (access(fileName, F_OK) == 0) {
printf("%s '%s' exists, remove (y/n)? ", title, fileName);
fflush(stdout);
answer = TGetReplyChar('n');
if (tolower(answer) != 'y')
return -1;
if (unlink(fileName) < 0) {
perror("unlink");
return -1;
}
}
return 0;
}
/* /*
* =========================================================================== * ===========================================================================
@ -113,21 +136,20 @@ FreeCallback(NuArchive* pArchive, void* args)
* Make sure the flags that control how we open the file work right, * Make sure the flags that control how we open the file work right,
* and verify that we handle existing zero-byte archive files correctly. * and verify that we handle existing zero-byte archive files correctly.
*/ */
int int Test_OpenFlags(void)
Test_OpenFlags(void)
{ {
NuError err; NuError err;
FILE* fp = nil; FILE* fp = NULL;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
printf("... open zero-byte existing\n"); printf("... open zero-byte existing\n");
fp = fopen(kTestArchive, kNuFileOpenWriteTrunc); fp = fopen(kTestArchive, kNuFileOpenWriteTrunc);
if (fp == nil) { if (fp == NULL) {
perror("fopen kTestArchive"); perror("fopen kTestArchive");
goto failed; goto failed;
} }
fclose(fp); fclose(fp);
fp = nil; fp = NULL;
FAIL_OK; FAIL_OK;
err = NuOpenRW(kTestArchive, kTestTempFile, kNuOpenCreat|kNuOpenExcl, err = NuOpenRW(kTestArchive, kTestTempFile, kNuOpenCreat|kNuOpenExcl,
@ -149,7 +171,7 @@ Test_OpenFlags(void)
fprintf(stderr, "ERROR: close failed\n"); fprintf(stderr, "ERROR: close failed\n");
goto failed; goto failed;
} }
pArchive = nil; pArchive = NULL;
if (access(kTestArchive, F_OK) == 0) { if (access(kTestArchive, F_OK) == 0) {
fprintf(stderr, "ERROR: archive should have been removed but wasn't\n"); fprintf(stderr, "ERROR: archive should have been removed but wasn't\n");
@ -159,7 +181,7 @@ Test_OpenFlags(void)
return 0; return 0;
failed: failed:
if (pArchive != nil) { if (pArchive != NULL) {
NuAbort(pArchive); NuAbort(pArchive);
NuClose(pArchive); NuClose(pArchive);
} }
@ -170,14 +192,13 @@ failed:
/* /*
* Add some files to the archive. These will be used by later tests. * Add some files to the archive. These will be used by later tests.
*/ */
int int Test_AddStuff(NuArchive* pArchive)
Test_AddStuff(NuArchive* pArchive)
{ {
NuError err; NuError err;
uchar* buf = nil; uint8_t* buf = NULL;
NuDataSource* pDataSource = nil; NuDataSource* pDataSource = NULL;
NuRecordIdx recordIdx; NuRecordIdx recordIdx;
long status; uint32_t status;
int i; int i;
static const char* testMsg = static const char* testMsg =
"This is a nice test message that has linefeeds in it so we can\n" "This is a nice test message that has linefeeds in it so we can\n"
@ -185,20 +206,20 @@ Test_AddStuff(NuArchive* pArchive)
"all. It's certainly nice to know that everything works the way\n" "all. It's certainly nice to know that everything works the way\n"
"it's supposed to, which I suppose is why we have this nifty test\n" "it's supposed to, which I suppose is why we have this nifty test\n"
"program available. It sure would be nice if everybody tested\n" "program available. It sure would be nice if everybody tested\n"
"there code, but where would Microsoft be without endless upgrades\n" "their code, but where would Microsoft be without endless upgrades\n"
"and service packs? Bugs are what America was built on, and\n" "and service packs? Bugs are what America was built on, and\n"
"anybody who says otherwise is a pinko commie lowlife. Verily.\n"; "anybody who says otherwise is a pinko commie lowlife. Verily.\n";
printf("... add 'bytes' record\n"); printf("... add 'bytes' record\n");
buf = malloc(131072); buf = malloc(131072);
if (buf == nil) if (buf == NULL)
goto failed; goto failed;
for (i = 0; i < 131072; i++) for (i = 0; i < 131072; i++)
*(buf+i) = i & 0xff; *(buf+i) = i & 0xff;
FAIL_OK; FAIL_OK;
err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed, err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed,
0, nil, 0, 131072, FreeCallback, &pDataSource); 0, NULL, 0, 131072, FreeCallback, &pDataSource);
FAIL_BAD; FAIL_BAD;
if (err == kNuErrNone) { if (err == kNuErrNone) {
fprintf(stderr, "ERROR: that should've failed!\n"); fprintf(stderr, "ERROR: that should've failed!\n");
@ -215,7 +236,7 @@ Test_AddStuff(NuArchive* pArchive)
"ERROR: 'bytes' data source create failed (err=%d)\n", err); "ERROR: 'bytes' data source create failed (err=%d)\n", err);
goto failed; goto failed;
} }
buf = nil; /* now owned by library */ buf = NULL; /* now owned by library */
err = AddSimpleRecord(pArchive, kTestEntryBytes, &recordIdx); err = AddSimpleRecord(pArchive, kTestEntryBytes, &recordIdx);
if (err != kNuErrNone) { if (err != kNuErrNone) {
@ -224,12 +245,12 @@ Test_AddStuff(NuArchive* pArchive)
} }
err = NuAddThread(pArchive, recordIdx, kNuThreadIDDataFork, pDataSource, err = NuAddThread(pArchive, recordIdx, kNuThreadIDDataFork, pDataSource,
nil); NULL);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: 'bytes' thread add failed (err=%d)\n", err); fprintf(stderr, "ERROR: 'bytes' thread add failed (err=%d)\n", err);
goto failed; goto failed;
} }
pDataSource = nil; /* now owned by library */ pDataSource = NULL; /* now owned by library */
/* /*
@ -237,7 +258,7 @@ Test_AddStuff(NuArchive* pArchive)
*/ */
printf("... add 'English' record\n"); printf("... add 'English' record\n");
err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed, err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed,
0, (const uchar*)testMsg, 0, strlen(testMsg), nil, &pDataSource); 0, (const uint8_t*)testMsg, 0, strlen(testMsg), NULL, &pDataSource);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, fprintf(stderr,
"ERROR: 'English' source create failed (err=%d)\n", err); "ERROR: 'English' source create failed (err=%d)\n", err);
@ -246,7 +267,7 @@ Test_AddStuff(NuArchive* pArchive)
FAIL_OK; FAIL_OK;
err = NuAddThread(pArchive, recordIdx, kNuThreadIDDataFork, pDataSource, err = NuAddThread(pArchive, recordIdx, kNuThreadIDDataFork, pDataSource,
nil); NULL);
FAIL_BAD; FAIL_BAD;
if (err == kNuErrNone) { if (err == kNuErrNone) {
fprintf(stderr, "ERROR: 'English' add should've conflicted!\n"); fprintf(stderr, "ERROR: 'English' add should've conflicted!\n");
@ -268,12 +289,12 @@ Test_AddStuff(NuArchive* pArchive)
} }
err = NuAddThread(pArchive, recordIdx, kNuThreadIDDataFork, pDataSource, err = NuAddThread(pArchive, recordIdx, kNuThreadIDDataFork, pDataSource,
nil); NULL);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: 'English' thread add failed (err=%d)\n", err); fprintf(stderr, "ERROR: 'English' thread add failed (err=%d)\n", err);
goto failed; goto failed;
} }
pDataSource = nil; /* now owned by library */ pDataSource = NULL; /* now owned by library */
/* /*
@ -281,7 +302,7 @@ Test_AddStuff(NuArchive* pArchive)
*/ */
printf("... add 'long' record\n"); printf("... add 'long' record\n");
err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed, err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed,
0, nil, 0, 0, nil, &pDataSource); 0, NULL, 0, 0, NULL, &pDataSource);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, fprintf(stderr,
"ERROR: 'English' source create failed (err=%d)\n", err); "ERROR: 'English' source create failed (err=%d)\n", err);
@ -295,12 +316,12 @@ Test_AddStuff(NuArchive* pArchive)
} }
err = NuAddThread(pArchive, recordIdx, kNuThreadIDRsrcFork, pDataSource, err = NuAddThread(pArchive, recordIdx, kNuThreadIDRsrcFork, pDataSource,
nil); NULL);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: 'long' thread add failed (err=%d)\n", err); fprintf(stderr, "ERROR: 'long' thread add failed (err=%d)\n", err);
goto failed; goto failed;
} }
pDataSource = nil; /* now owned by library */ pDataSource = NULL; /* now owned by library */
/* /*
@ -308,7 +329,7 @@ Test_AddStuff(NuArchive* pArchive)
*/ */
err = NuFlush(pArchive, &status); err = NuFlush(pArchive, &status);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr,"ERROR: couldn't flush after add (err=%d, status=%ld)\n", fprintf(stderr, "ERROR: couldn't flush after add (err=%d, status=%u)\n",
err, status); err, status);
goto failed; goto failed;
} }
@ -318,16 +339,16 @@ Test_AddStuff(NuArchive* pArchive)
*/ */
err = NuFlush(pArchive, &status); err = NuFlush(pArchive, &status);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr,"ERROR: second add flush failed (err=%d, status=%ld)\n", fprintf(stderr, "ERROR: second add flush failed (err=%d, status=%u)\n",
err, status); err, status);
goto failed; goto failed;
} }
return 0; return 0;
failed: failed:
if (pDataSource != nil) if (pDataSource != NULL)
NuFreeDataSource(pDataSource); NuFreeDataSource(pDataSource);
if (buf != nil) if (buf != NULL)
free(buf); free(buf);
return -1; return -1;
} }
@ -336,19 +357,18 @@ failed:
/* /*
* Make sure that what we're seeing makes sense. * Make sure that what we're seeing makes sense.
*/ */
NuResult NuResult TestContentsCallback(NuArchive* pArchive, void* vpRecord)
TestContentsCallback(NuArchive* pArchive, void* vpRecord)
{ {
const NuRecord* pRecord = (NuRecord*) vpRecord; const NuRecord* pRecord = (NuRecord*) vpRecord;
if (strcmp(pRecord->filename, kTestEntryBytes) == 0 || if (strcmp(pRecord->filenameMOR, kTestEntryBytes) == 0 ||
strcmp(pRecord->filename, kTestEntryEnglish) == 0 || strcmp(pRecord->filenameMOR, kTestEntryEnglish) == 0 ||
strcmp(pRecord->filename, kTestEntryLong) == 0) strcmp(pRecord->filenameMOR, kTestEntryLong) == 0)
{ {
return kNuOK; return kNuOK;
} }
fprintf(stderr, "ERROR: found mystery entry '%s'\n", pRecord->filename); fprintf(stderr, "ERROR: found mystery entry '%s'\n", pRecord->filenameMOR);
return kNuAbort; return kNuAbort;
} }
@ -356,8 +376,7 @@ TestContentsCallback(NuArchive* pArchive, void* vpRecord)
/* /*
* Verify that the contents look about right. * Verify that the contents look about right.
*/ */
int int Test_Contents(NuArchive* pArchive)
Test_Contents(NuArchive* pArchive)
{ {
NuError err; NuError err;
long posn; long posn;
@ -386,21 +405,21 @@ Test_Contents(NuArchive* pArchive)
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record index %ld (err=%d)\n", fprintf(stderr, "ERROR: couldn't get record index %u (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
assert(pRecord != nil); assert(pRecord != NULL);
switch (posn) { switch (posn) {
case 0: case 0:
cc = strcmp(pRecord->filename, kTestEntryBytes); cc = strcmp(pRecord->filenameMOR, kTestEntryBytes);
break; break;
case 1: case 1:
cc = strcmp(pRecord->filename, kTestEntryEnglish); cc = strcmp(pRecord->filenameMOR, kTestEntryEnglish);
break; break;
case 2: case 2:
cc = strcmp(pRecord->filename, kTestEntryLong); cc = strcmp(pRecord->filenameMOR, kTestEntryLong);
if (!cc) if (!cc)
cc = !(pRecord->recStorageType == kNuStorageExtended); cc = !(pRecord->recStorageType == kNuStorageExtended);
break; break;
@ -411,8 +430,8 @@ Test_Contents(NuArchive* pArchive)
} }
if (cc) { if (cc) {
fprintf(stderr, "ERROR: got '%s' for %ld (%ld), not expected\n", fprintf(stderr, "ERROR: got '%s' for %ld (%u), not expected\n",
pRecord->filename, posn, recordIdx); pRecord->filenameMOR, posn, recordIdx);
goto failed; goto failed;
} }
} }
@ -437,17 +456,16 @@ failed:
/* /*
* Selection callback filter for "test". This gets called once per record. * Selection callback filter for "test". This gets called once per record.
*/ */
NuResult NuResult VerifySelectionCallback(NuArchive* pArchive, void* vpProposal)
VerifySelectionCallback(NuArchive* pArchive, void* vpProposal)
{ {
NuError err; NuError err;
const NuSelectionProposal* pProposal = vpProposal; const NuSelectionProposal* pProposal = vpProposal;
long count; long count;
if (pProposal->pRecord == nil || pProposal->pThread == nil || if (pProposal->pRecord == NULL || pProposal->pThread == NULL ||
pProposal->pRecord->filename == nil) pProposal->pRecord->filenameMOR == NULL)
{ {
fprintf(stderr, "ERROR: unexpected nil in proposal\n"); fprintf(stderr, "ERROR: unexpected NULL in proposal\n");
goto failed; goto failed;
} }
@ -473,8 +491,7 @@ failed:
/* /*
* Verify the archive contents. * Verify the archive contents.
*/ */
int int Test_Verify(NuArchive* pArchive)
Test_Verify(NuArchive* pArchive)
{ {
NuError err; NuError err;
long count; long count;
@ -520,15 +537,14 @@ failed:
/* /*
* Extract stuff. * Extract stuff.
*/ */
int int Test_Extract(NuArchive* pArchive)
Test_Extract(NuArchive* pArchive)
{ {
NuError err; NuError err;
NuRecordIdx recordIdx; NuRecordIdx recordIdx;
const NuRecord* pRecord; const NuRecord* pRecord;
const NuThread* pThread; const NuThread* pThread;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
uchar* buf = nil; uint8_t* buf = NULL;
printf("... extracting files\n"); printf("... extracting files\n");
@ -549,24 +565,24 @@ Test_Extract(NuArchive* pArchive)
} }
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record index %ld (err=%d)\n", fprintf(stderr, "ERROR: couldn't get record index %u (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
assert(pRecord != nil); assert(pRecord != NULL);
/* we're not using ShrinkIt compat mode, so there should not be a comment */ /* we're not using ShrinkIt compat mode, so there should not be a comment */
pThread = NuGetThread(pRecord, 1); pThread = NuGetThread(pRecord, 1);
assert(pThread != nil); assert(pThread != NULL);
if (NuGetThreadID(pThread) != kNuThreadIDDataFork) { if (NuGetThreadID(pThread) != kNuThreadIDDataFork) {
fprintf(stderr, "ERROR: 'bytes' had unexpected threadID 0x%08lx\n", fprintf(stderr, "ERROR: 'bytes' had unexpected threadID 0x%08x\n",
NuGetThreadID(pThread)); NuGetThreadID(pThread));
goto failed; goto failed;
} }
buf = malloc(pThread->actualThreadEOF); buf = malloc(pThread->actualThreadEOF);
if (buf == nil) { if (buf == NULL) {
fprintf(stderr, "ERROR: malloc(%ld) failed\n",pThread->actualThreadEOF); fprintf(stderr, "ERROR: malloc(%u) failed\n",pThread->actualThreadEOF);
goto failed; goto failed;
} }
@ -587,7 +603,7 @@ Test_Extract(NuArchive* pArchive)
goto failed; goto failed;
} }
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
pDataSink = nil; pDataSink = NULL;
/* /*
* Try to extract with "on" conversion, which should fail because the * Try to extract with "on" conversion, which should fail because the
@ -608,7 +624,7 @@ Test_Extract(NuArchive* pArchive)
goto failed; goto failed;
} }
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
pDataSink = nil; pDataSink = NULL;
/* /*
* Try to extract with "auto" conversion, which should conclude that * Try to extract with "auto" conversion, which should conclude that
@ -628,12 +644,12 @@ Test_Extract(NuArchive* pArchive)
goto failed; goto failed;
} }
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
pDataSink = nil; pDataSink = NULL;
free(buf); free(buf);
buf = nil; buf = NULL;
@ -648,24 +664,24 @@ Test_Extract(NuArchive* pArchive)
} }
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record index %ld (err=%d)\n", fprintf(stderr, "ERROR: couldn't get record index %u (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
assert(pRecord != nil); assert(pRecord != NULL);
/* we're not using ShrinkIt compat mode, so there should not be a comment */ /* we're not using ShrinkIt compat mode, so there should not be a comment */
pThread = NuGetThread(pRecord, 1); pThread = NuGetThread(pRecord, 1);
assert(pThread != nil); assert(pThread != NULL);
if (NuGetThreadID(pThread) != kNuThreadIDDataFork) { if (NuGetThreadID(pThread) != kNuThreadIDDataFork) {
fprintf(stderr, "ERROR: 'English' had unexpected threadID 0x%08lx\n", fprintf(stderr, "ERROR: 'English' had unexpected threadID 0x%08x\n",
NuGetThreadID(pThread)); NuGetThreadID(pThread));
goto failed; goto failed;
} }
buf = malloc(pThread->actualThreadEOF); buf = malloc(pThread->actualThreadEOF);
if (buf == nil) { if (buf == NULL) {
fprintf(stderr, "ERROR: malloc(%ld) failed\n",pThread->actualThreadEOF); fprintf(stderr, "ERROR: malloc(%u) failed\n", pThread->actualThreadEOF);
goto failed; goto failed;
} }
@ -686,7 +702,7 @@ Test_Extract(NuArchive* pArchive)
goto failed; goto failed;
} }
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
pDataSink = nil; pDataSink = NULL;
/* /*
* Try to extract with "auto" conversion, which should fail because the * Try to extract with "auto" conversion, which should fail because the
@ -707,12 +723,12 @@ Test_Extract(NuArchive* pArchive)
goto failed; goto failed;
} }
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
pDataSink = nil; pDataSink = NULL;
/*Free(buf);*/ /*Free(buf);*/
/*buf = nil;*/ /*buf = NULL;*/
@ -727,17 +743,17 @@ Test_Extract(NuArchive* pArchive)
} }
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record index %ld (err=%d)\n", fprintf(stderr, "ERROR: couldn't get record index %u (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
assert(pRecord != nil); assert(pRecord != NULL);
/* we're not using ShrinkIt compat mode, so there should not be a comment */ /* we're not using ShrinkIt compat mode, so there should not be a comment */
pThread = NuGetThread(pRecord, 1); pThread = NuGetThread(pRecord, 1);
assert(pThread != nil); assert(pThread != NULL);
if (NuGetThreadID(pThread) != kNuThreadIDRsrcFork) { if (NuGetThreadID(pThread) != kNuThreadIDRsrcFork) {
fprintf(stderr, "ERROR: 'Long' had unexpected threadID 0x%08lx\n", fprintf(stderr, "ERROR: 'Long' had unexpected threadID 0x%08x\n",
NuGetThreadID(pThread)); NuGetThreadID(pThread));
goto failed; goto failed;
} }
@ -759,20 +775,20 @@ Test_Extract(NuArchive* pArchive)
goto failed; goto failed;
} }
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
pDataSink = nil; pDataSink = NULL;
free(buf); free(buf);
buf = nil; buf = NULL;
return 0; return 0;
failed: failed:
if (buf != nil) if (buf != NULL)
free(buf); free(buf);
if (pDataSink != nil) if (pDataSink != NULL)
(void) NuFreeDataSink(pDataSink); (void) NuFreeDataSink(pDataSink);
return -1; return -1;
} }
@ -780,13 +796,12 @@ failed:
/* /*
* Delete the first and last records. Does *not* flush the archive. * Delete the first and last records. Does *not* flush the archive.
*/ */
int int Test_Delete(NuArchive* pArchive)
Test_Delete(NuArchive* pArchive)
{ {
NuError err; NuError err;
NuRecordIdx recordIdx; NuRecordIdx recordIdx;
const NuRecord* pRecord; const NuRecord* pRecord;
const NuThread* pThread = nil; const NuThread* pThread = NULL;
long count; long count;
int idx; int idx;
@ -802,33 +817,33 @@ Test_Delete(NuArchive* pArchive)
} }
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record index %ld (err=%d)\n", fprintf(stderr, "ERROR: couldn't get record index %u (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
assert(pRecord != nil); assert(pRecord != NULL);
assert(pRecord->recTotalThreads > 0); assert(pRecord->recTotalThreads > 0);
for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) { for (idx = 0; idx < (int)pRecord->recTotalThreads; idx++) {
pThread = NuGetThread(pRecord, idx); pThread = NuGetThread(pRecord, idx);
assert(pThread != nil); assert(pThread != NULL);
err = NuDeleteThread(pArchive, pThread->threadIdx); err = NuDeleteThread(pArchive, pThread->threadIdx);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, fprintf(stderr,
"ERROR: couldn't delete thread #%d (%ld) (err=%d)\n", "ERROR: couldn't delete thread #%d (%u) (err=%d)\n",
idx, recordIdx, err); idx, recordIdx, err);
goto failed; goto failed;
} }
} }
/* try to re-delete the same thread */ /* try to re-delete the same thread */
assert(pThread != nil); assert(pThread != NULL);
FAIL_OK; FAIL_OK;
err = NuDeleteThread(pArchive, pThread->threadIdx); err = NuDeleteThread(pArchive, pThread->threadIdx);
FAIL_BAD; FAIL_BAD;
if (err == kNuErrNone) { if (err == kNuErrNone) {
fprintf(stderr, "ERROR: allowed to re-delete thread (%ld) (err=%d)\n", fprintf(stderr, "ERROR: allowed to re-delete thread (%u) (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
@ -839,7 +854,7 @@ Test_Delete(NuArchive* pArchive)
FAIL_BAD; FAIL_BAD;
if (err == kNuErrNone) { if (err == kNuErrNone) {
fprintf(stderr, fprintf(stderr,
"ERROR: able to delete modified record (%ld) (err=%d)\n", "ERROR: able to delete modified record (%u) (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
@ -847,7 +862,8 @@ Test_Delete(NuArchive* pArchive)
/* /*
* Make sure the attr hasn't been updated yet. * Make sure the attr hasn't been updated yet.
*/ */
err = NuGetAttr(pArchive, kNuAttrNumRecords, (unsigned long*) &count); count = 0;
err = NuGetAttr(pArchive, kNuAttrNumRecords, (uint32_t*) &count);
if (count != kNumEntries) { if (count != kNumEntries) {
fprintf(stderr, "ERROR: kNuAttrNumRecords %ld vs %d\n", fprintf(stderr, "ERROR: kNuAttrNumRecords %ld vs %d\n",
count, kNumEntries); count, kNumEntries);
@ -864,19 +880,19 @@ Test_Delete(NuArchive* pArchive)
} }
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record index %ld (err=%d)\n", fprintf(stderr, "ERROR: couldn't get record index %u (err=%d)\n",
recordIdx, err); recordIdx, err);
goto failed; goto failed;
} }
assert(pRecord != nil); assert(pRecord != NULL);
/* grab the first thread before we whack the record */ /* grab the first thread before we whack the record */
pThread = NuGetThread(pRecord, 0); pThread = NuGetThread(pRecord, 0);
assert(pThread != nil); assert(pThread != NULL);
err = NuDeleteRecord(pArchive, recordIdx); err = NuDeleteRecord(pArchive, recordIdx);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to delete record #%d (%ld) (err=%d)\n", fprintf(stderr, "ERROR: unable to delete record #%d (%u) (err=%d)\n",
kNumEntries-1, recordIdx, err); kNumEntries-1, recordIdx, err);
goto failed; goto failed;
} }
@ -887,7 +903,7 @@ Test_Delete(NuArchive* pArchive)
FAIL_BAD; FAIL_BAD;
if (err == kNuErrNone) { if (err == kNuErrNone) {
fprintf(stderr, fprintf(stderr,
"ERROR: allowed to delete from deleted (%ld) (err=%d)\n", "ERROR: allowed to delete from deleted (%u) (err=%d)\n",
pThread->threadIdx, err); pThread->threadIdx, err);
goto failed; goto failed;
} }
@ -901,8 +917,7 @@ failed:
/* /*
* Verify that the count in the master header has been updated. * Verify that the count in the master header has been updated.
*/ */
int int Test_MasterCount(NuArchive* pArchive, long expected)
Test_MasterCount(NuArchive* pArchive, long expected)
{ {
NuError err; NuError err;
const NuMasterHeader* pMasterHeader; const NuMasterHeader* pMasterHeader;
@ -915,8 +930,8 @@ Test_MasterCount(NuArchive* pArchive, long expected)
goto failed; goto failed;
} }
if (pMasterHeader->mhTotalRecords != (ulong)expected) { if (pMasterHeader->mhTotalRecords != (uint32_t)expected) {
fprintf(stderr, "ERROR: unexpected MH count (%ld vs %ld)\n", fprintf(stderr, "ERROR: unexpected MH count (%u vs %ld)\n",
pMasterHeader->mhTotalRecords, expected); pMasterHeader->mhTotalRecords, expected);
goto failed; goto failed;
} }
@ -932,41 +947,21 @@ failed:
* *
* Returns 0 on success, -1 on error. * Returns 0 on success, -1 on error.
*/ */
int int DoTests(void)
DoTests(void)
{ {
NuError err; NuError err;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
long status; uint32_t status;
int cc, result = 0; int cc, result = 0;
char answer;
/* /*
* Make sure we're starting with a clean slate. * Make sure we're starting with a clean slate.
*/ */
if (access(kTestArchive, F_OK) == 0) { if (RemoveTestFile("Test archive", kTestArchive) < 0) {
printf("Test archive '%s' exists, remove (y/n)? ", kTestArchive); goto failed;
fflush(stdout);
answer = TGetReplyChar('n');
if (tolower(answer) != 'y')
goto failed;
cc = unlink(kTestArchive);
if (cc < 0) {
perror("unlink kTestArchive");
goto failed;
}
} }
if (access(kTestTempFile, F_OK) == 0) { if (RemoveTestFile("Test temp file", kTestTempFile) < 0) {
printf("Test temp file '%s' exists, remove (y/n)? ", kTestTempFile); goto failed;
fflush(stdout);
answer = TGetReplyChar('n');
if (tolower(answer) != 'y')
goto failed;
cc = unlink(kTestTempFile);
if (cc < 0) {
perror("unlink kTestTempFile");
goto failed;
}
} }
/* /*
@ -1013,7 +1008,7 @@ DoTests(void)
fprintf(stderr, "ERROR: mid NuClose failed (err=%d)\n", err); fprintf(stderr, "ERROR: mid NuClose failed (err=%d)\n", err);
goto failed; goto failed;
} }
pArchive = nil; pArchive = NULL;
err = NuOpenRO(kTestArchive, &pArchive); err = NuOpenRO(kTestArchive, &pArchive);
if (err != kNuErrNone) { if (err != kNuErrNone) {
@ -1028,14 +1023,14 @@ DoTests(void)
} }
/* /*
* Make sure the contents are still what we expect. * Make sure the TOC (i.e. list of files) is still what we expect.
*/ */
printf("... checking contents\n"); printf("... checking contents\n");
if (Test_Contents(pArchive) != 0) if (Test_Contents(pArchive) != 0)
goto failed; goto failed;
/* /*
* Verify the archive contents. * Verify the archive data.
*/ */
if (Test_Verify(pArchive) != 0) if (Test_Verify(pArchive) != 0)
goto failed; goto failed;
@ -1055,7 +1050,7 @@ DoTests(void)
fprintf(stderr, "ERROR: late NuClose failed (err=%d)\n", err); fprintf(stderr, "ERROR: late NuClose failed (err=%d)\n", err);
goto failed; goto failed;
} }
pArchive = nil; pArchive = NULL;
err = NuOpenRW(kTestArchive, kTestTempFile, 0, &pArchive); err = NuOpenRW(kTestArchive, kTestTempFile, 0, &pArchive);
if (err != kNuErrNone) { if (err != kNuErrNone) {
@ -1107,7 +1102,7 @@ DoTests(void)
*/ */
err = NuFlush(pArchive, &status); err = NuFlush(pArchive, &status);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: flush failed (err=%d, status=%ld)\n", fprintf(stderr, "ERROR: flush failed (err=%d, status=%d)\n",
err, status); err, status);
goto failed; goto failed;
} }
@ -1122,7 +1117,7 @@ DoTests(void)
* That's all, folks... * That's all, folks...
*/ */
NuClose(pArchive); NuClose(pArchive);
pArchive = nil; pArchive = NULL;
printf("... removing '%s'\n", kTestArchive); printf("... removing '%s'\n", kTestArchive);
cc = unlink(kTestArchive); cc = unlink(kTestArchive);
@ -1133,7 +1128,7 @@ DoTests(void)
leave: leave:
if (pArchive != nil) { if (pArchive != NULL) {
NuAbort(pArchive); NuAbort(pArchive);
NuClose(pArchive); NuClose(pArchive);
} }
@ -1148,16 +1143,15 @@ failed:
/* /*
* Crank away. * Crank away.
*/ */
int int main(void)
main(void)
{ {
long major, minor, bug; int32_t major, minor, bug;
const char* pBuildDate; const char* pBuildDate;
const char* pBuildFlags; const char* pBuildFlags;
int cc; int cc;
(void) NuGetVersion(&major, &minor, &bug, &pBuildDate, &pBuildFlags); (void) NuGetVersion(&major, &minor, &bug, &pBuildDate, &pBuildFlags);
printf("Using NuFX library v%ld.%ld.%ld, built on or after\n" printf("Using NuFX library v%d.%d.%d, built on or after\n"
" %s with [%s]\n\n", " %s with [%s]\n\n",
major, minor, bug, pBuildDate, pBuildFlags); major, minor, bug, pBuildDate, pBuildFlags);

View File

@ -37,7 +37,7 @@
* Track an archive record. * Track an archive record.
*/ */
typedef struct ArchiveRecord { typedef struct ArchiveRecord {
char* filename; char* filenameMOR;
NuRecordIdx recordIdx; NuRecordIdx recordIdx;
long numThreads; long numThreads;
@ -50,25 +50,24 @@ typedef struct ArchiveRecord {
/* /*
* Alloc a new ArchiveRecord. * Alloc a new ArchiveRecord.
*/ */
ArchiveRecord* ArchiveRecord* ArchiveRecord_New(const NuRecord* pRecord)
ArchiveRecord_New(const NuRecord* pRecord)
{ {
ArchiveRecord* pArcRec = nil; ArchiveRecord* pArcRec = NULL;
pArcRec = malloc(sizeof(*pArcRec)); pArcRec = malloc(sizeof(*pArcRec));
if (pArcRec == nil) if (pArcRec == NULL)
return nil; return NULL;
if (pRecord->filename == nil) if (pRecord->filenameMOR == NULL)
pArcRec->filename = strdup("<unknown>"); pArcRec->filenameMOR = strdup("<unknown>");
else else
pArcRec->filename = strdup((char*)pRecord->filename); pArcRec->filenameMOR = strdup(pRecord->filenameMOR);
pArcRec->recordIdx = pRecord->recordIdx; pArcRec->recordIdx = pRecord->recordIdx;
pArcRec->numThreads = NuRecordGetNumThreads(pRecord); pArcRec->numThreads = NuRecordGetNumThreads(pRecord);
(void) NuRecordCopyThreads(pRecord, &pArcRec->pThreads); (void) NuRecordCopyThreads(pRecord, &pArcRec->pThreads);
pArcRec->pNext = nil; pArcRec->pNext = NULL;
return pArcRec; return pArcRec;
} }
@ -76,15 +75,14 @@ ArchiveRecord_New(const NuRecord* pRecord)
/* /*
* Free up an ArchiveRecord. * Free up an ArchiveRecord.
*/ */
void void ArchiveRecord_Free(ArchiveRecord* pArcRec)
ArchiveRecord_Free(ArchiveRecord* pArcRec)
{ {
if (pArcRec == nil) if (pArcRec == NULL)
return; return;
if (pArcRec->filename != nil) if (pArcRec->filenameMOR != NULL)
free(pArcRec->filename); free(pArcRec->filenameMOR);
if (pArcRec->pThreads != nil) if (pArcRec->pThreads != NULL)
free(pArcRec->pThreads); free(pArcRec->pThreads);
free(pArcRec); free(pArcRec);
} }
@ -92,8 +90,8 @@ ArchiveRecord_Free(ArchiveRecord* pArcRec)
/* /*
* Find a thread with a matching NuThreadID. * Find a thread with a matching NuThreadID.
*/ */
const NuThread* const NuThread* ArchiveRecord_FindThreadByID(const ArchiveRecord* pArcRec,
ArchiveRecord_FindThreadByID(const ArchiveRecord* pArcRec, NuThreadID threadID) NuThreadID threadID)
{ {
const NuThread* pThread; const NuThread* pThread;
int i; int i;
@ -104,44 +102,38 @@ ArchiveRecord_FindThreadByID(const ArchiveRecord* pArcRec, NuThreadID threadID)
return pThread; return pThread;
} }
return nil; return NULL;
} }
const char* const char* ArchiveRecord_GetFilename(const ArchiveRecord* pArcRec)
ArchiveRecord_GetFilename(const ArchiveRecord* pArcRec)
{ {
return pArcRec->filename; return pArcRec->filenameMOR;
} }
NuRecordIdx NuRecordIdx ArchiveRecord_GetRecordIdx(const ArchiveRecord* pArcRec)
ArchiveRecord_GetRecordIdx(const ArchiveRecord* pArcRec)
{ {
return pArcRec->recordIdx; return pArcRec->recordIdx;
} }
long long ArchiveRecord_GetNumThreads(const ArchiveRecord* pArcRec)
ArchiveRecord_GetNumThreads(const ArchiveRecord* pArcRec)
{ {
return pArcRec->numThreads; return pArcRec->numThreads;
} }
const NuThread* const NuThread* ArchiveRecord_GetThread(const ArchiveRecord* pArcRec, int idx)
ArchiveRecord_GetThread(const ArchiveRecord* pArcRec, int idx)
{ {
if (idx < 0 || idx >= pArcRec->numThreads) if (idx < 0 || idx >= pArcRec->numThreads)
return nil; return NULL;
return NuThreadGetByIdx(pArcRec->pThreads, idx); return NuThreadGetByIdx(pArcRec->pThreads, idx);
} }
void void ArchiveRecord_SetNext(ArchiveRecord* pArcRec, ArchiveRecord* pNextRec)
ArchiveRecord_SetNext(ArchiveRecord* pArcRec, ArchiveRecord* pNextRec)
{ {
pArcRec->pNext = pNextRec; pArcRec->pNext = pNextRec;
} }
ArchiveRecord* ArchiveRecord* ArchiveRecord_GetNext(const ArchiveRecord* pArcRec)
ArchiveRecord_GetNext(const ArchiveRecord* pArcRec)
{ {
return pArcRec->pNext; return pArcRec->pNext;
} }
@ -163,31 +155,29 @@ typedef struct ArchiveData {
} ArchiveData; } ArchiveData;
ArchiveData* ArchiveData* ArchiveData_New(void)
ArchiveData_New(void)
{ {
ArchiveData* pArcData; ArchiveData* pArcData;
pArcData = malloc(sizeof(*pArcData)); pArcData = malloc(sizeof(*pArcData));
if (pArcData == nil) if (pArcData == NULL)
return nil; return NULL;
pArcData->numRecords = 0; pArcData->numRecords = 0;
pArcData->pRecordHead = pArcData->pRecordTail = nil; pArcData->pRecordHead = pArcData->pRecordTail = NULL;
return pArcData; return pArcData;
} }
void void ArchiveData_Free(ArchiveData* pArcData)
ArchiveData_Free(ArchiveData* pArcData)
{ {
ArchiveRecord* pNext; ArchiveRecord* pNext;
if (pArcData == nil) if (pArcData == NULL)
return; return;
printf("*** Deleting %ld records!\n", pArcData->numRecords); printf("*** Deleting %ld records!\n", pArcData->numRecords);
while (pArcData->pRecordHead != nil) { while (pArcData->pRecordHead != NULL) {
pNext = ArchiveRecord_GetNext(pArcData->pRecordHead); pNext = ArchiveRecord_GetNext(pArcData->pRecordHead);
ArchiveRecord_Free(pArcData->pRecordHead); ArchiveRecord_Free(pArcData->pRecordHead);
pArcData->pRecordHead = pNext; pArcData->pRecordHead = pNext;
@ -197,22 +187,20 @@ ArchiveData_Free(ArchiveData* pArcData)
} }
ArchiveRecord* ArchiveRecord* ArchiveData_GetRecordHead(const ArchiveData* pArcData)
ArchiveData_GetRecordHead(const ArchiveData* pArcData)
{ {
return pArcData->pRecordHead; return pArcData->pRecordHead;
} }
/* add an ArchiveRecord to the list pointed at by ArchiveData */ /* add an ArchiveRecord to the list pointed at by ArchiveData */
void void ArchiveData_AddRecord(ArchiveData* pArcData, ArchiveRecord* pRecord)
ArchiveData_AddRecord(ArchiveData* pArcData, ArchiveRecord* pRecord)
{ {
assert(pRecord != nil); assert(pRecord != NULL);
assert((pArcData->pRecordHead == nil && pArcData->pRecordTail == nil) || assert((pArcData->pRecordHead == NULL && pArcData->pRecordTail == NULL) ||
(pArcData->pRecordHead != nil && pArcData->pRecordTail != nil)); (pArcData->pRecordHead != NULL && pArcData->pRecordTail != NULL));
if (pArcData->pRecordHead == nil) { if (pArcData->pRecordHead == NULL) {
/* first */ /* first */
pArcData->pRecordHead = pArcData->pRecordTail = pRecord; pArcData->pRecordHead = pArcData->pRecordTail = pRecord;
} else { } else {
@ -225,24 +213,23 @@ ArchiveData_AddRecord(ArchiveData* pArcData, ArchiveRecord* pRecord)
} }
/* dump the contents of the ArchiveData to stdout */ /* dump the contents of the ArchiveData to stdout */
void void ArchiveData_DumpContents(const ArchiveData* pArcData)
ArchiveData_DumpContents(const ArchiveData* pArcData)
{ {
ArchiveRecord* pArcRec; ArchiveRecord* pArcRec;
pArcRec = pArcData->pRecordHead; pArcRec = pArcData->pRecordHead;
while (pArcRec != nil) { while (pArcRec != NULL) {
const NuThread* pThread; const NuThread* pThread;
int i, count; int i, count;
printf("%5ld '%s'\n", printf("%5u '%s'\n",
ArchiveRecord_GetRecordIdx(pArcRec), ArchiveRecord_GetRecordIdx(pArcRec),
ArchiveRecord_GetFilename(pArcRec)); ArchiveRecord_GetFilename(pArcRec));
count = ArchiveRecord_GetNumThreads(pArcRec); count = ArchiveRecord_GetNumThreads(pArcRec);
for (i = 0; i < count; i++) { for (i = 0; i < count; i++) {
pThread = ArchiveRecord_GetThread(pArcRec, i); pThread = ArchiveRecord_GetThread(pArcRec, i);
printf(" %5ld 0x%04x 0x%04x\n", pThread->threadIdx, printf(" %5u 0x%04x 0x%04x\n", pThread->threadIdx,
pThread->thThreadClass, pThread->thThreadKind); pThread->thThreadClass, pThread->thThreadKind);
} }
@ -260,18 +247,18 @@ ArchiveData_DumpContents(const ArchiveData* pArcData)
/* /*
* Callback function to collect archive information. * Callback function to collect archive information.
*/ */
NuResult NuResult GatherContents(NuArchive* pArchive, void* vpRecord)
GatherContents(NuArchive* pArchive, void* vpRecord)
{ {
NuRecord* pRecord = (NuRecord*) vpRecord; NuRecord* pRecord = (NuRecord*) vpRecord;
ArchiveData* pArchiveData = nil; ArchiveData* pArchiveData = NULL;
ArchiveRecord* pArchiveRecord = ArchiveRecord_New(pRecord); ArchiveRecord* pArchiveRecord = ArchiveRecord_New(pRecord);
NuGetExtraData(pArchive, (void**)&pArchiveData); NuGetExtraData(pArchive, (void**)&pArchiveData);
assert(pArchiveData != nil); assert(pArchiveData != NULL);
printf("*** Filename = '%s'\n", printf("*** Filename = '%s'\n",
pRecord->filename == nil ? "<unknown>":(const char*)pRecord->filename); pRecord->filenameMOR == NULL ?
"<unknown>" : pRecord->filenameMOR);
ArchiveData_AddRecord(pArchiveData, pArchiveRecord); ArchiveData_AddRecord(pArchiveData, pArchiveRecord);
@ -282,8 +269,7 @@ GatherContents(NuArchive* pArchive, void* vpRecord)
/* /*
* Copy the filename thread from every record to "pDataSink". * Copy the filename thread from every record to "pDataSink".
*/ */
NuError NuError ReadAllFilenameThreads(NuArchive* pArchive, ArchiveData* pArchiveData,
ReadAllFilenameThreads(NuArchive* pArchive, ArchiveData* pArchiveData,
NuDataSink* pDataSink) NuDataSink* pDataSink)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
@ -291,10 +277,10 @@ ReadAllFilenameThreads(NuArchive* pArchive, ArchiveData* pArchiveData,
const NuThread* pThread; const NuThread* pThread;
pArchiveRecord = ArchiveData_GetRecordHead(pArchiveData); pArchiveRecord = ArchiveData_GetRecordHead(pArchiveData);
while (pArchiveRecord != nil) { while (pArchiveRecord != NULL) {
pThread = ArchiveRecord_FindThreadByID(pArchiveRecord, pThread = ArchiveRecord_FindThreadByID(pArchiveRecord,
kNuThreadIDFilename); kNuThreadIDFilename);
if (pThread != nil) { if (pThread != NULL) {
err = NuExtractThread(pArchive, pThread->threadIdx, pDataSink); err = NuExtractThread(pArchive, pThread->threadIdx, pDataSink);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "*** Extract failed (%d)\n", err); fprintf(stderr, "*** Extract failed (%d)\n", err);
@ -310,11 +296,10 @@ bail:
/* extract every filename thread into a single file, overwriting each time */ /* extract every filename thread into a single file, overwriting each time */
NuError NuError ExtractToFile(NuArchive* pArchive, ArchiveData* pArchiveData)
ExtractToFile(NuArchive* pArchive, ArchiveData* pArchiveData)
{ {
NuError err; NuError err;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
err = NuCreateDataSinkForFile(true, kNuConvertOff, "out.file", PATH_SEP, err = NuCreateDataSinkForFile(true, kNuConvertOff, "out.file", PATH_SEP,
&pDataSink); &pDataSink);
@ -337,14 +322,13 @@ bail:
} }
/* extract every filename thread into a FILE*, appending */ /* extract every filename thread into a FILE*, appending */
NuError NuError ExtractToFP(NuArchive* pArchive, ArchiveData* pArchiveData)
ExtractToFP(NuArchive* pArchive, ArchiveData* pArchiveData)
{ {
NuError err; NuError err;
FILE* fp = nil; FILE* fp = NULL;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
if ((fp = fopen("out.fp", kNuFileOpenWriteTrunc)) == nil) if ((fp = fopen("out.fp", kNuFileOpenWriteTrunc)) == NULL)
return kNuErrFileOpen; return kNuErrFileOpen;
err = NuCreateDataSinkForFP(true, kNuConvertOff, fp, &pDataSink); err = NuCreateDataSinkForFP(true, kNuConvertOff, fp, &pDataSink);
@ -357,7 +341,7 @@ ExtractToFP(NuArchive* pArchive, ArchiveData* pArchiveData)
bail: bail:
(void) NuFreeDataSink(pDataSink); (void) NuFreeDataSink(pDataSink);
if (fp != nil) if (fp != NULL)
fclose(fp); fclose(fp);
if (err == kNuErrNone) if (err == kNuErrNone)
printf("*** FP write complete\n"); printf("*** FP write complete\n");
@ -365,13 +349,12 @@ bail:
} }
/* extract every filename thread into a buffer, advancing as we go */ /* extract every filename thread into a buffer, advancing as we go */
NuError NuError ExtractToBuffer(NuArchive* pArchive, ArchiveData* pArchiveData)
ExtractToBuffer(NuArchive* pArchive, ArchiveData* pArchiveData)
{ {
NuError err; NuError err;
unsigned char buffer[kHappySize]; uint8_t buffer[kHappySize];
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
unsigned long count; uint32_t count;
err = NuCreateDataSinkForBuffer(true, kNuConvertOff, buffer, kHappySize, err = NuCreateDataSinkForBuffer(true, kNuConvertOff, buffer, kHappySize,
&pDataSink); &pDataSink);
@ -389,9 +372,9 @@ ExtractToBuffer(NuArchive* pArchive, ArchiveData* pArchiveData)
(void) NuDataSinkGetOutCount(pDataSink, &count); (void) NuDataSinkGetOutCount(pDataSink, &count);
if (count > 0) { if (count > 0) {
FILE* fp; FILE* fp;
if ((fp = fopen("out.buf", kNuFileOpenWriteTrunc)) != nil) { if ((fp = fopen("out.buf", kNuFileOpenWriteTrunc)) != NULL) {
printf("*** Writing %ld bytes\n", count); printf("*** Writing %u bytes\n", count);
if (fwrite(buffer, count, 1, fp) != 1) if (fwrite(buffer, count, 1, fp) != 1)
err = kNuErrFileWrite; err = kNuErrFileWrite;
fclose(fp); fclose(fp);
@ -409,14 +392,13 @@ bail:
/* /*
* Do file stuff. * Do file stuff.
*/ */
int int DoFileStuff(const UNICHAR* filenameUNI)
DoFileStuff(const char* filename)
{ {
NuError err; NuError err;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
ArchiveData* pArchiveData = ArchiveData_New(); ArchiveData* pArchiveData = ArchiveData_New();
err = NuOpenRO(filename, &pArchive); err = NuOpenRO(filenameUNI, &pArchive);
if (err != kNuErrNone) if (err != kNuErrNone)
goto bail; goto bail;
@ -444,7 +426,7 @@ bail:
if (err != kNuErrNone) if (err != kNuErrNone)
fprintf(stderr, "*** ERROR: got error %d\n", err); fprintf(stderr, "*** ERROR: got error %d\n", err);
if (pArchive != nil) { if (pArchive != NULL) {
NuError err2 = NuClose(pArchive); NuError err2 = NuClose(pArchive);
if (err == kNuErrNone && err2 != kNuErrNone) if (err == kNuErrNone && err2 != kNuErrNone)
err = err2; err = err2;
@ -459,21 +441,20 @@ bail:
/* /*
* Grab the name of an archive to read. If no name was provided, use stdin. * Grab the name of an archive to read. If no name was provided, use stdin.
*/ */
int int main(int argc, char** argv)
main(int argc, char** argv)
{ {
long major, minor, bug; int32_t major, minor, bug;
const char* pBuildDate; const char* pBuildDate;
FILE* infp = nil; FILE* infp = NULL;
int cc; int cc;
(void) NuGetVersion(&major, &minor, &bug, &pBuildDate, nil); (void) NuGetVersion(&major, &minor, &bug, &pBuildDate, NULL);
printf("Using NuFX lib %ld.%ld.%ld built on or after %s\n", printf("Using NuFX lib %d.%d.%d built on or after %s\n",
major, minor, bug, pBuildDate); major, minor, bug, pBuildDate);
if (argc == 2) { if (argc == 2) {
infp = fopen(argv[1], kNuFileOpenReadOnly); infp = fopen(argv[1], kNuFileOpenReadOnly);
if (infp == nil) { if (infp == NULL) {
perror("fopen failed"); perror("fopen failed");
exit(1); exit(1);
} }
@ -484,7 +465,7 @@ main(int argc, char** argv)
cc = DoFileStuff(argv[1]); cc = DoFileStuff(argv[1]);
if (infp != nil) if (infp != NULL)
fclose(infp); fclose(infp);
exit(cc != 0); exit(cc != 0);

580
nufxlib/samples/TestNames.c Normal file
View File

@ -0,0 +1,580 @@
/*
* NuFX archive manipulation library
* Copyright (C) 2000-2007 by Andy McFadden, All Rights Reserved.
* This is free software; you can redistribute it and/or modify it under the
* terms of the BSD License, see the file COPYING.LIB.
*
* Test local and storage names with Unicode and Mac OS Roman content.
*
* On Windows, opening files with fancy filenames requires UTF-16 and
* special functions. On Linux and Mac OS X we're just writing UTF-8 data,
* so they don't really need to do anything special other than be 8-bit
* clean. NufxLib functions take UTF-8 strings, so on Windows we define
* everything in UTF-16 and convert to UTF-8. (We need the UTF-16 form so
* we can use "wide" I/O functions to confirm that the file was created
* with the correct name.)
*
* To see files with the correct appearance with "ls", you may need to
* do something like:
*
* % LC_ALL=en_US.UTF-8 ls
*
* (Many users set LC_ALL=POSIX to avoid GNU grep slowdowns and altered
* sort ordering in ls.)
*/
#include <stdio.h>
#include <ctype.h>
#include "NufxLib.h"
#include "Common.h"
/*
* Test filenames.
*
* The local filename (kTestArchive) contains non-MOR Unicode values
* (two Japanese characters that Google Translate claims form the verb
* "shrink"). The temp file name is similar.
*
* The entry name uses a mix of simple ASCII, CP1252 MOR, and
* non-CP1252 MOR characters: fl ligature, double dagger, copyright symbol,
* Apple logo (the latter of which doesn't have a glyph on Windows or Linux).
* All of the characters have MOR translations.
*/
#ifdef USE_UTF16
const UNICHAR kTestArchive[] = L"nlTest\u7e2e\u3080.shk";
const UNICHAR kTestEntryName[] = L"nl-test\u2013\ufb01_\u2021_\u00a9\uf8ff!";
const UNICHAR kTestTempFile[] = L"nlTest\4e00\u6642\u30d5\u30a1\u30a4\u30eb.tmp";
#else
const UNICHAR kTestArchive[] = "nlTest\xe7\xb8\xae\xe3\x82\x80.shk";
const UNICHAR kTestEntryName[] = "nl-test\xe2\x80\x93\xef\xac\x81_\xe2\x80\xa1_"
"\xc2\xa9\xef\xa3\xbf!";
const UNICHAR kTestTempFile[] = "nlTest\xe4\xb8\x80\xe6\x99\x82\xe3\x83\x95"
"\xe3\x82\xa1\xe3\x82\xa4\xe3\x83\xab.tmp";
#endif
const UNICHAR kLocalFssep = '|';
/*
* ===========================================================================
* Helper functions
* ===========================================================================
*/
/*
* Get a single character of input from the user.
*/
static char TGetReplyChar(char defaultReply)
{
char tmpBuf[32];
if (fgets(tmpBuf, sizeof(tmpBuf), stdin) == NULL)
return defaultReply;
if (tmpBuf[0] == '\n' || tmpBuf[0] == '\r')
return defaultReply;
return tmpBuf[0];
}
NuError AddSimpleRecord(NuArchive* pArchive, const char* fileNameMOR,
NuRecordIdx* pRecordIdx)
{
NuFileDetails fileDetails;
memset(&fileDetails, 0, sizeof(fileDetails));
fileDetails.storageNameMOR = fileNameMOR;
fileDetails.fileSysInfo = kLocalFssep;
fileDetails.access = kNuAccessUnlocked;
return NuAddRecord(pArchive, &fileDetails, pRecordIdx);
}
/*
* Display error messages... or not.
*/
NuResult ErrorMessageHandler(NuArchive* pArchive, void* vErrorMessage)
{
const NuErrorMessage* pErrorMessage = (const NuErrorMessage*) vErrorMessage;
//if (gSuppressError)
// return kNuOK;
if (pErrorMessage->isDebug) {
fprintf(stderr, "%sNufxLib says: [%s:%d %s] %s\n",
pArchive == NULL ? "GLOBAL>" : "",
pErrorMessage->file, pErrorMessage->line, pErrorMessage->function,
pErrorMessage->message);
} else {
fprintf(stderr, "%sNufxLib says: %s\n",
pArchive == NULL ? "GLOBAL>" : "",
pErrorMessage->message);
}
return kNuOK;
}
#ifdef USE_UTF16
TODO - use _waccess, _wunlink, etc.
#else
int RemoveTestFile(const char* title, const char* fileName)
{
char answer;
if (access(fileName, F_OK) == 0) {
printf("%s '%s' exists, remove (y/n)? ", title, fileName);
fflush(stdout);
answer = TGetReplyChar('n');
if (tolower(answer) != 'y')
return -1;
if (unlink(fileName) < 0) {
perror("unlink");
return -1;
}
}
return 0;
}
#endif
/*
* Utility function that wraps NuConvertUNIToMOR, allocating a new
* buffer to hold the converted string. The caller must free the result.
*/
char* CopyUNIToMOR(const UNICHAR* stringUNI)
{
size_t morLen;
char* morBuf;
morLen = NuConvertUNIToMOR(stringUNI, NULL, 0);
if (morLen == (size_t) -1) {
return NULL;
}
morBuf = (char*) malloc(morLen);
(void) NuConvertUNIToMOR(stringUNI, morBuf, morLen);
return morBuf;
}
/*
* Utility function that wraps NuConvertMORToUNI, allocating a new
* buffer to hold the converted string. The caller must free the result.
*/
UNICHAR* CopyMORToUNI(const char* stringMOR)
{
size_t uniLen;
char* uniBuf;
uniLen = NuConvertMORToUNI(stringMOR, NULL, 0);
if (uniLen == (size_t) -1) {
return NULL;
}
uniBuf = (UNICHAR*) malloc(uniLen);
(void) NuConvertMORToUNI(stringMOR, uniBuf, uniLen);
return uniBuf;
}
/*
* ===========================================================================
* Tests
* ===========================================================================
*/
void DumpMorString(const char* str)
{
printf("(%d) ", (int) strlen(str));
while (*str != '\0') {
if (*str >= 0x20 && *str < 0x7f) {
putchar(*str);
} else {
printf("\\x%02x", (uint8_t) *str);
}
str++;
}
putchar('\n');
}
void DumpUnicharString(const UNICHAR* str)
{
printf("(%d) ", (int) strlen(str));
while (*str != '\0') {
if (*str >= 0x20 && *str < 0x7f) {
putchar(*str);
} else {
if (sizeof(UNICHAR) == 1) {
printf("\\x%02x", (uint8_t) *str);
} else {
printf("\\u%04x", (uint16_t) *str);
}
}
str++;
}
putchar('\n');
}
/*
* Some basic string conversion unit tests.
*
* TODO: test with short buffer, make sure we don't get partial code
* points when converting to Unicode
*/
int TestStringConversion(void)
{
static const char kMORTest[] = "test\xe0\xe9\xed\xf3\xfa#\xf0\xb0";
size_t outLen;
char morBuf[512];
UNICHAR uniBuf[512];
// convert test string to Unicode
memset(uniBuf, 0xcc, sizeof(uniBuf));
//printf("MOR: "); DumpMorString(kMORTest);
outLen = NuConvertMORToUNI(kMORTest, NULL, 0);
//printf("outLen is %u\n", (unsigned int) outLen);
if (NuConvertMORToUNI(kMORTest, uniBuf, sizeof(uniBuf)) != outLen) {
fprintf(stderr, "Inconsistent MORToUNI len\n");
return -1;
}
//printf("UNI: "); DumpUnicharString(uniBuf);
if (strlen(uniBuf) + 1 != outLen) {
fprintf(stderr, "Expected length != actual length\n");
return -1;
}
// convert Unicode back to MOR
memset(morBuf, 0xcc, sizeof(morBuf));
outLen = NuConvertUNIToMOR(uniBuf, NULL, 0);
//printf("outLen is %u\n", (unsigned int) outLen);
if (NuConvertUNIToMOR(uniBuf, morBuf, sizeof(morBuf)) != outLen) {
fprintf(stderr, "Inconsistent UNIToMOR len\n");
return -1;
}
//printf("MOR: "); DumpMorString(morBuf);
if (strlen(morBuf) + 1 != outLen) {
fprintf(stderr, "Expected length != actual length\n");
return -1;
}
// check vs. original
if (strcmp(kMORTest, morBuf) != 0) {
fprintf(stderr, "Test string corrupted by double conversion\n");
return -1;
}
#ifdef USE_UTF16
static const UNICHAR kNonMorUniStr[] = L"nlTest\u7e2e\u3080.shk";
static const UNICHAR kBadUniStr[] = L"nlTest\u7e2e\x30";
#else
static const UNICHAR kNonMorUniStr[] = "nlTest\xe7\xb8\xae\xe3\x82\x80.shk";
static const UNICHAR kBadUniStr[] = "nlTest\x81\xe7";
#endif
static const char kNonMorExpected[] = "nlTest??.shk";
static const char kBadExpected[] = "nlTest??";
NuConvertUNIToMOR(kNonMorUniStr, morBuf, sizeof(morBuf));
if (strcmp(morBuf, kNonMorExpected) != 0) {
fprintf(stderr, "Non-MOR string conversion failed\n");
return -1;
}
NuConvertUNIToMOR(kBadUniStr, morBuf, sizeof(morBuf));
if (strcmp(morBuf, kBadExpected) != 0) {
fprintf(stderr, "Bad UNI string conversion failed\n");
return -1;
}
printf("... string conversion tests successful\n");
return 0;
}
/*
* Create a new entry and give it a trivial data fork.
*/
int AddTestEntry(NuArchive* pArchive, const char* entryNameMOR)
{
NuDataSource* pDataSource = NULL;
NuRecordIdx recordIdx;
static const char* kTestMsg = "Hello, world!\n";
uint32_t status;
NuError err;
/*
* Add our test entry.
*/
err = AddSimpleRecord(pArchive, entryNameMOR, &recordIdx);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: add record failed (err=%d)\n", err);
goto failed;
}
err = NuCreateDataSourceForBuffer(kNuThreadFormatUncompressed,
0, (const uint8_t*)kTestMsg, 0, strlen(kTestMsg), NULL,
&pDataSource);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: source create failed (err=%d)\n", err);
goto failed;
}
err = NuAddThread(pArchive, recordIdx, kNuThreadIDDataFork, pDataSource,
NULL);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: thread add failed (err=%d)\n", err);
goto failed;
}
pDataSource = NULL; /* now owned by library */
/*
* Flush changes.
*/
err = NuFlush(pArchive, &status);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't flush after add (err=%d, status=%u)\n",
err, status);
goto failed;
}
return 0;
failed:
if (pDataSource != NULL)
NuFreeDataSource(pDataSource);
return -1;
}
/*
* Extract the file we created.
*/
int TestExtract(NuArchive* pArchive, const char* entryNameMOR)
{
const NuRecord* pRecord;
NuRecordIdx recordIdx;
NuError err;
err = NuGetRecordIdxByName(pArchive, entryNameMOR, &recordIdx);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't find '%s' (err=%d)\n",
entryNameMOR, err);
return -1;
}
err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: couldn't get record index %u (err=%d)\n",
recordIdx, err);
return -1;
}
assert(pRecord != NULL);
const NuThread* pThread = NULL;
uint32_t idx;
for (idx = 0; idx < NuRecordGetNumThreads(pRecord); idx++) {
pThread = NuGetThread(pRecord, idx);
if (NuGetThreadID(pThread) == kNuThreadIDDataFork)
break;
}
if (pThread == NULL) {
fprintf(stderr, "ERROR: no data thread?\n");
return -1;
}
/*
* Prepare the output file.
*/
UNICHAR* entryNameUNI = CopyMORToUNI(entryNameMOR);
NuDataSink* pDataSink = NULL;
err = NuCreateDataSinkForFile(true, kNuConvertOff, entryNameUNI,
kLocalFssep, &pDataSink);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to create data sink for file (err=%d)\n",
err);
free(entryNameUNI);
return -1;
}
err = NuExtractThread(pArchive, pThread->threadIdx, pDataSink);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: extract failed (err=%d)\n", err);
(void) NuFreeDataSink(pDataSink);
free(entryNameUNI);
return -1;
}
(void) NuFreeDataSink(pDataSink);
printf("... confirming extraction of '%s'\n", entryNameUNI);
if (access(entryNameUNI, F_OK) != 0) {
fprintf(stderr, "ERROR: unable to read '%s' (err=%d)\n",
entryNameUNI, errno);
free(entryNameUNI);
return -1;
}
if (unlink(entryNameUNI) < 0) {
perror("unlink test entry");
free(entryNameUNI);
return -1;
}
free(entryNameUNI);
return 0;
}
/*
* Run some tests.
*
* Returns 0 on success, -1 on error.
*/
int DoTests(void)
{
NuError err;
NuArchive* pArchive = NULL;
char* testEntryNameMOR = NULL;
int result = 0;
if (TestStringConversion() < 0) {
goto failed;
}
/*
* Make sure we're starting with a clean slate.
*/
if (RemoveTestFile("Test archive", kTestArchive) < 0) {
goto failed;
}
if (RemoveTestFile("Test temp file", kTestTempFile) < 0) {
goto failed;
}
if (RemoveTestFile("Test entry", kTestEntryName) < 0) {
goto failed;
}
testEntryNameMOR = CopyUNIToMOR(kTestEntryName);
/*
* Create a new archive to play with.
*/
err = NuOpenRW(kTestArchive, kTestTempFile, kNuOpenCreat|kNuOpenExcl,
&pArchive);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: NuOpenRW failed (err=%d)\n", err);
goto failed;
}
if (NuSetErrorMessageHandler(pArchive, ErrorMessageHandler) ==
kNuInvalidCallback)
{
fprintf(stderr, "ERROR: couldn't set message handler\n");
goto failed;
}
/*
* Add a single entry.
*/
if (AddTestEntry(pArchive, testEntryNameMOR) != 0) {
goto failed;
}
printf("... checking presence of '%s' and '%s'\n",
kTestArchive, kTestTempFile);
if (access(kTestTempFile, F_OK) != 0) {
/* in theory, NufxLib doesn't need to use the temp file we provide,
so this test isn't entirely sound */
fprintf(stderr, "ERROR: did not find %s (err=%d)\n",
kTestTempFile, err);
goto failed;
}
/*
* Close it and confirm that the file has the expected name.
*/
err = NuClose(pArchive);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: mid NuClose failed (err=%d)\n", err);
goto failed;
}
pArchive = NULL;
if (access(kTestArchive, F_OK) != 0) {
fprintf(stderr, "ERROR: did not find %s (err=%d)\n", kTestArchive, err);
goto failed;
}
/*
* Reopen it read-only.
*/
printf("... reopening archive read-only\n");
err = NuOpenRO(kTestArchive, &pArchive);
if (err != kNuErrNone) {
fprintf(stderr, "ERROR: NuOpenRO failed (err=%d)\n", err);
goto failed;
}
if (NuSetErrorMessageHandler(pArchive, ErrorMessageHandler) ==
kNuInvalidCallback)
{
fprintf(stderr, "ERROR: couldn't set message handler\n");
goto failed;
}
/*
* Extract the file.
*/
if (TestExtract(pArchive, testEntryNameMOR) < 0) {
goto failed;
}
/*
* That's all, folks...
*/
NuClose(pArchive);
pArchive = NULL;
printf("... removing '%s'\n", kTestArchive);
if (unlink(kTestArchive) < 0) {
perror("unlink kTestArchive");
goto failed;
}
leave:
if (pArchive != NULL) {
NuAbort(pArchive);
NuClose(pArchive);
}
free(testEntryNameMOR);
return result;
failed:
result = -1;
goto leave;
}
/*
* Start here.
*/
int main(void)
{
int32_t major, minor, bug;
const char* pBuildDate;
const char* pBuildFlags;
int cc;
(void) NuGetVersion(&major, &minor, &bug, &pBuildDate, &pBuildFlags);
printf("Using NuFX library v%d.%d.%d, built on or after\n"
" %s with [%s]\n\n",
major, minor, bug, pBuildDate, pBuildFlags);
if (NuSetGlobalErrorMessageHandler(ErrorMessageHandler) ==
kNuInvalidCallback)
{
fprintf(stderr, "ERROR: can't set the global message handler");
exit(1);
}
printf("... starting tests\n");
cc = DoTests();
printf("... tests ended, %s\n", cc == 0 ? "SUCCESS" : "FAILURE");
exit(cc != 0);
}

View File

@ -21,12 +21,20 @@
* header, a filename thread, or a default value ("UNKNOWN", stuffed in * header, a filename thread, or a default value ("UNKNOWN", stuffed in
* when a record has no filename at all). * when a record has no filename at all).
*/ */
NuResult NuResult ShowContents(NuArchive* pArchive, void* vpRecord)
ShowContents(NuArchive* pArchive, void* vpRecord)
{ {
const NuRecord* pRecord = (NuRecord*) vpRecord; const NuRecord* pRecord = (NuRecord*) vpRecord;
printf("*** Filename = '%s'\n", pRecord->filename); size_t bufLen = NuConvertMORToUNI(pRecord->filenameMOR, NULL, 0);
if (bufLen == (size_t) -1) {
fprintf(stderr, "GLITCH: unable to convert '%s'\n",
pRecord->filenameMOR);
} else {
UNICHAR* buf = (UNICHAR*) malloc(bufLen);
NuConvertMORToUNI(pRecord->filenameMOR, buf, bufLen);
printf("*** Filename = '%s'\n", buf);
free(buf);
}
return kNuOK; return kNuOK;
} }
@ -38,11 +46,10 @@ ShowContents(NuArchive* pArchive, void* vpRecord)
* If we're not interested in handling an archive on stdin, we could just * If we're not interested in handling an archive on stdin, we could just
* pass the filename in here and use NuOpenRO instead. * pass the filename in here and use NuOpenRO instead.
*/ */
int int DoStreamStuff(FILE* fp)
DoStreamStuff(FILE* fp)
{ {
NuError err; NuError err;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
err = NuStreamOpenRO(fp, &pArchive); err = NuStreamOpenRO(fp, &pArchive);
if (err != kNuErrNone) { if (err != kNuErrNone) {
@ -59,7 +66,7 @@ DoStreamStuff(FILE* fp)
} }
bail: bail:
if (pArchive != nil) { if (pArchive != NULL) {
NuError err2 = NuClose(pArchive); NuError err2 = NuClose(pArchive);
if (err == kNuErrNone) if (err == kNuErrNone)
err = err2; err = err2;
@ -72,16 +79,15 @@ bail:
/* /*
* Grab the name of an archive to read. If "-" was given, use stdin. * Grab the name of an archive to read. If "-" was given, use stdin.
*/ */
int int main(int argc, char** argv)
main(int argc, char** argv)
{ {
long major, minor, bug; int32_t major, minor, bug;
const char* pBuildDate; const char* pBuildDate;
FILE* infp = nil; FILE* infp = NULL;
int cc; int cc;
(void) NuGetVersion(&major, &minor, &bug, &pBuildDate, nil); (void) NuGetVersion(&major, &minor, &bug, &pBuildDate, NULL);
printf("Using NuFX lib %ld.%ld.%ld built on or after %s\n", printf("Using NuFX lib %d.%d.%d built on or after %s\n",
major, minor, bug, pBuildDate); major, minor, bug, pBuildDate);
if (argc != 2) { if (argc != 2) {
@ -93,7 +99,7 @@ main(int argc, char** argv)
infp = stdin; infp = stdin;
else { else {
infp = fopen(argv[1], kNuFileOpenReadOnly); infp = fopen(argv[1], kNuFileOpenReadOnly);
if (infp == nil) { if (infp == NULL) {
fprintf(stderr, "ERROR: unable to open '%s'\n", argv[1]); fprintf(stderr, "ERROR: unable to open '%s'\n", argv[1]);
exit(1); exit(1);
} }

View File

@ -29,16 +29,15 @@ const int kMaxHeldLen = 1024 * 1024;
* A list of CRCs. * A list of CRCs.
*/ */
typedef struct CRCList { typedef struct CRCList {
int numEntries; int numEntries;
unsigned short* entries; uint16_t* entries;
} CRCList; } CRCList;
/* /*
* Returns true if the compression type is supported, false otherwise. * Returns true if the compression type is supported, false otherwise.
*/ */
int int CompressionSupported(NuValue compression)
CompressionSupported(NuValue compression)
{ {
int result; int result;
@ -76,8 +75,7 @@ CompressionSupported(NuValue compression)
/* /*
* This gets called when a buffer DataSource is no longer needed. * This gets called when a buffer DataSource is no longer needed.
*/ */
NuResult NuResult FreeCallback(NuArchive* pArchive, void* args)
FreeCallback(NuArchive* pArchive, void* args)
{ {
free(args); free(args);
return kNuOK; return kNuOK;
@ -87,8 +85,7 @@ FreeCallback(NuArchive* pArchive, void* args)
/* /*
* Dump a CRC list. * Dump a CRC list.
*/ */
void void DumpCRCs(const CRCList* pCRCList)
DumpCRCs(const CRCList* pCRCList)
{ {
int i; int i;
@ -101,10 +98,9 @@ DumpCRCs(const CRCList* pCRCList)
/* /*
* Free a CRC list. * Free a CRC list.
*/ */
void void FreeCRCs(CRCList* pCRCList)
FreeCRCs(CRCList* pCRCList)
{ {
if (pCRCList == nil) if (pCRCList == NULL)
return; return;
free(pCRCList->entries); free(pCRCList->entries);
@ -117,21 +113,20 @@ FreeCRCs(CRCList* pCRCList)
* We assume there are at most two data threads (e.g. data fork and rsrc * We assume there are at most two data threads (e.g. data fork and rsrc
* fork) in a record. * fork) in a record.
* *
* Returns the list on success, nil on failure. * Returns the list on success, NULL on failure.
*/ */
CRCList* CRCList* GatherCRCs(NuArchive* pArchive)
GatherCRCs(NuArchive* pArchive)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
const NuMasterHeader* pMasterHeader; const NuMasterHeader* pMasterHeader;
CRCList* pCRCList = nil; CRCList* pCRCList = NULL;
unsigned short* pEntries = nil; uint16_t* pEntries = NULL;
long recCount, maxCRCs; long recCount, maxCRCs;
long recIdx, crcIdx; long recIdx, crcIdx;
int i; int i;
pCRCList = malloc(sizeof(*pCRCList)); pCRCList = malloc(sizeof(*pCRCList));
if (pCRCList == nil) { if (pCRCList == NULL) {
fprintf(stderr, "ERROR: couldn't alloc CRC list\n"); fprintf(stderr, "ERROR: couldn't alloc CRC list\n");
err = kNuErrGeneric; err = kNuErrGeneric;
goto bail; goto bail;
@ -148,7 +143,7 @@ GatherCRCs(NuArchive* pArchive)
maxCRCs = recCount * 2; maxCRCs = recCount * 2;
pEntries = malloc(sizeof(*pEntries) * maxCRCs); pEntries = malloc(sizeof(*pEntries) * maxCRCs);
if (pEntries == nil) { if (pEntries == NULL) {
fprintf(stderr, "ERROR: unable to alloc CRC list (%ld entries)\n", fprintf(stderr, "ERROR: unable to alloc CRC list (%ld entries)\n",
maxCRCs); maxCRCs);
err = kNuErrGeneric; err = kNuErrGeneric;
@ -178,12 +173,12 @@ GatherCRCs(NuArchive* pArchive)
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to get recordIdx %ld\n", recordIdx); fprintf(stderr, "ERROR: unable to get recordIdx %u\n", recordIdx);
goto bail; goto bail;
} }
if (NuRecordGetNumThreads(pRecord) == 0) { if (NuRecordGetNumThreads(pRecord) == 0) {
fprintf(stderr, "ERROR: not expecting empty record (%ld)!\n", fprintf(stderr, "ERROR: not expecting empty record (%u)!\n",
recordIdx); recordIdx);
err = kNuErrGeneric; err = kNuErrGeneric;
goto bail; goto bail;
@ -211,7 +206,7 @@ GatherCRCs(NuArchive* pArchive)
bail: bail:
if (err != kNuErrNone) { if (err != kNuErrNone) {
FreeCRCs(pCRCList); FreeCRCs(pCRCList);
pCRCList = nil; pCRCList = NULL;
} }
return pCRCList; return pCRCList;
} }
@ -228,16 +223,15 @@ bail:
* *
* Returns 0 on success, nonzero on failure. * Returns 0 on success, nonzero on failure.
*/ */
int int CompareCRCs(NuArchive* pArchive, const CRCList* pOldCRCList)
CompareCRCs(NuArchive* pArchive, const CRCList* pOldCRCList)
{ {
CRCList* pNewCRCList = nil; CRCList* pNewCRCList = NULL;
int result = -1; int result = -1;
int badCrc = 0; int badCrc = 0;
int i; int i;
pNewCRCList = GatherCRCs(pArchive); pNewCRCList = GatherCRCs(pArchive);
if (pNewCRCList == nil) { if (pNewCRCList == NULL) {
fprintf(stderr, "ERROR: unable to gather new list\n"); fprintf(stderr, "ERROR: unable to gather new list\n");
goto bail; goto bail;
} }
@ -274,18 +268,17 @@ bail:
* *
* All of this good stuff gets queued up until the next NuFlush call. * All of this good stuff gets queued up until the next NuFlush call.
*/ */
NuError NuError RecompressThread(NuArchive* pArchive, const NuRecord* pRecord,
RecompressThread(NuArchive* pArchive, const NuRecord* pRecord,
const NuThread* pThread) const NuThread* pThread)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuDataSource* pDataSource = nil; NuDataSource* pDataSource = NULL;
NuDataSink* pDataSink = nil; NuDataSink* pDataSink = NULL;
unsigned char* buf = nil; uint8_t* buf = NULL;
if (pThread->actualThreadEOF == 0) { if (pThread->actualThreadEOF == 0) {
buf = malloc(1); buf = malloc(1);
if (buf == nil) { if (buf == NULL) {
fprintf(stderr, "ERROR: failed allocating trivial buffer\n"); fprintf(stderr, "ERROR: failed allocating trivial buffer\n");
err = kNuErrGeneric; err = kNuErrGeneric;
goto bail; goto bail;
@ -295,8 +288,8 @@ RecompressThread(NuArchive* pArchive, const NuRecord* pRecord,
* Create a buffer and data sink to hold the data. * Create a buffer and data sink to hold the data.
*/ */
buf = malloc(pThread->actualThreadEOF); buf = malloc(pThread->actualThreadEOF);
if (buf == nil) { if (buf == NULL) {
fprintf(stderr, "ERROR: failed allocating %ld bytes\n", fprintf(stderr, "ERROR: failed allocating %u bytes\n",
pThread->actualThreadEOF); pThread->actualThreadEOF);
err = kNuErrGeneric; err = kNuErrGeneric;
goto bail; goto bail;
@ -314,8 +307,8 @@ RecompressThread(NuArchive* pArchive, const NuRecord* pRecord,
*/ */
err = NuExtractThread(pArchive, pThread->threadIdx, pDataSink); err = NuExtractThread(pArchive, pThread->threadIdx, pDataSink);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: failed extracting thread %ld in '%s': %s\n", fprintf(stderr, "ERROR: failed extracting thread %u in '%s': %s\n",
pThread->threadIdx, pRecord->filename, NuStrError(err)); pThread->threadIdx, pRecord->filenameMOR, NuStrError(err));
goto bail; goto bail;
} }
} }
@ -325,7 +318,7 @@ RecompressThread(NuArchive* pArchive, const NuRecord* pRecord,
*/ */
err = NuDeleteThread(pArchive, pThread->threadIdx); err = NuDeleteThread(pArchive, pThread->threadIdx);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to delete thread %ld\n", fprintf(stderr, "ERROR: unable to delete thread %u\n",
pThread->threadIdx); pThread->threadIdx);
goto bail; goto bail;
} }
@ -340,19 +333,19 @@ RecompressThread(NuArchive* pArchive, const NuRecord* pRecord,
fprintf(stderr, "ERROR: unable to create data source (err=%d)\n", err); fprintf(stderr, "ERROR: unable to create data source (err=%d)\n", err);
goto bail; goto bail;
} }
buf = nil; buf = NULL;
/* /*
* Create replacement thread. * Create replacement thread.
*/ */
err = NuAddThread(pArchive, pRecord->recordIdx, NuGetThreadID(pThread), err = NuAddThread(pArchive, pRecord->recordIdx, NuGetThreadID(pThread),
pDataSource, nil); pDataSource, NULL);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to add new thread ID=0x%08lx (err=%d)\n", fprintf(stderr, "ERROR: unable to add new thread ID=0x%08x (err=%d)\n",
NuGetThreadID(pThread), err); NuGetThreadID(pThread), err);
goto bail; goto bail;
} }
pDataSource = nil; /* now owned by NufxLib */ pDataSource = NULL; /* now owned by NufxLib */
bail: bail:
NuFreeDataSink(pDataSink); NuFreeDataSink(pDataSink);
@ -367,21 +360,20 @@ bail:
* The amount of data we're holding in memory as a result of the * The amount of data we're holding in memory as a result of the
* recompression is placed in "*pLen". * recompression is placed in "*pLen".
*/ */
NuError NuError RecompressRecord(NuArchive* pArchive, NuRecordIdx recordIdx, long* pLen)
RecompressRecord(NuArchive* pArchive, NuRecordIdx recordIdx, long* pLen)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
const NuRecord* pRecord; const NuRecord* pRecord;
const NuThread* pThread; const NuThread* pThread;
int i; int i;
printf(" Recompressing %ld\n", recordIdx); printf(" Recompressing %u\n", recordIdx);
*pLen = 0; *pLen = 0;
err = NuGetRecord(pArchive, recordIdx, &pRecord); err = NuGetRecord(pArchive, recordIdx, &pRecord);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to get record %ld (err=%d)\n", fprintf(stderr, "ERROR: unable to get record %u (err=%d)\n",
recordIdx, err); recordIdx, err);
goto bail; goto bail;
} }
@ -393,8 +385,8 @@ RecompressRecord(NuArchive* pArchive, NuRecordIdx recordIdx, long* pLen)
NuGetThreadID(pThread));*/ NuGetThreadID(pThread));*/
err = RecompressThread(pArchive, pRecord, pThread); err = RecompressThread(pArchive, pRecord, pThread);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: failed recompressing thread %ld " fprintf(stderr, "ERROR: failed recompressing thread %u "
" in record %ld (err=%d)\n", " in record %u (err=%d)\n",
pThread->threadIdx, pRecord->recordIdx, err); pThread->threadIdx, pRecord->recordIdx, err);
goto bail; goto bail;
} }
@ -412,23 +404,22 @@ bail:
/* /*
* Recompress every data thread in the archive. * Recompress every data thread in the archive.
*/ */
NuError NuError RecompressArchive(NuArchive* pArchive, NuValue compression)
RecompressArchive(NuArchive* pArchive, NuValue compression)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuRecordIdx* pIndices = nil; NuRecordIdx* pIndices = NULL;
NuAttr countAttr; NuAttr countAttr;
long heldLen; long heldLen;
long idx; long idx;
err = NuSetValue(pArchive, kNuValueDataCompression, compression); err = NuSetValue(pArchive, kNuValueDataCompression, compression);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: unable to set compression to %ld (err=%d)\n", fprintf(stderr, "ERROR: unable to set compression to %u (err=%d)\n",
compression, err); compression, err);
goto bail; goto bail;
} }
printf("Recompressing threads with compression type %ld\n", compression); printf("Recompressing threads with compression type %u\n", compression);
err = NuGetAttr(pArchive, kNuAttrNumRecords, &countAttr); err = NuGetAttr(pArchive, kNuAttrNumRecords, &countAttr);
if (err != kNuErrNone) { if (err != kNuErrNone) {
@ -446,8 +437,8 @@ RecompressArchive(NuArchive* pArchive, NuValue compression)
* record to "disappear" during processing, we will know about it. * record to "disappear" during processing, we will know about it.
*/ */
pIndices = malloc(countAttr * sizeof(*pIndices)); pIndices = malloc(countAttr * sizeof(*pIndices));
if (pIndices == nil) { if (pIndices == NULL) {
fprintf(stderr, "ERROR: malloc on %ld indices failed\n", countAttr); fprintf(stderr, "ERROR: malloc on %u indices failed\n", countAttr);
err = kNuErrGeneric; err = kNuErrGeneric;
goto bail; goto bail;
} }
@ -470,7 +461,7 @@ RecompressArchive(NuArchive* pArchive, NuValue compression)
err = RecompressRecord(pArchive, pIndices[idx], &recHeldLen); err = RecompressRecord(pArchive, pIndices[idx], &recHeldLen);
if (err != kNuErrNone) { if (err != kNuErrNone) {
fprintf(stderr, "ERROR: failed recompressing record %ld (err=%d)\n", fprintf(stderr, "ERROR: failed recompressing record %u (err=%d)\n",
pIndices[idx], err); pIndices[idx], err);
goto bail; goto bail;
} }
@ -478,7 +469,7 @@ RecompressArchive(NuArchive* pArchive, NuValue compression)
heldLen += recHeldLen; heldLen += recHeldLen;
if (heldLen > kMaxHeldLen) { if (heldLen > kMaxHeldLen) {
long statusFlags; uint32_t statusFlags;
printf(" (flush)\n"); printf(" (flush)\n");
err = NuFlush(pArchive, &statusFlags); err = NuFlush(pArchive, &statusFlags);
@ -500,12 +491,11 @@ bail:
/* /*
* Initiate the twirling. * Initiate the twirling.
*/ */
int int TwirlArchive(const char* filename)
TwirlArchive(const char* filename)
{ {
NuError err = kNuErrNone; NuError err = kNuErrNone;
NuArchive* pArchive = nil; NuArchive* pArchive = NULL;
CRCList* pCRCList = nil; CRCList* pCRCList = NULL;
int compression; int compression;
int cc; int cc;
@ -534,7 +524,7 @@ TwirlArchive(const char* filename)
} }
pCRCList = GatherCRCs(pArchive); pCRCList = GatherCRCs(pArchive);
if (pCRCList == nil) { if (pCRCList == NULL) {
fprintf(stderr, "ERROR: unable to get CRC list\n"); fprintf(stderr, "ERROR: unable to get CRC list\n");
goto bail; goto bail;
} }
@ -545,7 +535,7 @@ TwirlArchive(const char* filename)
for (compression = kNuCompressNone; compression <= kNuCompressBzip2; for (compression = kNuCompressNone; compression <= kNuCompressBzip2;
compression++) compression++)
{ {
long statusFlags; uint32_t statusFlags;
if (!CompressionSupported(compression)) if (!CompressionSupported(compression))
continue; continue;
@ -571,7 +561,7 @@ TwirlArchive(const char* filename)
for (compression = kNuCompressBzip2; compression >= kNuCompressNone; for (compression = kNuCompressBzip2; compression >= kNuCompressNone;
compression--) compression--)
{ {
long statusFlags; uint32_t statusFlags;
if (!CompressionSupported(compression)) if (!CompressionSupported(compression))
continue; continue;
@ -599,7 +589,7 @@ TwirlArchive(const char* filename)
bail: bail:
FreeCRCs(pCRCList); FreeCRCs(pCRCList);
if (pArchive != nil) { if (pArchive != NULL) {
NuAbort(pArchive); NuAbort(pArchive);
NuClose(pArchive); NuClose(pArchive);
} }
@ -611,22 +601,21 @@ bail:
/* /*
* Copy from the current offset in "srcfp" to a new file called * Copy from the current offset in "srcfp" to a new file called
* "outFileName". Returns a writable file descriptor for the new file * "outFileName". Returns a writable file descriptor for the new file
* on success, or nil on error. * on success, or NULL on error.
* *
* (Note "CopyFile()" exists under Win32.) * (Note "CopyFile()" exists under Win32.)
*/ */
FILE* FILE* MyCopyFile(const char* outFileName, FILE* srcfp)
MyCopyFile(const char* outFileName, FILE* srcfp)
{ {
char buf[24576]; char buf[24576];
FILE* outfp; FILE* outfp;
size_t count; size_t count;
outfp = fopen(outFileName, kNuFileOpenWriteTrunc); outfp = fopen(outFileName, kNuFileOpenWriteTrunc);
if (outfp == nil) { if (outfp == NULL) {
fprintf(stderr, "ERROR: unable to open '%s' (err=%d)\n", outFileName, fprintf(stderr, "ERROR: unable to open '%s' (err=%d)\n", outFileName,
errno); errno);
return nil; return NULL;
} }
while (!feof(srcfp)) { while (!feof(srcfp)) {
@ -636,14 +625,14 @@ MyCopyFile(const char* outFileName, FILE* srcfp)
if (fwrite(buf, 1, count, outfp) != count) { if (fwrite(buf, 1, count, outfp) != count) {
fprintf(stderr, "ERROR: failed writing outfp (err=%d)\n", errno); fprintf(stderr, "ERROR: failed writing outfp (err=%d)\n", errno);
fclose(outfp); fclose(outfp);
return nil; return NULL;
} }
} }
if (ferror(srcfp)) { if (ferror(srcfp)) {
fprintf(stderr, "ERROR: failed reading srcfp (err=%d)\n", errno); fprintf(stderr, "ERROR: failed reading srcfp (err=%d)\n", errno);
fclose(outfp); fclose(outfp);
return nil; return NULL;
} }
return outfp; return outfp;
@ -652,26 +641,25 @@ MyCopyFile(const char* outFileName, FILE* srcfp)
/* /*
* Let's get started. * Let's get started.
*/ */
int int main(int argc, char** argv)
main(int argc, char** argv)
{ {
long major, minor, bug; int32_t major, minor, bug;
const char* pBuildDate; const char* pBuildDate;
FILE* srcfp = nil; FILE* srcfp = NULL;
FILE* infp = nil; FILE* infp = NULL;
int cc; int cc;
/* don't buffer output */ /* don't buffer output */
setvbuf(stdout, nil, _IONBF, 0); setvbuf(stdout, NULL, _IONBF, 0);
setvbuf(stderr, nil, _IONBF, 0); setvbuf(stderr, NULL, _IONBF, 0);
(void) NuGetVersion(&major, &minor, &bug, &pBuildDate, nil); (void) NuGetVersion(&major, &minor, &bug, &pBuildDate, NULL);
printf("Using NuFX lib %ld.%ld.%ld built on or after %s\n\n", printf("Using NuFX lib %d.%d.%d built on or after %s\n\n",
major, minor, bug, pBuildDate); major, minor, bug, pBuildDate);
if (argc == 2) { if (argc == 2) {
srcfp = fopen(argv[1], kNuFileOpenReadOnly); srcfp = fopen(argv[1], kNuFileOpenReadOnly);
if (srcfp == nil) { if (srcfp == NULL) {
perror("fopen failed"); perror("fopen failed");
exit(1); exit(1);
} }
@ -683,7 +671,7 @@ main(int argc, char** argv)
printf("Copying '%s' to '%s'\n", argv[1], kWorkFileName); printf("Copying '%s' to '%s'\n", argv[1], kWorkFileName);
infp = MyCopyFile(kWorkFileName, srcfp); infp = MyCopyFile(kWorkFileName, srcfp);
if (infp == nil) { if (infp == NULL) {
fprintf(stderr, "Copy failed, bailing.\n"); fprintf(stderr, "Copy failed, bailing.\n");
exit(1); exit(1);
} }