diff --git a/Sources/Plasma/Apps/plClient/plClient.cpp b/Sources/Plasma/Apps/plClient/plClient.cpp index 0242debe81..2eb8c1f1f7 100644 --- a/Sources/Plasma/Apps/plClient/plClient.cpp +++ b/Sources/Plasma/Apps/plClient/plClient.cpp @@ -820,7 +820,6 @@ bool plClient::MsgReceive(plMessage* msg) char buf[256]; sprintf(buf, "%s %d\n", plAgeLoader::GetInstance()->GetCurrAgeFilename(), fNumPostLoadMsgs); s.WriteString(buf); - s.Close(); #endif #endif } @@ -2021,9 +2020,6 @@ void plClient::IDetectAudioVideoSettings() plPipeline::fDefaultPipeParams.VSync = false; - int val = 0; - hsStream *stream = nullptr; - hsUNIXStream s; plFileName audioIniFile = plFileName::Join(plFileSystem::GetInitPath(), "audio.ini"); plFileName graphicsIniFile = plFileName::Join(plFileSystem::GetInitPath(), "graphics.ini"); @@ -2036,54 +2032,44 @@ void plClient::IDetectAudioVideoSettings() #endif //check to see if audio.ini exists - if (s.Open(audioIniFile)) - s.Close(); - else + if (!plFileInfo(audioIniFile).Exists()) IWriteDefaultAudioSettings(audioIniFile); // check to see if graphics.ini exists - if (s.Open(graphicsIniFile)) - s.Close(); - else + if (!plFileInfo(graphicsIniFile).Exists()) IWriteDefaultGraphicsSettings(graphicsIniFile); } void plClient::IWriteDefaultAudioSettings(const plFileName& destFile) { - hsStream *stream = plEncryptedStream::OpenEncryptedFileWrite(destFile); - WriteBool(stream, "Audio.Initialize", true); - WriteBool(stream, "Audio.UseEAX", false); - WriteInt(stream, "Audio.SetPriorityCutoff", 6); - WriteInt(stream, "Audio.MuteAll", false); - WriteInt(stream, "Audio.SetChannelVolume SoundFX", 1); - WriteInt(stream, "Audio.SetChannelVolume BgndMusic", 1); - WriteInt(stream, "Audio.SetChannelVolume Ambience", 1); - WriteInt(stream, "Audio.SetChannelVolume NPCVoice", 1); - WriteInt(stream, "Audio.EnableVoiceRecording", 1); - WriteInt(stream, "Audio.EnableSubtitles", true); - stream->Close(); - delete stream; - stream = nullptr; + std::unique_ptr stream = plEncryptedStream::OpenEncryptedFileWrite(destFile); + WriteBool(stream.get(), "Audio.Initialize", true); + WriteBool(stream.get(), "Audio.UseEAX", false); + WriteInt(stream.get(), "Audio.SetPriorityCutoff", 6); + WriteInt(stream.get(), "Audio.MuteAll", false); + WriteInt(stream.get(), "Audio.SetChannelVolume SoundFX", 1); + WriteInt(stream.get(), "Audio.SetChannelVolume BgndMusic", 1); + WriteInt(stream.get(), "Audio.SetChannelVolume Ambience", 1); + WriteInt(stream.get(), "Audio.SetChannelVolume NPCVoice", 1); + WriteInt(stream.get(), "Audio.EnableVoiceRecording", 1); + WriteInt(stream.get(), "Audio.EnableSubtitles", true); } void plClient::IWriteDefaultGraphicsSettings(const plFileName& destFile) { - hsStream *stream = plEncryptedStream::OpenEncryptedFileWrite(destFile); - - WriteInt(stream, "Graphics.Width", plPipeline::fDefaultPipeParams.Width); - WriteInt(stream, "Graphics.Height", plPipeline::fDefaultPipeParams.Height); - WriteInt(stream, "Graphics.ColorDepth", plPipeline::fDefaultPipeParams.ColorDepth); - WriteBool(stream, "Graphics.Windowed", plPipeline::fDefaultPipeParams.Windowed); - WriteInt(stream, "Graphics.AntiAliasAmount", plPipeline::fDefaultPipeParams.AntiAliasingAmount); - WriteInt(stream, "Graphics.AnisotropicLevel", plPipeline::fDefaultPipeParams.AnisotropicLevel ); - WriteInt(stream, "Graphics.TextureQuality", plPipeline::fDefaultPipeParams.TextureQuality); - WriteInt(stream, "Quality.Level", plPipeline::fDefaultPipeParams.VideoQuality); - WriteInt(stream, "Graphics.Shadow.Enable", plPipeline::fDefaultPipeParams.Shadows); - WriteInt(stream, "Graphics.EnablePlanarReflections", plPipeline::fDefaultPipeParams.PlanarReflections); - WriteBool(stream, "Graphics.EnableVSync", plPipeline::fDefaultPipeParams.VSync); - stream->Close(); - delete stream; - stream = nullptr; + std::unique_ptr stream = plEncryptedStream::OpenEncryptedFileWrite(destFile); + + WriteInt(stream.get(), "Graphics.Width", plPipeline::fDefaultPipeParams.Width); + WriteInt(stream.get(), "Graphics.Height", plPipeline::fDefaultPipeParams.Height); + WriteInt(stream.get(), "Graphics.ColorDepth", plPipeline::fDefaultPipeParams.ColorDepth); + WriteBool(stream.get(), "Graphics.Windowed", plPipeline::fDefaultPipeParams.Windowed); + WriteInt(stream.get(), "Graphics.AntiAliasAmount", plPipeline::fDefaultPipeParams.AntiAliasingAmount); + WriteInt(stream.get(), "Graphics.AnisotropicLevel", plPipeline::fDefaultPipeParams.AnisotropicLevel ); + WriteInt(stream.get(), "Graphics.TextureQuality", plPipeline::fDefaultPipeParams.TextureQuality); + WriteInt(stream.get(), "Quality.Level", plPipeline::fDefaultPipeParams.VideoQuality); + WriteInt(stream.get(), "Graphics.Shadow.Enable", plPipeline::fDefaultPipeParams.Shadows); + WriteInt(stream.get(), "Graphics.EnablePlanarReflections", plPipeline::fDefaultPipeParams.PlanarReflections); + WriteBool(stream.get(), "Graphics.EnableVSync", plPipeline::fDefaultPipeParams.VSync); } diff --git a/Sources/Plasma/Apps/plClient/win32/winmain.cpp b/Sources/Plasma/Apps/plClient/win32/winmain.cpp index 92855684df..02cc0f9f14 100644 --- a/Sources/Plasma/Apps/plClient/win32/winmain.cpp +++ b/Sources/Plasma/Apps/plClient/win32/winmain.cpp @@ -875,10 +875,8 @@ INT_PTR CALLBACK UruLoginDialogProc( HWND hwndDlg, UINT uMsg, WPARAM wParam, LPA { plFileName gipath = plFileName::Join(plFileSystem::GetInitPath(), "general.ini"); ST::string ini_str = ST::format("App.SetLanguage {}\n", plLocalization::GetLanguageName(new_language)); - hsStream* gini = plEncryptedStream::OpenEncryptedFileWrite(gipath); + std::unique_ptr gini = plEncryptedStream::OpenEncryptedFileWrite(gipath); gini->WriteString(ini_str); - gini->Close(); - delete gini; } memset(&pLoginParam->authError, 0, sizeof(pLoginParam->authError)); diff --git a/Sources/Plasma/Apps/plFileSecure/main.cpp b/Sources/Plasma/Apps/plFileSecure/main.cpp index 9370103433..85cf3ccfca 100644 --- a/Sources/Plasma/Apps/plFileSecure/main.cpp +++ b/Sources/Plasma/Apps/plFileSecure/main.cpp @@ -104,7 +104,6 @@ void GenerateKey(bool useDefault) hsUNIXStream out; out.Open(plSecureStream::kKeyFilename, "wb"); out.Write(sizeof(uint32_t) * std::size(key), (void*)key); - out.Close(); } void SecureFiles(const plFileName& dir, const ST::string& ext, uint32_t* key) diff --git a/Sources/Plasma/Apps/plPageInfo/plPageInfo.cpp b/Sources/Plasma/Apps/plPageInfo/plPageInfo.cpp index b903d5c3ca..a7d66d659a 100644 --- a/Sources/Plasma/Apps/plPageInfo/plPageInfo.cpp +++ b/Sources/Plasma/Apps/plPageInfo/plPageInfo.cpp @@ -44,6 +44,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "hsStream.h" #include "hsTimer.h" +#include #include #include "pnFactory/plFactory.h" @@ -212,7 +213,7 @@ class plStatDumpIterator : public plRegistryPageIterator, public plRegistryKeyIt { protected: plFileName fOutputDir; - hsUNIXStream fStream; + std::unique_ptr fStream; public: plStatDumpIterator(const plFileName& outputDir) : fOutputDir(outputDir) {} @@ -221,16 +222,16 @@ class plStatDumpIterator : public plRegistryPageIterator, public plRegistryKeyIt { const plKeyImp* imp = plKeyImp::GetFromKey(key); - fStream.WriteString(key->GetName()); - fStream.WriteString(","); + fStream->WriteString(key->GetName()); + fStream->WriteString(","); - fStream.WriteString(plFactory::GetNameOfClass(key->GetUoid().GetClassType())); - fStream.WriteString(","); + fStream->WriteString(plFactory::GetNameOfClass(key->GetUoid().GetClassType())); + fStream->WriteString(","); char buf[30]; sprintf(buf, "%u", imp->GetDataLen()); - fStream.WriteString(buf); - fStream.WriteString("\n"); + fStream->WriteString(buf); + fStream->WriteString("\n"); return true; } @@ -241,12 +242,13 @@ class plStatDumpIterator : public plRegistryPageIterator, public plRegistryKeyIt plFileName fileName = plFileName::Join(fOutputDir, ST::format("{}_{}.csv", info.GetAge(), info.GetPage())); - fStream.Open(fileName, "wt"); + fStream = std::make_unique(); + fStream->Open(fileName, "wt"); page->LoadKeys(); page->IterateKeys(this); - fStream.Close(); + fStream.reset(); return true; } diff --git a/Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.cpp b/Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.cpp index d502ea52fc..b9d563e8eb 100644 --- a/Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.cpp +++ b/Sources/Plasma/Apps/plPageOptimizer/plPageOptimizer.cpp @@ -269,8 +269,5 @@ void plPageOptimizer::IRewritePage() newPage.WriteLE32(dataLen); } } - - newPage.Close(); - oldPage.Close(); } } diff --git a/Sources/Plasma/Apps/plPythonPack/main.cpp b/Sources/Plasma/Apps/plPythonPack/main.cpp index be496fc0f5..125a0ec863 100644 --- a/Sources/Plasma/Apps/plPythonPack/main.cpp +++ b/Sources/Plasma/Apps/plPythonPack/main.cpp @@ -206,9 +206,6 @@ void WritePythonFile(const plFileName &fileName, const plFileName &path, hsStrea delete [] code; Py_XDECREF(pythonCode); Py_XDECREF(fModule); - - pyStream.Close(); - glueStream.Close(); } void FindFiles(std::vector &filenames, std::vector &pathnames, const plFileName& path) @@ -291,40 +288,40 @@ void PackDirectory(const plFileName& dir, const plFileName& rootPath, const plFi // ok, we know how many files we're gonna pack, so make a fake index (we'll fill in later) - hsUNIXStream s; - if (!s.Open(pakName, "wb")) - return; - - s.WriteLE32((uint32_t)fileNames.size()); - for (const plFileName& fn : fileNames) { - s.WriteSafeString(fn.AsString()); - s.WriteLE32(0); - } + hsUNIXStream s; + if (!s.Open(pakName, "wb")) + return; - PythonInterface::initPython(rootPath, extraDirs, out, stderr); - - std::vector filePositions; - filePositions.resize(fileNames.size()); + s.WriteLE32((uint32_t)fileNames.size()); + for (const plFileName& fn : fileNames) + { + s.WriteSafeString(fn.AsString()); + s.WriteLE32(0); + } - for (size_t i = 0; i < fileNames.size(); i++) - { - // strip '.py' from the file name - plFileName properFileName = fileNames[i].StripFileExt(); - uint32_t initialPos = s.GetPosition(); - WritePythonFile(properFileName, pathNames[i], &s); + PythonInterface::initPython(rootPath, extraDirs, out, stderr); + + std::vector filePositions(fileNames.size()); - filePositions[i] = initialPos; - } + for (size_t i = 0; i < fileNames.size(); i++) + { + // strip '.py' from the file name + plFileName properFileName = fileNames[i].StripFileExt(); + uint32_t initialPos = s.GetPosition(); + WritePythonFile(properFileName, pathNames[i], &s); + + filePositions[i] = initialPos; + } - s.SetPosition(sizeof(uint32_t)); - for (size_t i = 0; i < fileNames.size(); i++) - { - s.WriteSafeString(fileNames[i].AsString()); - s.WriteLE32(filePositions[i]); + s.SetPosition(sizeof(uint32_t)); + for (size_t i = 0; i < fileNames.size(); i++) + { + s.WriteSafeString(fileNames[i].AsString()); + s.WriteLE32(filePositions[i]); + } } - s.Close(); ST::printf(out, "\nPython Package written to {}\n", pakName); PythonInterface::finiPython(); diff --git a/Sources/Plasma/CoreLib/hsStream.cpp b/Sources/Plasma/CoreLib/hsStream.cpp index 19c26e6653..099587556d 100644 --- a/Sources/Plasma/CoreLib/hsStream.cpp +++ b/Sources/Plasma/CoreLib/hsStream.cpp @@ -427,7 +427,9 @@ void hsStream::WriteLEFloat(size_t count, const float values[]) hsUNIXStream::~hsUNIXStream() { - // Don't Close here, because Sub classes Don't always want that behaviour! + if (fRef) { + fclose(fRef); + } } bool hsUNIXStream::Open(const plFileName &name, const char *mode) @@ -437,16 +439,6 @@ bool hsUNIXStream::Open(const plFileName &name, const char *mode) return (fRef) ? true : false; } -bool hsUNIXStream::Close() -{ - int rtn = true; - if (fRef) - rtn = fclose(fRef); - fRef = nullptr; - - return !rtn; -} - uint32_t hsUNIXStream::Read(uint32_t bytes, void* buffer) { if (!fRef || !bytes) @@ -549,16 +541,9 @@ void hsUNIXStream::Flush() ////////////////////////////////////////////////////////////////////////////////////// -plReadOnlySubStream::~plReadOnlySubStream() +plReadOnlySubStream::plReadOnlySubStream(hsStream* base, uint32_t offset, uint32_t length) + : fBase(base), fOffset(offset), fLength(length) { -} - -void plReadOnlySubStream::Open( hsStream *base, uint32_t offset, uint32_t length ) -{ - fBase = base; - fOffset = offset; - fLength = length; - fBase->SetPosition( fOffset ); IFixPosition(); } @@ -803,6 +788,12 @@ void hsReadOnlyStream::CopyToMem(void* mem) //////////////////////////////////////////////////////////////////////////////////// + +bool hsWriteOnlyStream::AtEnd() +{ + return fData >= fStop; +} + uint32_t hsWriteOnlyStream::Read(uint32_t byteCount, void* buffer) { hsThrow( "can't read to a writeonly stream"); @@ -819,6 +810,39 @@ uint32_t hsWriteOnlyStream::Write(uint32_t byteCount, const void* buffer) return byteCount; } +void hsWriteOnlyStream::Skip(uint32_t deltaByteCount) +{ + fPosition += deltaByteCount; + fData += deltaByteCount; + if (fData > fStop) { + hsThrow("Skip went past end of stream"); + } +} + +void hsWriteOnlyStream::Rewind() +{ + fPosition = 0; + fData = fStart; +} + +void hsWriteOnlyStream::FastFwd() +{ + fPosition = GetEOF(); + fData = fStop; +} + +void hsWriteOnlyStream::Truncate() +{ + hsThrow("can't change size of hsWriteOnlyStream"); +} + +void hsWriteOnlyStream::CopyToMem(void* mem) +{ + if (fData < fStop) { + memmove(mem, fData, fStop - fData); + } +} + /////////////////////////////////////////////////////////////////////////////////// @@ -972,57 +996,52 @@ hsBufferedStream::hsBufferedStream() { } -bool hsBufferedStream::Open(const plFileName& name, const char* mode) -{ - hsAssert(!fRef, "hsBufferedStream:Open Stream already opened"); - fRef = plFileSystem::Open(name, mode); - if (!fRef) - return false; - - SetFileRef(fRef); - -#ifdef LOG_BUFFERED - fBufferHits = fBufferMisses = 0; - fBufferReadIn = fBufferReadOut = fReadDirect = fLastReadPos = 0; - fFilename = name; - fCloseReason = nullptr; -#endif // LOG_BUFFERED - - return true; -} - -bool hsBufferedStream::Close() +hsBufferedStream::~hsBufferedStream() { - int rtn = true; - if (fRef) - rtn = fclose(fRef); - fRef = nullptr; + if (fRef) { + fclose(fRef); + } #ifdef LOG_BUFFERED hsUNIXStream s; static bool firstClose = true; - if (firstClose) - { + if (firstClose) { firstClose = false; s.Open("log\\BufferedStream.csv", "wt"); s.WriteString("File,Hits,Misses,Read In,Read Out,Read Direct,% Wasted,Reason\n"); - } - else + } else { s.Open("log\\BufferedStream.csv", "at"); + } int wasted = 100; - if (fBufferReadIn + fReadDirect > 0) + if (fBufferReadIn + fReadDirect > 0) { wasted -= int((float(fBufferReadOut+fReadDirect) / float(fBufferReadIn+fReadDirect)) * 100.f); + } s.WriteString(ST::format("{},{},{},{},{},{},{},{}\n", fFilename, fBufferHits, fBufferMisses, fBufferReadIn, fBufferReadOut, fReadDirect, wasted, fCloseReason ? fCloseReason : "Unknown")); +#endif // LOG_BUFFERED +} + +bool hsBufferedStream::Open(const plFileName& name, const char* mode) +{ + hsAssert(!fRef, "hsBufferedStream:Open Stream already opened"); + fRef = plFileSystem::Open(name, mode); + if (!fRef) + return false; - s.Close(); + SetFileRef(fRef); + +#ifdef LOG_BUFFERED + fBufferHits = fBufferMisses = 0; + fBufferReadIn = fBufferReadOut = fReadDirect = fLastReadPos = 0; + fFilename = name; + fCloseReason = nullptr; #endif // LOG_BUFFERED - return !rtn; + return true; } FILE* hsBufferedStream::GetFileRef() diff --git a/Sources/Plasma/CoreLib/hsStream.h b/Sources/Plasma/CoreLib/hsStream.h index 137c306267..609da689dc 100644 --- a/Sources/Plasma/CoreLib/hsStream.h +++ b/Sources/Plasma/CoreLib/hsStream.h @@ -62,8 +62,6 @@ enum { hsStream() : fPosition(0) {} virtual ~hsStream() { } - virtual bool Open(const plFileName &, const char * = "rb") = 0; - virtual bool Close()=0; virtual bool AtEnd() = 0; virtual uint32_t Read(uint32_t byteCount, void * buffer) = 0; virtual uint32_t Write(uint32_t byteCount, const void* buffer) = 0; @@ -143,6 +141,11 @@ enum { template void WriteLEDouble(T) = delete; }; +class hsFileSystemStream : public hsStream { +public: + virtual bool Open(const plFileName&, const char* = "rb") = 0; +}; + class hsStreamable { public: virtual void Read(hsStream* stream) = 0; @@ -150,15 +153,20 @@ class hsStreamable { virtual uint32_t GetStreamSize() = 0; }; -class hsUNIXStream: public hsStream +class hsUNIXStream : public hsFileSystemStream { FILE* fRef; public: hsUNIXStream() : fRef() {} + hsUNIXStream(const hsUNIXStream& other) = delete; + hsUNIXStream(hsUNIXStream&& other) = delete; ~hsUNIXStream(); + + const hsUNIXStream& operator=(const hsUNIXStream& other) = delete; + hsUNIXStream& operator=(hsUNIXStream&& other) = delete; + bool Open(const plFileName& name, const char* mode = "rb") override; - bool Close() override; bool AtEnd() override; uint32_t Read(uint32_t byteCount, void* buffer) override; @@ -188,12 +196,8 @@ class plReadOnlySubStream: public hsStream void IFixPosition(); public: - plReadOnlySubStream() : fBase(), fOffset(), fLength() { } - ~plReadOnlySubStream(); + plReadOnlySubStream(hsStream* base, uint32_t offset, uint32_t length); - bool Open(const plFileName &, const char *) override { hsAssert(0, "plReadOnlySubStream::Open NotImplemented"); return false; } - void Open( hsStream *base, uint32_t offset, uint32_t length ); - bool Close() override { fBase = nullptr; fOffset = 0; fLength = 0; return true; } bool AtEnd() override; uint32_t Read(uint32_t byteCount, void* buffer) override; uint32_t Write(uint32_t byteCount, const void* buffer) override; @@ -217,10 +221,6 @@ class hsRAMStream : public hsStream hsRAMStream() {} hsRAMStream(uint32_t chunkSize) { fVector.reserve(chunkSize); } - bool Open(const plFileName &, const char *) override { hsAssert(0, "hsRAMStream::Open NotImplemented"); return false; } - bool Close() override { return false; } - - bool AtEnd() override; uint32_t Read(uint32_t byteCount, void * buffer) override; uint32_t Write(uint32_t byteCount, const void* buffer) override; @@ -245,10 +245,6 @@ class hsRAMStream : public hsStream class hsNullStream : public hsStream { public: - - bool Open(const plFileName &, const char *) override { return true; } - bool Close() override { return true; } - bool AtEnd() override; uint32_t Read(uint32_t byteCount, void * buffer) override; // throws exception uint32_t Write(uint32_t byteCount, const void* buffer) override; @@ -264,16 +260,16 @@ class hsNullStream : public hsStream { // read only mem stream class hsReadOnlyStream : public hsStream { protected: - char* fStart; - char* fData; - char* fStop; + const char* fStart; + const char* fData; + const char* fStop; public: - hsReadOnlyStream(int size, const void* data) { Init(size, data); } - hsReadOnlyStream() : fStart(), fData(), fStop() { } + hsReadOnlyStream(int size, const void* data) : + fStart(static_cast(data)), + fData(static_cast(data)), + fStop(static_cast(data) + size) + {} - virtual void Init(int size, const void* data) { fStart=((char*)data); fData=((char*)data); fStop=((char*)data + size); } - bool Open(const plFileName &, const char *) override { hsAssert(0, "hsReadOnlyStream::Open NotImplemented"); return false; } - bool Close() override { hsAssert(0, "hsReadOnlyStream::Close NotImplemented"); return false; } bool AtEnd() override; uint32_t Read(uint32_t byteCount, void * buffer) override; uint32_t Write(uint32_t byteCount, const void* buffer) override; // throws exception @@ -286,15 +282,33 @@ class hsReadOnlyStream : public hsStream { }; // write only mem stream -class hsWriteOnlyStream : public hsReadOnlyStream { +class hsWriteOnlyStream : public hsStream { +protected: + char* fStart; + char* fData; + char* fStop; + public: - hsWriteOnlyStream(int size, const void* data) : hsReadOnlyStream(size, data) {} - hsWriteOnlyStream() {} + hsWriteOnlyStream(int size, void* data) : + fStart(static_cast(data)), + fData(static_cast(data)), + fStop(static_cast(data) + size) + {} + hsWriteOnlyStream(const hsWriteOnlyStream& other) = delete; + hsWriteOnlyStream(hsWriteOnlyStream&& other) = delete; + + const hsWriteOnlyStream& operator=(const hsWriteOnlyStream& other) = delete; + hsWriteOnlyStream& operator=(hsWriteOnlyStream&& other) = delete; - bool Open(const plFileName &, const char *) override { hsAssert(0, "hsWriteOnlyStream::Open NotImplemented"); return false; } - bool Close() override { hsAssert(0, "hsWriteOnlyStream::Close NotImplemented"); return false; } + bool AtEnd() override; uint32_t Read(uint32_t byteCount, void * buffer) override; // throws exception uint32_t Write(uint32_t byteCount, const void* buffer) override; + void Skip(uint32_t deltaByteCount) override; + void Rewind() override; + void FastFwd() override; + void Truncate() override; + uint32_t GetEOF() override { return (uint32_t)(fStop - fStart); } + void CopyToMem(void* mem); }; // circular queue stream @@ -307,10 +321,12 @@ class hsQueueStream : public hsStream { public: hsQueueStream(int32_t size); + hsQueueStream(const hsQueueStream& other) = delete; + hsQueueStream(hsQueueStream&& other) = delete; ~hsQueueStream(); - bool Open(const plFileName &, const char *) override { hsAssert(0, "hsQueueStream::Open NotImplemented"); return false; } - bool Close() override { hsAssert(0, "hsQueueStream::Close NotImplemented"); return false; } + const hsQueueStream& operator=(const hsQueueStream& other) = delete; + hsQueueStream& operator=(hsQueueStream&& other) = delete; uint32_t Read(uint32_t byteCount, void * buffer) override; uint32_t Write(uint32_t byteCount, const void* buffer) override; @@ -327,7 +343,7 @@ class hsQueueStream : public hsStream { uint32_t GetWriteCursor() { return fWriteCursor; } }; -class hsBufferedStream : public hsStream +class hsBufferedStream : public hsFileSystemStream { FILE* fRef; uint32_t fFileSize; @@ -351,10 +367,14 @@ class hsBufferedStream : public hsStream public: hsBufferedStream(); - virtual ~hsBufferedStream() { } + hsBufferedStream(const hsBufferedStream& other) = delete; + hsBufferedStream(hsBufferedStream&& other) = delete; + ~hsBufferedStream(); + + const hsBufferedStream& operator=(const hsBufferedStream& other) = delete; + hsBufferedStream& operator=(hsBufferedStream&& other) = delete; bool Open(const plFileName& name, const char* mode = "rb") override; - bool Close() override; bool AtEnd() override; uint32_t Read(uint32_t byteCount, void* buffer) override; diff --git a/Sources/Plasma/CoreLib/hsSystemInfo.cpp b/Sources/Plasma/CoreLib/hsSystemInfo.cpp index f4176e33e3..183c4fa8f0 100644 --- a/Sources/Plasma/CoreLib/hsSystemInfo.cpp +++ b/Sources/Plasma/CoreLib/hsSystemInfo.cpp @@ -221,12 +221,10 @@ static inline bool IGetLinuxVersion(const plFileName& osVersionPath, ST::string& system = ST::string::from_utf8(token); // chop off the quotes system = system.substr(1, system.size() - 2); - s.Close(); return true; } } } - s.Close(); } } diff --git a/Sources/Plasma/FeatureLib/pfConsole/pfConsoleCommands.cpp b/Sources/Plasma/FeatureLib/pfConsole/pfConsoleCommands.cpp index 854c39a1a6..8124ae1d6d 100644 --- a/Sources/Plasma/FeatureLib/pfConsole/pfConsoleCommands.cpp +++ b/Sources/Plasma/FeatureLib/pfConsole/pfConsoleCommands.cpp @@ -5298,8 +5298,6 @@ PF_CONSOLE_CMD( Age, GetElapsedDays, "string agedefnfile", "Gets the elapsed day age.Read(&s); PrintString(ST::format("ElapsedTime: {f} Days", age.GetAgeElapsedDays(plUnifiedTime::GetCurrent()))); - - s.Close(); } PF_CONSOLE_CMD( Age, GetTimeOfDay, "string agedefnfile", "Gets the elapsed days and fractions" ) @@ -5315,8 +5313,6 @@ PF_CONSOLE_CMD( Age, GetTimeOfDay, "string agedefnfile", "Gets the elapsed days age.Read(&s); PrintString(ST::format("TimeOfDay: {f} percent", age.GetAgeTimeOfDayPercent(plUnifiedTime::GetCurrent()))); - - s.Close(); } PF_CONSOLE_CMD( Age, SetSDLFloat, "string varName, float value, int index", "Set the value of an age global variable" ) diff --git a/Sources/Plasma/FeatureLib/pfConsoleCore/pfConsoleEngine.cpp b/Sources/Plasma/FeatureLib/pfConsoleCore/pfConsoleEngine.cpp index 87213d21ee..b89b9a3575 100644 --- a/Sources/Plasma/FeatureLib/pfConsoleCore/pfConsoleEngine.cpp +++ b/Sources/Plasma/FeatureLib/pfConsoleCore/pfConsoleEngine.cpp @@ -246,7 +246,7 @@ bool pfConsoleEngine::ExecuteFile(const plFileName &fileName) { int line; - hsStream* stream = plEncryptedStream::OpenEncryptedFile(fileName); + std::unique_ptr stream = plEncryptedStream::OpenEncryptedFile(fileName); if( !stream ) { @@ -268,13 +268,9 @@ bool pfConsoleEngine::ExecuteFile(const plFileName &fileName) { fErrorMsg = ST::format("Error in console file {}, command line {}: {}", fileName.AsString(), line, fErrorMsg); - stream->Close(); - delete stream; return false; } } - stream->Close(); - delete stream; fLastErrorLine.clear(); return true; diff --git a/Sources/Plasma/FeatureLib/pfLocalizationMgr/pfLocalizationDataMgr.cpp b/Sources/Plasma/FeatureLib/pfLocalizationMgr/pfLocalizationDataMgr.cpp index 2fe43196fc..57b40ecede 100644 --- a/Sources/Plasma/FeatureLib/pfLocalizationMgr/pfLocalizationDataMgr.cpp +++ b/Sources/Plasma/FeatureLib/pfLocalizationMgr/pfLocalizationDataMgr.cpp @@ -365,7 +365,7 @@ bool LocalizationXMLFile::Parse(const plFileName& fileName) XML_SetCharacterDataHandler(fParser, HandleData); XML_SetUserData(fParser, (void*)this); - hsStream *xmlStream = plEncryptedStream::OpenEncryptedFile(fileName); + std::unique_ptr xmlStream = plEncryptedStream::OpenEncryptedFile(fileName); if (!xmlStream) { pfLocalizationDataMgr::GetLog()->AddLineF("ERROR: Can't open file stream for {}", fileName); @@ -393,8 +393,6 @@ bool LocalizationXMLFile::Parse(const plFileName& fileName) XML_ParserFree(fParser); fParser = nullptr; - xmlStream->Close(); - delete xmlStream; return true; } @@ -901,10 +899,8 @@ void pfLocalizationDataMgr::IWriteText(const plFileName & filename, const ST::st if (weWroteData) { // now spit the results out to the file - hsStream *xmlStream = plEncryptedStream::OpenEncryptedFileWrite(filename); + std::unique_ptr xmlStream = plEncryptedStream::OpenEncryptedFileWrite(filename); xmlStream->Write(fileData.size(), fileData.raw_buffer()); - xmlStream->Close(); - delete xmlStream; } } diff --git a/Sources/Plasma/FeatureLib/pfPasswordStore/pfPasswordStore.cpp b/Sources/Plasma/FeatureLib/pfPasswordStore/pfPasswordStore.cpp index b02db01506..af4876ffca 100644 --- a/Sources/Plasma/FeatureLib/pfPasswordStore/pfPasswordStore.cpp +++ b/Sources/Plasma/FeatureLib/pfPasswordStore/pfPasswordStore.cpp @@ -90,7 +90,7 @@ ST::string pfFilePasswordStore::GetPassword(const ST::string& username) loginDat = local; #endif - hsStream* stream = plEncryptedStream::OpenEncryptedFile(loginDat, fCryptKey); + std::unique_ptr stream = plEncryptedStream::OpenEncryptedFile(loginDat, fCryptKey); if (stream && !stream->AtEnd()) { uint32_t savedKey[4]; @@ -103,9 +103,6 @@ ST::string pfFilePasswordStore::GetPassword(const ST::string& username) password = stream->ReadSafeString(); } } - - stream->Close(); - delete stream; } return password; @@ -123,16 +120,13 @@ bool pfFilePasswordStore::SetPassword(const ST::string& username, const ST::stri loginDat = local; #endif - hsStream* stream = plEncryptedStream::OpenEncryptedFileWrite(loginDat, fCryptKey); + std::unique_ptr stream = plEncryptedStream::OpenEncryptedFileWrite(loginDat, fCryptKey); if (stream) { stream->Write(sizeof(fCryptKey), fCryptKey); stream->WriteSafeString(username); stream->WriteSafeString(password); - stream->Close(); - delete stream; - return true; } diff --git a/Sources/Plasma/FeatureLib/pfPatcher/pfPatcher.cpp b/Sources/Plasma/FeatureLib/pfPatcher/pfPatcher.cpp index 576df658b1..3a7f887fdc 100644 --- a/Sources/Plasma/FeatureLib/pfPatcher/pfPatcher.cpp +++ b/Sources/Plasma/FeatureLib/pfPatcher/pfPatcher.cpp @@ -233,7 +233,7 @@ class pfPatcherStream : public plZlibStream : fParent(parent), fFilename(filename), fFlags(), fBytesWritten(), fDLStartTime(), plZlibStream() { fParent->fTotalBytes += size; - fOutput = new hsRAMStream; + fOutput = std::make_unique(); } pfPatcherStream(pfPatcherWorker* parent, const pfPatcherQueuedFile& file) @@ -382,7 +382,6 @@ static void IFileThingDownloadCB(ENetError result, void* param, const plFileName { pfPatcherWorker* patcher = static_cast(param); pfPatcherStream* stream = static_cast(writer); - stream->Close(); if (IS_NET_SUCCESS(result)) { PatcherLogGreen("\tDownloaded File '{}'", stream->GetFileName()); @@ -422,7 +421,6 @@ pfPatcherWorker::~pfPatcherWorker() hsLockGuard(fRequestMut); std::for_each(fRequests.begin(), fRequests.end(), [] (const Request& req) { - if (req.fStream) req.fStream->Close(); delete req.fStream; } ); @@ -632,8 +630,9 @@ void pfPatcherWorker::WhitelistFile(const plFileName& file, bool justDownloaded, ST::string ext = file.GetFileExt(); if (ext.compare_i("pak") == 0 || ext.compare_i("sdl") == 0) { if (!stream) { - stream = new hsUNIXStream; - stream->Open(file, "rb"); + hsUNIXStream* newStream = new hsUNIXStream; + newStream->Open(file, "rb"); + stream = newStream; } // if something terrible goes wrong (eg bad encryption), we can exit sanely @@ -641,9 +640,8 @@ void pfPatcherWorker::WhitelistFile(const plFileName& file, bool justDownloaded, if (!fGameCodeDiscovered(file, stream)) EndPatch(kNetErrInternalError, "SecurePreloader failed."); } - } else if (stream) { + } else { // no dad gum memory leaks, m'kay? - stream->Close(); delete stream; } } diff --git a/Sources/Plasma/FeatureLib/pfPython/pyStream.cpp b/Sources/Plasma/FeatureLib/pfPython/pyStream.cpp index b8b170e771..a7c6e082d8 100644 --- a/Sources/Plasma/FeatureLib/pfPython/pyStream.cpp +++ b/Sources/Plasma/FeatureLib/pfPython/pyStream.cpp @@ -59,12 +59,6 @@ pyStream::pyStream() { } -pyStream::~pyStream() -{ - Close(); -} - - bool pyStream::Open(const plFileName& fileName, const ST::string& flags) { // make sure its closed first @@ -92,8 +86,9 @@ bool pyStream::Open(const plFileName& fileName, const ST::string& flags) // force encryption? if (encryptflag) { - fStream = new plEncryptedStream; - fStream->Open(fileName, "wb"); + auto stream = std::make_unique(); + stream->Open(fileName, "wb"); + fStream = std::move(stream); } else fStream = plEncryptedStream::OpenEncryptedFileWrite(fileName); @@ -145,10 +140,5 @@ bool pyStream::WriteLines(const std::vector & lines) void pyStream::Close() { - if (fStream) - { - fStream->Close(); - delete fStream; - } - fStream = nullptr; + fStream.reset(); } diff --git a/Sources/Plasma/FeatureLib/pfPython/pyStream.h b/Sources/Plasma/FeatureLib/pfPython/pyStream.h index 6419b0b816..d1ef6b4abc 100644 --- a/Sources/Plasma/FeatureLib/pfPython/pyStream.h +++ b/Sources/Plasma/FeatureLib/pfPython/pyStream.h @@ -52,6 +52,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "HeadSpin.h" #include "pyGlueHelpers.h" +#include #include class hsStream; @@ -61,14 +62,12 @@ namespace ST { class string; } class pyStream { private: - hsStream* fStream; + std::unique_ptr fStream; protected: pyStream(); public: - ~pyStream(); - // required functions for PyObject interoperability PYTHON_CLASS_NEW_FRIEND(ptStream); PYTHON_CLASS_NEW_DEFINITION; diff --git a/Sources/Plasma/NucleusLib/pnEncryption/plChecksum.cpp b/Sources/Plasma/NucleusLib/pnEncryption/plChecksum.cpp index 9a4d634b50..caf71f5e35 100644 --- a/Sources/Plasma/NucleusLib/pnEncryption/plChecksum.cpp +++ b/Sources/Plasma/NucleusLib/pnEncryption/plChecksum.cpp @@ -168,7 +168,6 @@ void plMD5Checksum::CalcFromFile(const plFileName& fileName) if (s.Open(fileName)) { CalcFromStream(&s); - s.Close(); } } @@ -310,7 +309,6 @@ void plSHAChecksum::CalcFromFile(const plFileName& fileName) if (s.Open(fileName)) { CalcFromStream(&s); - s.Close(); } } @@ -463,7 +461,6 @@ void plSHA1Checksum::CalcFromFile(const plFileName& fileName) if (s.Open(fileName)) { CalcFromStream(&s); - s.Close(); } } diff --git a/Sources/Plasma/PubUtilLib/plAgeDescription/plAgeDescription.cpp b/Sources/Plasma/PubUtilLib/plAgeDescription/plAgeDescription.cpp index ab3f48bd4c..42b2fa1bf9 100644 --- a/Sources/Plasma/PubUtilLib/plAgeDescription/plAgeDescription.cpp +++ b/Sources/Plasma/PubUtilLib/plAgeDescription/plAgeDescription.cpp @@ -166,13 +166,11 @@ bool plAgeDescription::ReadFromFile( const plFileName &fileNameToReadFrom ) { IInit(); - hsStream* stream = plEncryptedStream::OpenEncryptedFile(fileNameToReadFrom); + std::unique_ptr stream = plEncryptedStream::OpenEncryptedFile(fileNameToReadFrom); if( !stream ) return false; - Read( stream ); - stream->Close(); - delete stream; + Read(stream.get()); SetAgeNameFromPath( fileNameToReadFrom ); return true; @@ -402,7 +400,6 @@ void plAgeDescription::Read(hsStream* stream) } reader.Parse(); - reader.Close(); } // diff --git a/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.cpp b/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.cpp index dca011eb48..e874e0ffa7 100644 --- a/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.cpp +++ b/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.cpp @@ -229,20 +229,19 @@ bool plAgeLoader::ILoadAge(const ST::string& ageName) fPendingAgeCsvFiles.emplace_back(plFileName::Join("dat", ST::format("{}.csv", fAgeName))); plSynchEnabler p( false ); // turn off dirty tracking while in this function - - hsStream* stream=GetAgeDescFileStream(fAgeName); - if (!stream) + plAgeDescription ad; { - nc->ErrorMsg("Failed loading age. Age desc file {} has nil stream", fAgeName); - fFlags &= ~kLoadingAge; - return false; - } + std::unique_ptr stream = GetAgeDescFileStream(fAgeName); + if (!stream) + { + nc->ErrorMsg("Failed loading age. Age desc file {} has nil stream", fAgeName); + fFlags &= ~kLoadingAge; + return false; + } - plAgeDescription ad; - ad.Read(stream); - ad.SetAgeName(fAgeName); - stream->Close(); - delete stream; + ad.Read(stream.get()); + ad.SetAgeName(fAgeName); + } ad.SeekFirstPage(); plAgePage *page; @@ -414,12 +413,10 @@ void plAgeLoader::ExecPendingAgeCsvFiles() int i; for (i=0;i stream = plEncryptedStream::OpenEncryptedFile(fPendingAgeCsvFiles[i].AsString()); if (stream) { - plRelevanceMgr::Instance()->ParseCsvInput(stream); - stream->Close(); - delete stream; + plRelevanceMgr::Instance()->ParseCsvInput(stream.get()); } } fPendingAgeCsvFiles.clear(); @@ -429,14 +426,14 @@ void plAgeLoader::ExecPendingAgeCsvFiles() // return alloced stream or nullptr // static // -hsStream* plAgeLoader::GetAgeDescFileStream(const ST::string& ageName) +std::unique_ptr plAgeLoader::GetAgeDescFileStream(const ST::string& ageName) { if (ageName.empty()) return nullptr; plFileName ageDescFileName = plFileName::Join("dat", ST::format("{}.age", ageName)); - hsStream* stream = plEncryptedStream::OpenEncryptedFile(ageDescFileName); + std::unique_ptr stream = plEncryptedStream::OpenEncryptedFile(ageDescFileName); if (!stream) { hsAssert(false, ST::format("Can't find age desc file {}", ageDescFileName).c_str()); diff --git a/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.h b/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.h index 7662154431..455d0f4377 100644 --- a/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.h +++ b/Sources/Plasma/PubUtilLib/plAgeLoader/plAgeLoader.h @@ -44,6 +44,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "HeadSpin.h" +#include + #include "pnKeyedObject/hsKeyedObject.h" #include "plAgeDescription/plAgeDescription.h" @@ -97,7 +99,7 @@ class plAgeLoader : public hsKeyedObject static plAgeLoader* GetInstance(); static void SetInstance(plAgeLoader* inst); - static hsStream* GetAgeDescFileStream(const ST::string& ageName); + static std::unique_ptr GetAgeDescFileStream(const ST::string& ageName); void Init(); void Shutdown(); diff --git a/Sources/Plasma/PubUtilLib/plAgeLoader/plResPatcher.cpp b/Sources/Plasma/PubUtilLib/plAgeLoader/plResPatcher.cpp index 76f62d44dc..a3a3600582 100644 --- a/Sources/Plasma/PubUtilLib/plAgeLoader/plResPatcher.cpp +++ b/Sources/Plasma/PubUtilLib/plAgeLoader/plResPatcher.cpp @@ -107,15 +107,14 @@ void plResPatcher::OnFileDownloaded(const plFileName& file) bool plResPatcher::OnGameCodeDiscovered(const plFileName& file, hsStream* stream) { - plSecureStream* ss = new plSecureStream(false, plStreamSource::GetInstance()->GetEncryptionKey()); + auto ss = std::make_unique(false, plStreamSource::GetInstance()->GetEncryptionKey()); if (ss->Open(stream)) { - plStreamSource::GetInstance()->InsertFile(file, ss); + plStreamSource::GetInstance()->InsertFile(file, std::move(ss)); // SecureStream will hold a decrypted buffer... - stream->Close(); delete stream; } else - plStreamSource::GetInstance()->InsertFile(file, stream); + plStreamSource::GetInstance()->InsertFile(file, std::unique_ptr(stream)); return true; // ASSume success for now... } diff --git a/Sources/Plasma/PubUtilLib/plAvatar/plAvatarClothing.cpp b/Sources/Plasma/PubUtilLib/plAvatar/plAvatarClothing.cpp index cd026d0c58..adc7bef9c4 100644 --- a/Sources/Plasma/PubUtilLib/plAvatar/plAvatarClothing.cpp +++ b/Sources/Plasma/PubUtilLib/plAvatar/plAvatarClothing.cpp @@ -1468,7 +1468,6 @@ bool plClothingOutfit::WriteToFile(const plFileName &filename) S.Write(sdl.GetSDLData().size(), sdl.GetSDLData().data()); } - S.Close(); return true; } @@ -1491,7 +1490,6 @@ bool plClothingOutfit::IReadFromFile(const plFileName &filename) else if (gender == plClothingMgr::kClothingBaseFemale) plClothingMgr::ChangeAvatar("Female", filename); } - S.Close(); return true; } @@ -1517,7 +1515,6 @@ bool plClothingOutfit::IReadFromFile(const plFileName &filename) } } - S.Close(); fSynchClients = true; ForceUpdate(true); SaveCustomizations(); // Sync with the vault diff --git a/Sources/Plasma/PubUtilLib/plClientResMgr/plClientResMgr.cpp b/Sources/Plasma/PubUtilLib/plClientResMgr/plClientResMgr.cpp index bc5a035ce7..9edf389c75 100644 --- a/Sources/Plasma/PubUtilLib/plClientResMgr/plClientResMgr.cpp +++ b/Sources/Plasma/PubUtilLib/plClientResMgr/plClientResMgr.cpp @@ -119,8 +119,6 @@ void plClientResMgr::ILoadResources(const plFileName& resfile) default: break; } - - in.Close(); } } diff --git a/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.cpp b/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.cpp index ecd9290285..d88224f9a1 100644 --- a/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.cpp +++ b/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.cpp @@ -54,7 +54,7 @@ void ZlibFree(voidpf opaque, voidpf address) plZlibStream::~plZlibStream() { - hsAssert(!fOutput && !fZStream, "plZlibStream not closed"); + Close(); } bool plZlibStream::Open(const plFileName& filename, const char* mode) @@ -62,18 +62,18 @@ bool plZlibStream::Open(const plFileName& filename, const char* mode) fFilename = filename; fMode = mode; - fOutput = new hsUNIXStream; - return fOutput->Open(filename, "wb"); + auto output = std::make_unique(); + if (output->Open(filename, "wb")) { + fOutput = std::move(output); + return true; + } else { + return false; + } } -bool plZlibStream::Close() +void plZlibStream::Close() { - if (fOutput) - { - fOutput->Close(); - delete fOutput; - fOutput = nullptr; - } + fOutput.reset(); if (fZStream) { z_streamp zstream = (z_streamp)fZStream; @@ -81,8 +81,6 @@ bool plZlibStream::Close() delete zstream; fZStream = nullptr; } - - return true; } uint32_t plZlibStream::Write(uint32_t byteCount, const void* buffer) diff --git a/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.h b/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.h index 8ded7cc5be..ddfb2cadc0 100644 --- a/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.h +++ b/Sources/Plasma/PubUtilLib/plCompression/plZlibStream.h @@ -44,14 +44,16 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "hsStream.h" +#include + // // This is for reading a .gz file from a buffer, and writing the uncompressed data to a file. // Call open with the name of the uncompressed file, then call write with the compressed data. // -class plZlibStream : public hsStream +class plZlibStream : public hsFileSystemStream { protected: - hsStream* fOutput; + std::unique_ptr fOutput; void* fZStream; bool fErrorOccurred; bool fDecompressedOk; @@ -60,12 +62,18 @@ class plZlibStream : public hsStream plFileName fFilename; const char* fMode; + void Close(); + public: plZlibStream() : fOutput(), fZStream(), fErrorOccurred(), fDecompressedOk(), fMode() { } + plZlibStream(const plZlibStream& other) = delete; + plZlibStream(plZlibStream&& other) = delete; virtual ~plZlibStream(); + const plZlibStream& operator=(const plZlibStream& other) = delete; + plZlibStream& operator=(plZlibStream&& other) = delete; + bool Open(const plFileName& filename, const char* mode) override; - bool Close() override; uint32_t Write(uint32_t byteCount, const void* buffer) override; // Since most functions don't check the return value from Write, you can diff --git a/Sources/Plasma/PubUtilLib/plDrawable/plDrawableSpansExport.cpp b/Sources/Plasma/PubUtilLib/plDrawable/plDrawableSpansExport.cpp index 9d9de4f7f8..5b840ed92a 100644 --- a/Sources/Plasma/PubUtilLib/plDrawable/plDrawableSpansExport.cpp +++ b/Sources/Plasma/PubUtilLib/plDrawable/plDrawableSpansExport.cpp @@ -184,7 +184,6 @@ void plDrawableSpans::Write( hsStream* s, hsResMgr* mgr ) char buf[256]; sprintf(buf, "Drawable Span: %s, GroupNum: %u\r\n", GetKeyName().c_str(), i); log.WriteString(buf); - log.Close(); #endif fGroups[ i ]->Write( s ); } diff --git a/Sources/Plasma/PubUtilLib/plDrawable/plGBufferGroup.cpp b/Sources/Plasma/PubUtilLib/plDrawable/plGBufferGroup.cpp index ab206d102f..8dcc462546 100644 --- a/Sources/Plasma/PubUtilLib/plDrawable/plGBufferGroup.cpp +++ b/Sources/Plasma/PubUtilLib/plDrawable/plGBufferGroup.cpp @@ -528,11 +528,6 @@ void plGBufferGroup::Write( hsStream *s ) for (const plGBufferCell& cell : fCells[i]) cell.Write(s); } - -#ifdef VERT_LOG - log.Close(); -#endif - // All done! } /////////////////////////////////////////////////////////////////////////////// diff --git a/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.cpp b/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.cpp index fdba009b17..0dcb42a5cc 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.cpp +++ b/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.cpp @@ -71,6 +71,14 @@ plEncryptedStream::plEncryptedStream(uint32_t* key) : plEncryptedStream::~plEncryptedStream() { + if (fOpenMode == kOpenWrite) { + fRAMStream->Rewind(); + IWriteEncypted(fRAMStream.get(), fWriteFileName); + } + + if (fRef) { + fclose(fRef); + } } // @@ -145,7 +153,7 @@ bool plEncryptedStream::Open(const plFileName& name, const char* mode) } else if (strcmp(mode, "wb") == 0) { - fRAMStream = new hsRAMStream; + fRAMStream = std::make_unique(); fWriteFileName = name; fPosition = 0; @@ -162,35 +170,6 @@ bool plEncryptedStream::Open(const plFileName& name, const char* mode) } } -bool plEncryptedStream::Close() -{ - int rtn = false; - - if (fOpenMode == kOpenWrite) - { - fRAMStream->Rewind(); - rtn = IWriteEncypted(fRAMStream, fWriteFileName); - } - if (fRef) - { - rtn = (fclose(fRef) == 0); - fRef = nullptr; - } - - if (fRAMStream) - { - delete fRAMStream; - fRAMStream = nullptr; - } - - fWriteFileName = ST::string(); - fActualFileSize = 0; - fBufferedStream = false; - fOpenMode = kOpenFail; - - return rtn; -} - uint32_t plEncryptedStream::IRead(uint32_t bytes, void* buffer) { if (!fRef) @@ -213,7 +192,7 @@ uint32_t plEncryptedStream::IRead(uint32_t bytes, void* buffer) void plEncryptedStream::IBufferFile() { - fRAMStream = new hsRAMStream; + fRAMStream = std::make_unique(); char buf[1024]; while (!AtEnd()) { @@ -422,30 +401,27 @@ bool plEncryptedStream::IWriteEncypted(hsStream* sourceStream, const plFileName& outputStream.Skip(kMagicStringLen); outputStream.WriteLE32(actualSize); - outputStream.Close(); - return true; } bool plEncryptedStream::FileEncrypt(const plFileName& fileName) { - hsUNIXStream sIn; - if (!sIn.Open(fileName)) - return false; - - // Don't double encrypt any files - if (ICheckMagicString(sIn.GetFILE())) + bool wroteEncrypted; { - sIn.Close(); - return true; - } - sIn.Rewind(); + hsUNIXStream sIn; + if (!sIn.Open(fileName)) + return false; - plEncryptedStream sOut; - bool wroteEncrypted = sOut.IWriteEncypted(&sIn, "crypt.dat"); + // Don't double encrypt any files + if (ICheckMagicString(sIn.GetFILE())) + { + return true; + } + sIn.Rewind(); - sIn.Close(); - sOut.Close(); + plEncryptedStream sOut; + wroteEncrypted = sOut.IWriteEncypted(&sIn, "crypt.dat"); + } if (wroteEncrypted) { @@ -458,27 +434,25 @@ bool plEncryptedStream::FileEncrypt(const plFileName& fileName) bool plEncryptedStream::FileDecrypt(const plFileName& fileName) { - plEncryptedStream sIn; - if (!sIn.Open(fileName)) - return false; - - hsUNIXStream sOut; - if (!sOut.Open("crypt.dat", "wb")) { - sIn.Close(); - return false; - } + plEncryptedStream sIn; + if (!sIn.Open(fileName)) + return false; - char buf[1024]; + hsUNIXStream sOut; + if (!sOut.Open("crypt.dat", "wb")) + { + return false; + } - while (!sIn.AtEnd()) - { - uint32_t numRead = sIn.Read(sizeof(buf), buf); - sOut.Write(numRead, buf); - } + char buf[1024]; - sIn.Close(); - sOut.Close(); + while (!sIn.AtEnd()) + { + uint32_t numRead = sIn.Read(sizeof(buf), buf); + sOut.Write(numRead, buf); + } + } plFileSystem::Unlink(fileName); plFileSystem::Move("crypt.dat", fileName); @@ -507,28 +481,28 @@ bool plEncryptedStream::IsEncryptedFile(const plFileName& fileName) return isEncrypted; } -hsStream* plEncryptedStream::OpenEncryptedFile(const plFileName& fileName, uint32_t* cryptKey) +std::unique_ptr plEncryptedStream::OpenEncryptedFile(const plFileName& fileName, uint32_t* cryptKey) { bool isEncrypted = IsEncryptedFile(fileName); - hsStream* s = nullptr; + std::unique_ptr s; if (isEncrypted) - s = new plEncryptedStream(cryptKey); + s = std::make_unique(cryptKey); else - s = new hsUNIXStream; + s = std::make_unique(); s->Open(fileName, "rb"); return s; } -hsStream* plEncryptedStream::OpenEncryptedFileWrite(const plFileName& fileName, uint32_t* cryptKey) +std::unique_ptr plEncryptedStream::OpenEncryptedFileWrite(const plFileName& fileName, uint32_t* cryptKey) { - hsStream* s = nullptr; + std::unique_ptr s; if (IsEncryptedFile(fileName)) - s = new plEncryptedStream(cryptKey); + s = std::make_unique(cryptKey); else - s = new hsUNIXStream; + s = std::make_unique(); s->Open(fileName, "wb"); return s; diff --git a/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.h b/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.h index a978c1a80f..bd9c24d934 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.h +++ b/Sources/Plasma/PubUtilLib/plFile/plEncryptedStream.h @@ -44,12 +44,14 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "hsStream.h" +#include + // // Encrypt a large file by running FileEncrypt on it. Small files can be done // in the usual way, but they will be in memory until Close is called. Files // will be decrypted on the fly during read.operations // -class plEncryptedStream : public hsStream +class plEncryptedStream : public hsFileSystemStream { protected: FILE* fRef; @@ -59,7 +61,7 @@ class plEncryptedStream : public hsStream bool fBufferedStream; - hsStream* fRAMStream; + std::unique_ptr fRAMStream; plFileName fWriteFileName; @@ -80,10 +82,14 @@ class plEncryptedStream : public hsStream public: // If you don't pass in a key (4 uint32_t's), the default one will be used plEncryptedStream(uint32_t* key=nullptr); + plEncryptedStream(const plEncryptedStream& other) = delete; + plEncryptedStream(plEncryptedStream&& other) = delete; ~plEncryptedStream(); + const plEncryptedStream& operator=(const plEncryptedStream& other) = delete; + plEncryptedStream& operator=(plEncryptedStream&& other) = delete; + bool Open(const plFileName& name, const char* mode = "rb") override; - bool Close() override; uint32_t Read(uint32_t byteCount, void* buffer) override; uint32_t Write(uint32_t byteCount, const void* buffer) override; @@ -102,10 +108,9 @@ class plEncryptedStream : public hsStream static bool IsEncryptedFile(const plFileName& fileName); // Attempts to create a read-binary stream for the requested file. If it's - // encrypted, you'll get a plEncryptedStream, otherwise just a standard - // hsUNIXStream. Remember to delete the stream when you're done with it. - static hsStream* OpenEncryptedFile(const plFileName& fileName, uint32_t* cryptKey = nullptr); - static hsStream* OpenEncryptedFileWrite(const plFileName& fileName, uint32_t* cryptKey = nullptr); + // encrypted, you'll get a plEncryptedStream, otherwise just a standard hsUNIXStream. + static std::unique_ptr OpenEncryptedFile(const plFileName& fileName, uint32_t* cryptKey = nullptr); + static std::unique_ptr OpenEncryptedFileWrite(const plFileName& fileName, uint32_t* cryptKey = nullptr); }; #endif // plEncryptedStream_h_inc diff --git a/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.cpp b/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.cpp index d2ce86df3e..c48b6bd2d1 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.cpp +++ b/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.cpp @@ -79,19 +79,21 @@ void plInitFileReader::IInitReaders( plInitSectionReader **readerArray ) } plInitFileReader::plInitFileReader( plInitSectionReader **readerArray, uint16_t lineSize ) + : fOurStream() { fCurrLine = nullptr; fLineSize = lineSize; - fStream = fOurStream = nullptr; + fStream = nullptr; IInitReaders( readerArray ); fUnhandledSection = nullptr; } plInitFileReader::plInitFileReader( const char *fileName, plInitSectionReader **readerArray, uint16_t lineSize ) + : fOurStream() { fCurrLine = nullptr; fLineSize = lineSize; - fStream = fOurStream = nullptr; + fStream = nullptr; IInitReaders( readerArray ); if( !Open( fileName ) ) hsAssert( false, "Constructor open for plInitFileReader failed!" ); @@ -99,10 +101,11 @@ plInitFileReader::plInitFileReader( const char *fileName, plInitSectionReader ** } plInitFileReader::plInitFileReader( hsStream *stream, plInitSectionReader **readerArray, uint16_t lineSize ) + : fOurStream() { fCurrLine = nullptr; fLineSize = lineSize; - fStream = fOurStream = nullptr; + fStream = nullptr; IInitReaders( readerArray ); if( !Open( stream ) ) hsAssert( false, "Constructor open for plInitFileReader failed!" ); @@ -111,7 +114,6 @@ plInitFileReader::plInitFileReader( hsStream *stream, plInitSectionReader **read plInitFileReader::~plInitFileReader() { - Close(); delete [] fCurrLine; } @@ -128,7 +130,7 @@ bool plInitFileReader::Open( const char *fileName ) if (fOurStream == nullptr) return false; - fStream = fOurStream; + fStream = fOurStream.get(); return true; } @@ -192,19 +194,3 @@ bool plInitFileReader::Parse( uint32_t userData ) return true; } - -void plInitFileReader::Close() -{ - if (fStream == nullptr) - return; - - if( fStream == fOurStream ) - { - fStream->Close(); - delete fOurStream; - fOurStream = nullptr; - } - - fStream = nullptr; -} - diff --git a/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.h b/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.h index d402572ffa..52ab7f3119 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.h +++ b/Sources/Plasma/PubUtilLib/plFile/plInitFileReader.h @@ -64,6 +64,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "HeadSpin.h" #include "hsStream.h" + +#include #include //// Base Section Class ////////////////////////////////////////////////////// @@ -115,7 +117,7 @@ class plInitFileReader protected: hsStream *fStream; - hsStream *fOurStream; + std::unique_ptr fOurStream; char *fCurrLine; uint32_t fLineSize; @@ -142,7 +144,6 @@ class plInitFileReader bool Open( const char *fileName ); bool Open( hsStream *stream ); bool Parse( uint32_t userData = 0 ); - void Close(); bool IsOpen() const { return fStream != nullptr; } }; diff --git a/Sources/Plasma/PubUtilLib/plFile/plSecureStream.cpp b/Sources/Plasma/PubUtilLib/plFile/plSecureStream.cpp index 7efec02bc0..e1aed99d69 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plSecureStream.cpp +++ b/Sources/Plasma/PubUtilLib/plFile/plSecureStream.cpp @@ -95,6 +95,18 @@ fDeleteOnExit(false) plSecureStream::~plSecureStream() { + if (fOpenMode == kOpenWrite) { + fRAMStream->Rewind(); + IWriteEncrypted(fRAMStream.get(), fWriteFileName); + } + + if (fRef != INVALID_HANDLE_VALUE) { +#if defined(HS_BUILD_FOR_WIN32) + CloseHandle(fRef); +#elif defined(HS_BUILD_FOR_UNIX) + fclose(fRef); +#endif + } } // @@ -217,7 +229,7 @@ bool plSecureStream::Open(const plFileName& name, const char* mode) } else if (strcmp(mode, "wb") == 0) { - fRAMStream = new hsRAMStream; + fRAMStream = std::make_unique(); fWriteFileName = name; fPosition = 0; @@ -243,7 +255,7 @@ bool plSecureStream::Open(hsStream* stream) fActualFileSize = stream->ReadLE32(); uint32_t trimSize = kMagicStringLen + sizeof(uint32_t) + fActualFileSize; - fRAMStream = new hsRAMStream; + fRAMStream = std::make_unique(); while (!stream->AtEnd()) { // Don't write out any garbage @@ -267,39 +279,6 @@ bool plSecureStream::Open(hsStream* stream) return true; } -bool plSecureStream::Close() -{ - int rtn = false; - - if (fOpenMode == kOpenWrite) - { - fRAMStream->Rewind(); - rtn = IWriteEncrypted(fRAMStream, fWriteFileName); - } - if (fRef != INVALID_HANDLE_VALUE) - { -#if HS_BUILD_FOR_WIN32 - rtn = CloseHandle(fRef); -#elif HS_BUILD_FOR_UNIX - rtn = fclose(fRef); -#endif - fRef = INVALID_HANDLE_VALUE; - } - - if (fRAMStream) - { - delete fRAMStream; - fRAMStream = nullptr; - } - - fWriteFileName = ST::string(); - fActualFileSize = 0; - fBufferedStream = false; - fOpenMode = kOpenFail; - - return rtn; -} - uint32_t plSecureStream::IRead(uint32_t bytes, void* buffer) { if (fRef == INVALID_HANDLE_VALUE) @@ -335,7 +314,7 @@ uint32_t plSecureStream::IRead(uint32_t bytes, void* buffer) void plSecureStream::IBufferFile() { - fRAMStream = new hsRAMStream; + fRAMStream = std::make_unique(); char buf[1024]; while (!AtEnd()) { @@ -559,30 +538,27 @@ bool plSecureStream::IWriteEncrypted(hsStream* sourceStream, const plFileName& o outputStream.Skip(kMagicStringLen); outputStream.WriteLE32(actualSize); - outputStream.Close(); - return true; } bool plSecureStream::FileEncrypt(const plFileName& fileName, uint32_t* key /* = nullptr */) { - hsUNIXStream sIn; - if (!sIn.Open(fileName)) - return false; - - // Don't double encrypt any files - if (ICheckMagicString(sIn.GetFILE())) + bool wroteEncrypted; { - sIn.Close(); - return true; - } - sIn.Rewind(); + hsUNIXStream sIn; + if (!sIn.Open(fileName)) + return false; - plSecureStream sOut(false, key); - bool wroteEncrypted = sOut.IWriteEncrypted(&sIn, "crypt.dat"); + // Don't double encrypt any files + if (ICheckMagicString(sIn.GetFILE())) + { + return true; + } + sIn.Rewind(); - sIn.Close(); - sOut.Close(); + plSecureStream sOut(false, key); + wroteEncrypted = sOut.IWriteEncrypted(&sIn, "crypt.dat"); + } if (wroteEncrypted) { @@ -595,27 +571,25 @@ bool plSecureStream::FileEncrypt(const plFileName& fileName, uint32_t* key /* = bool plSecureStream::FileDecrypt(const plFileName& fileName, uint32_t* key /* = nullptr */) { - plSecureStream sIn(false, key); - if (!sIn.Open(fileName)) - return false; - - hsUNIXStream sOut; - if (!sOut.Open("crypt.dat", "wb")) { - sIn.Close(); - return false; - } + plSecureStream sIn(false, key); + if (!sIn.Open(fileName)) + return false; - char buf[1024]; + hsUNIXStream sOut; + if (!sOut.Open("crypt.dat", "wb")) + { + return false; + } - while (!sIn.AtEnd()) - { - uint32_t numRead = sIn.Read(sizeof(buf), buf); - sOut.Write(numRead, buf); - } + char buf[1024]; - sIn.Close(); - sOut.Close(); + while (!sIn.AtEnd()) + { + uint32_t numRead = sIn.Read(sizeof(buf), buf); + sOut.Write(numRead, buf); + } + } plFileSystem::Unlink(fileName); plFileSystem::Move("crypt.dat", fileName); @@ -674,30 +648,30 @@ bool plSecureStream::IsSecureFile(const plFileName& fileName) return isEncrypted; } -hsStream* plSecureStream::OpenSecureFile(const plFileName& fileName, const uint32_t flags /* = kRequireEncryption */, uint32_t* key /* = nullptr */) +std::unique_ptr plSecureStream::OpenSecureFile(const plFileName& fileName, const uint32_t flags /* = kRequireEncryption */, uint32_t* key /* = nullptr */) { bool requireEncryption = flags & kRequireEncryption; bool deleteOnExit = flags & kDeleteOnExit; bool isEncrypted = IsSecureFile(fileName); - hsStream* s = nullptr; + std::unique_ptr s; if (isEncrypted) - s = new plSecureStream(deleteOnExit, key); + s = std::make_unique(deleteOnExit, key); else if (!requireEncryption) - s = new hsUNIXStream; + s = std::make_unique(); if (s) s->Open(fileName, "rb"); return s; } -hsStream* plSecureStream::OpenSecureFileWrite(const plFileName& fileName, uint32_t* key /* = nullptr */) +std::unique_ptr plSecureStream::OpenSecureFileWrite(const plFileName& fileName, uint32_t* key /* = nullptr */) { - hsStream* s = nullptr; + std::unique_ptr s; #ifdef PLASMA_EXTERNAL_RELEASE - s = new plSecureStream(false, key); + s = std::make_unique(false, key); #else - s = new hsUNIXStream; + s = std::make_unique(); #endif s->Open(fileName, "wb"); @@ -721,8 +695,6 @@ bool plSecureStream::GetSecureEncryptionKey(const plFileName& filename, uint32_t uint8_t* buffer = (uint8_t*)malloc(bytesToRead); unsigned bytesRead = file.Read(bytesToRead, buffer); - file.Close(); - unsigned memSize = std::min(bytesToRead, bytesRead); memcpy(key, buffer, memSize); free(buffer); diff --git a/Sources/Plasma/PubUtilLib/plFile/plSecureStream.h b/Sources/Plasma/PubUtilLib/plFile/plSecureStream.h index c568a4ec6d..2984e446d8 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plSecureStream.h +++ b/Sources/Plasma/PubUtilLib/plFile/plSecureStream.h @@ -45,6 +45,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "HeadSpin.h" #include "hsStream.h" +#include + #if HS_BUILD_FOR_WIN32 typedef void* HANDLE; # define hsFD HANDLE @@ -57,7 +59,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com // to download the file from a server into a temporary directory (with a mangled name) and // delete that file on close, thereby minimizing the chance of having that file examined or // edited. -class plSecureStream: public hsStream +class plSecureStream : public hsFileSystemStream { protected: hsFD fRef; @@ -67,7 +69,7 @@ class plSecureStream: public hsStream bool fBufferedStream; - hsStream* fRAMStream; + std::unique_ptr fRAMStream; plFileName fWriteFileName; @@ -91,11 +93,15 @@ class plSecureStream: public hsStream public: plSecureStream(bool deleteOnExit = false, uint32_t* key = nullptr); // uses default key if you don't pass one in plSecureStream(hsStream* base, uint32_t* key = nullptr); + plSecureStream(const plSecureStream& other) = delete; + plSecureStream(plSecureStream&& other) = delete; ~plSecureStream(); + const plSecureStream& operator=(const plSecureStream& other) = delete; + plSecureStream& operator=(plSecureStream&& other) = delete; + bool Open(const plFileName& name, const char* mode = "rb") override; bool Open(hsStream* stream); - bool Close() override; uint32_t Read(uint32_t byteCount, void* buffer) override; uint32_t Write(uint32_t byteCount, const void* buffer) override; @@ -119,12 +125,10 @@ class plSecureStream: public hsStream static bool IsSecureFile(const plFileName& fileName); - // Attempts to create a read-binary stream for the requested file (delete the stream - // when you are done with it!) - static hsStream* OpenSecureFile(const plFileName& fileName, const uint32_t flags = kRequireEncryption, uint32_t* key = nullptr); - // Attempts to create a write-binary stream for the requested file (delete the stream - // when you are done with it!) - static hsStream* OpenSecureFileWrite(const plFileName& fileName, uint32_t* key = nullptr); + // Attempts to create a read-binary stream for the requested file + static std::unique_ptr OpenSecureFile(const plFileName& fileName, const uint32_t flags = kRequireEncryption, uint32_t* key = nullptr); + // Attempts to create a write-binary stream for the requested file + static std::unique_ptr OpenSecureFileWrite(const plFileName& fileName, uint32_t* key = nullptr); static const uint32_t kDefaultKey[4]; // our default encryption key diff --git a/Sources/Plasma/PubUtilLib/plFile/plStreamSource.cpp b/Sources/Plasma/PubUtilLib/plFile/plStreamSource.cpp index 750265074c..a512e630d6 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plStreamSource.cpp +++ b/Sources/Plasma/PubUtilLib/plFile/plStreamSource.cpp @@ -46,6 +46,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "plEncryptedStream.h" #include "hsLockGuard.h" +#include + #if HS_BUILD_FOR_UNIX # include #endif @@ -58,16 +60,6 @@ plStreamSource::plStreamSource() void plStreamSource::ICleanup() { hsLockGuard(fMutex); - - // loop through all the file data records, and delete the streams - decltype(fFileData.begin()) curData; - for (curData = fFileData.begin(); curData != fFileData.end(); curData++) - { - curData->second.fStream->Close(); - delete curData->second.fStream; - curData->second.fStream = nullptr; - } - fFileData.clear(); } @@ -88,25 +80,25 @@ hsStream* plStreamSource::GetFile(const plFileName& filename) fFileData[sFilename].fExt = sFilename.GetFileExt(); if (plSecureStream::IsSecureFile(filename)) { - hsStream* ss = nullptr; + std::unique_ptr ss; uint32_t encryptionKey[4]; if (plSecureStream::GetSecureEncryptionKey(filename, encryptionKey, 4)) ss = plSecureStream::OpenSecureFile(filename, 0, encryptionKey); else ss = plSecureStream::OpenSecureFile(filename, 0, fServerKey); - fFileData[sFilename].fStream = ss; hsAssert(ss, "failed to open a SecureStream for a disc file!"); + fFileData[sFilename].fStream = std::move(ss); } else // otherwise it is an encrypted or plain stream, this call handles both fFileData[sFilename].fStream = plEncryptedStream::OpenEncryptedFile(filename); - return fFileData[sFilename].fStream; + return fFileData[sFilename].fStream.get(); } #endif // PLASMA_EXTERNAL_RELEASE return nullptr; } - return fFileData[sFilename].fStream; + return fFileData[sFilename].fStream.get(); } std::vector plStreamSource::GetListOfNames(const plFileName& dir, const ST::string& ext) @@ -139,7 +131,7 @@ std::vector plStreamSource::GetListOfNames(const plFileName& dir, co return retVal; } -bool plStreamSource::InsertFile(const plFileName& filename, hsStream* stream) +bool plStreamSource::InsertFile(const plFileName& filename, std::unique_ptr&& stream) { plFileName sFilename = filename.Normalize('/'); @@ -151,7 +143,7 @@ bool plStreamSource::InsertFile(const plFileName& filename, hsStream* stream) fFileData[sFilename].fFilename = sFilename; fFileData[sFilename].fDir = sFilename.StripFileName(); fFileData[sFilename].fExt = sFilename.GetFileExt(); - fFileData[sFilename].fStream = stream; + fFileData[sFilename].fStream = std::move(stream); return true; } diff --git a/Sources/Plasma/PubUtilLib/plFile/plStreamSource.h b/Sources/Plasma/PubUtilLib/plFile/plStreamSource.h index 30bfe2d7f4..838843dcde 100644 --- a/Sources/Plasma/PubUtilLib/plFile/plStreamSource.h +++ b/Sources/Plasma/PubUtilLib/plFile/plStreamSource.h @@ -43,6 +43,7 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #define plStreamSource_h_inc #include +#include #include #include "hsStream.h" @@ -57,7 +58,7 @@ class plStreamSource plFileName fFilename; // includes path plFileName fDir; // parent directory ST::string fExt; - hsStream* fStream; // we own this pointer, so clean it up + std::unique_ptr fStream; }; std::map fFileData; // key is filename std::mutex fMutex; @@ -77,7 +78,7 @@ class plStreamSource std::vector GetListOfNames(const plFileName& dir, const ST::string& ext); // internal builds merge from disk // For other classes to insert files (takes ownership of the stream if successful) - bool InsertFile(const plFileName& filename, hsStream* stream); + bool InsertFile(const plFileName& filename, std::unique_ptr&& stream); /** Gets a pointer to our encryption key */ uint32_t* GetEncryptionKey() { return fServerKey; } diff --git a/Sources/Plasma/PubUtilLib/plGImage/plJPEG.cpp b/Sources/Plasma/PubUtilLib/plGImage/plJPEG.cpp index f4cd3fca1a..e31379fe89 100644 --- a/Sources/Plasma/PubUtilLib/plGImage/plJPEG.cpp +++ b/Sources/Plasma/PubUtilLib/plGImage/plJPEG.cpp @@ -242,9 +242,7 @@ plMipmap* plJPEG::ReadFromFile( const plFileName &fileName ) delete [] tempbuffer; tempstream.Rewind(); - plMipmap* ret = IRead(&tempstream); - in.Close(); - return ret; + return IRead(&tempstream); } //// IWrite /////////////////////////////////////////////////////////////////// @@ -360,7 +358,6 @@ bool plJPEG::WriteToFile( const plFileName &fileName, plMipmap *sourceData ) delete [] tempbuffer; } - out.Close(); return ret; } diff --git a/Sources/Plasma/PubUtilLib/plGImage/plMipmap.cpp b/Sources/Plasma/PubUtilLib/plGImage/plMipmap.cpp index 21536f363a..28dfdfb6f6 100644 --- a/Sources/Plasma/PubUtilLib/plGImage/plMipmap.cpp +++ b/Sources/Plasma/PubUtilLib/plGImage/plMipmap.cpp @@ -559,16 +559,20 @@ void plMipmap::IWriteJPEGImage( hsStream *stream ) plMipmap *alpha = ISplitAlpha(); uint8_t flags = 0; - hsNullStream *nullStream = new hsNullStream(); - IWriteRLEImage(nullStream,this); - if (nullStream->GetPosition() < 5120) // we use RLE if it can get the image size under 5k, otherwise we use JPEG - flags |= kColorDataRLE; - delete nullStream; - nullStream = new hsNullStream(); - IWriteRLEImage(nullStream,alpha); - if (nullStream->GetPosition() < 5120) - flags |= kAlphaDataRLE; - delete nullStream; + { + hsNullStream nullStream; + IWriteRLEImage(&nullStream, this); + if (nullStream.GetPosition() < 5120) // we use RLE if it can get the image size under 5k, otherwise we use JPEG + flags |= kColorDataRLE; + } + + { + hsNullStream nullStream; + IWriteRLEImage(&nullStream, alpha); + if (nullStream.GetPosition() < 5120) + flags |= kAlphaDataRLE; + } + stream->WriteByte(flags); if (flags & kColorDataRLE) diff --git a/Sources/Plasma/PubUtilLib/plGImage/plPNG.cpp b/Sources/Plasma/PubUtilLib/plGImage/plPNG.cpp index e7d4df05b9..bc53256ce8 100644 --- a/Sources/Plasma/PubUtilLib/plGImage/plPNG.cpp +++ b/Sources/Plasma/PubUtilLib/plGImage/plPNG.cpp @@ -187,9 +187,7 @@ plMipmap* plPNG::ReadFromFile(const plFileName& fileName) return nullptr; } - plMipmap* ret = IRead(&in); - in.Close(); - return ret; + return IRead(&in); } bool plPNG::IWrite(plMipmap* source, hsStream* outStream, const std::multimap& textFields) @@ -293,7 +291,5 @@ bool plPNG::WriteToFile(const plFileName& fileName, plMipmap* sourceData, const return false; } - bool ret = IWrite(sourceData, &out, textFields); - out.Close(); - return ret; + return IWrite(sourceData, &out, textFields); } diff --git a/Sources/Plasma/PubUtilLib/plGImage/plTGAWriter.cpp b/Sources/Plasma/PubUtilLib/plGImage/plTGAWriter.cpp index 1767b33620..53c06b58ed 100644 --- a/Sources/Plasma/PubUtilLib/plGImage/plTGAWriter.cpp +++ b/Sources/Plasma/PubUtilLib/plGImage/plTGAWriter.cpp @@ -105,8 +105,5 @@ void plTGAWriter::WriteMipmap( const char *fileName, plMipmap *mipmap ) stream.WriteByte( pixel.r ); } } - - /// All done! - stream.Close(); } diff --git a/Sources/Plasma/PubUtilLib/plNetClient/plNetClientMgr.cpp b/Sources/Plasma/PubUtilLib/plNetClient/plNetClientMgr.cpp index 8183ef8e08..54603d5329 100644 --- a/Sources/Plasma/PubUtilLib/plNetClient/plNetClientMgr.cpp +++ b/Sources/Plasma/PubUtilLib/plNetClient/plNetClientMgr.cpp @@ -1342,15 +1342,13 @@ plUoid plNetClientMgr::GetAgeSDLObjectUoid(const ST::string& ageName) const if (!loc.IsValid()) { // try to load age desc - hsStream* stream=plAgeLoader::GetAgeDescFileStream(ageName); + std::unique_ptr stream = plAgeLoader::GetAgeDescFileStream(ageName); if (stream) { plAgeDescription ad; - ad.Read(stream); + ad.Read(stream.get()); loc=ad.CalcPageLocation("BuiltIn"); - stream->Close(); - } - delete stream; + } } } diff --git a/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientRecorder.h b/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientRecorder.h index f405210e74..233effb23c 100644 --- a/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientRecorder.h +++ b/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientRecorder.h @@ -44,6 +44,8 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "HeadSpin.h" +#include + class hsStream; class plNetMessage; class plStatusLog; @@ -114,7 +116,7 @@ class plNetClientLoggingRecorder : public plNetClientRecorder class plNetClientStreamRecorder : public plNetClientLoggingRecorder { protected: - hsStream* fRecordStream; + std::unique_ptr fRecordStream; hsResMgr* fResMgr; diff --git a/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientStreamRecorder.cpp b/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientStreamRecorder.cpp index a1c7d29bdb..9764e72f84 100644 --- a/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientStreamRecorder.cpp +++ b/Sources/Plasma/PubUtilLib/plNetClientRecorder/plNetClientStreamRecorder.cpp @@ -70,13 +70,7 @@ plNetClientStreamRecorder::plNetClientStreamRecorder(TimeWrapper* timeWrapper) : plNetClientStreamRecorder::~plNetClientStreamRecorder() -{ - if (fRecordStream) - { - fRecordStream->Close(); - delete fRecordStream; - } -} +{} hsResMgr* plNetClientStreamRecorder::GetResMgr() { @@ -100,22 +94,21 @@ bool plNetClientStreamRecorder::BeginRecording(const char* recName) { if (!fRecordStream) { - fRecordStream = new hsUNIXStream; char path[256]; IMakeFilename(recName, path); - if (!fRecordStream->Open(path, "wb")) - { - delete fRecordStream; + auto newStream = std::make_unique(); + if (!newStream->Open(path, "wb")) { return false; } + fRecordStream = std::move(newStream); hsBitVector contentFlags; contentFlags.SetBit(kNetClientRecSDLDesc); - contentFlags.Write(fRecordStream); + contentFlags.Write(fRecordStream.get()); // kNetClientRecSDLDesc - plSDLMgr::GetInstance()->Write(fRecordStream); + plSDLMgr::GetInstance()->Write(fRecordStream.get()); return true; } @@ -127,26 +120,22 @@ bool plNetClientStreamRecorder::BeginPlayback(const char* recName) { if (!fRecordStream) { - fRecordStream = new hsUNIXStream; char path[256]; IMakeFilename(recName, path); - if (fRecordStream->Open(path, "rb")) - { + auto newStream = std::make_unique(); + if (newStream->Open(path, "rb")) { + fRecordStream = std::move(newStream); hsBitVector contentFlags; - contentFlags.Read(fRecordStream); + contentFlags.Read(fRecordStream.get()); if (contentFlags.IsBitSet(kNetClientRecSDLDesc)) - plSDLMgr::GetInstance()->Read(fRecordStream); + plSDLMgr::GetInstance()->Read(fRecordStream.get()); fPlaybackTimeOffset = GetTime(); fNextPlaybackTime = fRecordStream->ReadLEDouble(); fBetweenAges = false; - } - else - { - delete fRecordStream; - fRecordStream = nullptr; + } else { return false; } @@ -164,7 +153,7 @@ void plNetClientStreamRecorder::RecordMsg(plNetMessage* msg, double secs) if (IProcessRecordMsg(msg,secs)) { fRecordStream->WriteLEDouble(secs - fPlaybackTimeOffset); - GetResMgr()->WriteCreatableVersion(fRecordStream, msg); + GetResMgr()->WriteCreatableVersion(fRecordStream.get(), msg); ILogMsg(msg); } @@ -211,7 +200,7 @@ plNetMessage* plNetClientStreamRecorder::IGetNextMessage() if (!IsQueueEmpty() && GetNextMessageTimeDelta() <= 0 ) { - msg = plNetMessage::ConvertNoRef(GetResMgr()->ReadCreatableVersion(fRecordStream)); + msg = plNetMessage::ConvertNoRef(GetResMgr()->ReadCreatableVersion(fRecordStream.get())); // msg->SetPeeked(true); // Fix the flags on game messages, so we won't get an assert later @@ -239,9 +228,7 @@ plNetMessage* plNetClientStreamRecorder::IGetNextMessage() // If this was the last message, stop playing back if (fRecordStream->AtEnd()) { - fRecordStream->Close(); - delete fRecordStream; - fRecordStream = nullptr; + fRecordStream.reset(); } } diff --git a/Sources/Plasma/PubUtilLib/plNetMessage/plNetMessage.cpp b/Sources/Plasma/PubUtilLib/plNetMessage/plNetMessage.cpp index 6ddfcb5ee8..0870a1c787 100644 --- a/Sources/Plasma/PubUtilLib/plNetMessage/plNetMessage.cpp +++ b/Sources/Plasma/PubUtilLib/plNetMessage/plNetMessage.cpp @@ -139,9 +139,8 @@ plNetMessage* plNetMessage::Create(const plNetCommonMessage* msg) { if (msg) { - hsReadOnlyStream readStream; ClassIndexType classIndex; - readStream.Init(sizeof(classIndex), msg->GetData()); + hsReadOnlyStream readStream(sizeof(classIndex), msg->GetData()); readStream.ReadLE16(&classIndex); if (!plFactory::IsValidClassIndex(classIndex)) return nullptr; @@ -170,8 +169,7 @@ int plNetMessage::PokeBuffer(char* bufIn, int bufLen, uint32_t peekOptions) memset(bufIn, 0, bufLen); ValidatePoke(); - hsWriteOnlyStream writeStream; - writeStream.Init(bufLen, bufIn); + hsWriteOnlyStream writeStream(bufLen, bufIn); int ret; if (peekOptions & kBaseClassOnly) { @@ -199,8 +197,7 @@ int plNetMessage::PeekBuffer(const char* bufIn, int bufLen, uint32_t peekOptions // set peek status based on peekOptions fPeekStatus = partialPeekOptions ? partialPeekOptions : kFullyPeeked; - hsReadOnlyStream readStream; - readStream.Init(bufLen, bufIn); + hsReadOnlyStream readStream(bufLen, bufIn); int ret; if (peekOptions & kBaseClassOnly) { diff --git a/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.cpp b/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.cpp index b66ab8dbb9..15f79c1072 100644 --- a/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.cpp +++ b/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.cpp @@ -42,23 +42,28 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #include "plRegistryNode.h" +#include "hsStream.h" #include "plRegistryHelpers.h" #include "plRegistryKeyList.h" #include "plVersion.h" #include "pnKeyedObject/plKeyImp.h" +plRegistryPageNode::plRegistryPageNode() +{} + plRegistryPageNode::plRegistryPageNode(const plFileName& path) : fValid(kPageCorrupt) , fPath(path) , fLoadedTypes(0) + , fStream(nullptr) , fOpenRequests(0) , fIsNewPage(false) { hsStream* stream = OpenStream(); if (stream) { - fPageInfo.Read(&fStream); + fPageInfo.Read(stream); fValid = IVerify(); CloseStream(); } @@ -69,6 +74,7 @@ plRegistryPageNode::plRegistryPageNode(const plLocation& location, const ST::str : fValid(kPageOk) , fPageInfo(location) , fLoadedTypes(0) + , fStream(nullptr) , fOpenRequests(0) , fIsNewPage(true) { @@ -124,11 +130,15 @@ hsStream* plRegistryPageNode::OpenStream() { if (fOpenRequests == 0) { - if (!fStream.Open(fPath, "rb")) + hsAssert(fStream == nullptr, "plRegistryPageNode::fStream should be nullptr when not open!"); + auto stream = std::make_unique(); + if (!stream->Open(fPath, "rb")) { return nullptr; + } + fStream = std::move(stream); } fOpenRequests++; - return &fStream; + return fStream.get(); } void plRegistryPageNode::CloseStream() @@ -136,8 +146,9 @@ void plRegistryPageNode::CloseStream() if (fOpenRequests > 0) fOpenRequests--; - if (fOpenRequests == 0) - fStream.Close(); + if (fOpenRequests == 0) { + fStream.reset(); + } } void plRegistryPageNode::LoadKeys() @@ -212,9 +223,11 @@ class plWriteIterator : public plRegistryKeyIterator void plRegistryPageNode::Write() { + hsAssert(fStream == nullptr, "Trying to write while the page is open for reading"); hsAssert(fOpenRequests == 0, "Trying to write while the page is open for reading"); - if (!fStream.Open(fPath, "wb")) + hsBufferedStream stream; + if (!stream.Open(fPath, "wb")) { hsAssert(0, "Couldn't open file for writing"); return; @@ -233,31 +246,29 @@ void plRegistryPageNode::Write() } // First thing we write is the pageinfo. Later we'll rewind and overwrite this with the final values - fPageInfo.Write(&fStream); + fPageInfo.Write(&stream); - fPageInfo.SetDataStart(fStream.GetPosition()); + fPageInfo.SetDataStart(stream.GetPosition()); // Write all our objects - plWriteIterator writer(&fStream); + plWriteIterator writer(&stream); IterateKeys(&writer); - fPageInfo.SetIndexStart(fStream.GetPosition()); + fPageInfo.SetIndexStart(stream.GetPosition()); // Write our keys - fStream.WriteLE32((uint32_t)fKeyLists.size()); + stream.WriteLE32((uint32_t)fKeyLists.size()); for (it = fKeyLists.begin(); it != fKeyLists.end(); it++) { plRegistryKeyList* keyList = it->second; - fStream.WriteLE16(keyList->GetClassType()); - keyList->Write(&fStream); + stream.WriteLE16(keyList->GetClassType()); + keyList->Write(&stream); } // Rewind and write the pageinfo with the correct data and index offsets - fStream.Rewind(); - fPageInfo.SetChecksum(fStream.GetEOF() - fPageInfo.GetDataStart()); - fPageInfo.Write(&fStream); - - fStream.Close(); + stream.Rewind(); + fPageInfo.SetChecksum(stream.GetEOF() - fPageInfo.GetDataStart()); + fPageInfo.Write(&stream); } //// IterateKeys ///////////////////////////////////////////////////////////// diff --git a/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.h b/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.h index ba8348da3e..de466b37ed 100644 --- a/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.h +++ b/Sources/Plasma/PubUtilLib/plResMgr/plRegistryNode.h @@ -43,11 +43,13 @@ You can contact Cyan Worlds, Inc. by email legal@cyan.com #define plRegistryNode_h_inc #include "HeadSpin.h" -#include "hsStream.h" +#include "plFileSystem.h" #include "plPageInfo.h" #include +#include +class hsStream; class plRegistryKeyList; class plKeyImp; class plRegistryKeyIterator; @@ -78,12 +80,12 @@ class plRegistryPageNode plFileName fPath; // Path to the page file plPageInfo fPageInfo; // Info about this page - hsBufferedStream fStream; // Stream for reading/writing our page + std::unique_ptr fStream; // Stream for reading/writing our page uint8_t fOpenRequests; // How many handles there are to fStream (or // zero if it's closed) bool fIsNewPage; // True if this page is new (not read off disk) - plRegistryPageNode() {} + plRegistryPageNode(); plRegistryKeyList* IGetKeyList(uint16_t classType) const; PageCond IVerify(); diff --git a/Sources/Plasma/PubUtilLib/plStatGather/plProfileManagerFull.cpp b/Sources/Plasma/PubUtilLib/plStatGather/plProfileManagerFull.cpp index a86694f62b..535e83adb8 100644 --- a/Sources/Plasma/PubUtilLib/plStatGather/plProfileManagerFull.cpp +++ b/Sources/Plasma/PubUtilLib/plStatGather/plProfileManagerFull.cpp @@ -483,8 +483,6 @@ void plProfileManagerFull::ILogStats() } s.WriteByte((uint8_t)'\r'); s.WriteByte((uint8_t)'\n'); - - s.Close(); } fLogStats = false; diff --git a/Sources/Tools/MaxComponent/plAudioComponents.cpp b/Sources/Tools/MaxComponent/plAudioComponents.cpp index 6795a3a5f3..c3dd5a348c 100644 --- a/Sources/Tools/MaxComponent/plAudioComponents.cpp +++ b/Sources/Tools/MaxComponent/plAudioComponents.cpp @@ -3043,9 +3043,6 @@ void plEAXListenerComponent::SetCustFile( const MCHAR* path ) hsAssert( false, "Couldn't find all of the keywords in the settings file. Oh well" ); } - // All done! - presetFile.Close(); - // Update our helper reminder string _tsplitpath(path, nullptr, nullptr, file, nullptr); fCompPB->SetValue( (ParamID)kRefCustFile, 0, file ); diff --git a/Sources/Tools/MaxComponent/plMultistageBehComponent.cpp b/Sources/Tools/MaxComponent/plMultistageBehComponent.cpp index a26c8f2190..f08d07c21e 100644 --- a/Sources/Tools/MaxComponent/plMultistageBehComponent.cpp +++ b/Sources/Tools/MaxComponent/plMultistageBehComponent.cpp @@ -485,10 +485,12 @@ class MaxStream : public hsStream public: MaxStream(ISave* isave) : fSave(isave), fLoad() { } MaxStream(ILoad* iload) : fSave(), fLoad(iload) { } + MaxStream(const MaxStream& other) = delete; + MaxStream(MaxStream&& other) = delete; + const MaxStream& operator=(const MaxStream& other) = delete; + MaxStream& operator=(MaxStream&& other) = delete; // Don't support any of this - bool Open(const plFileName &, const char * = "rb") override { hsAssert(0, "Not supported"); return false; } - bool Close() override { hsAssert(0, "Not supported"); return false; } bool AtEnd() override { hsAssert(false, "Not supported"); return false; } void Skip(uint32_t deltaByteCount) override { hsAssert(0, "Not supported"); } void Rewind() override { hsAssert(0, "Not supported"); } diff --git a/Sources/Tools/MaxConvert/hsMaterialConverter.cpp b/Sources/Tools/MaxConvert/hsMaterialConverter.cpp index 376422e17d..3816e4dd26 100644 --- a/Sources/Tools/MaxConvert/hsMaterialConverter.cpp +++ b/Sources/Tools/MaxConvert/hsMaterialConverter.cpp @@ -5008,7 +5008,6 @@ void hsMaterialConverter::IPrintDoneMaterials(const char* path, const std::vecto char buff[256]; sprintf(buff, ""); stream.WriteString("No Materials Generated\n"); - stream.Close(); return; } @@ -5065,8 +5064,6 @@ void hsMaterialConverter::IPrintDoneMaterials(const char* path, const std::vecto sprintf(buff, "\nThank you, and have a lovely day.\n"); stream.WriteString(buff); - - stream.Close(); } hsMaterialConverter::DoneMaterialData* hsMaterialConverter::IFindDoneMaterial(DoneMaterialData& done) diff --git a/Sources/Tools/MaxConvert/plLightMapGen.cpp b/Sources/Tools/MaxConvert/plLightMapGen.cpp index f00d47540a..75c00bc19f 100644 --- a/Sources/Tools/MaxConvert/plLightMapGen.cpp +++ b/Sources/Tools/MaxConvert/plLightMapGen.cpp @@ -329,8 +329,6 @@ void DumpMipmap(plMipmap* mipmap, const char* prefix) dump.WriteString("\n"); } } - - dump.Close(); } #endif // MIPMAP_LOG diff --git a/Sources/Tools/MaxExport/SimpleExport.cpp b/Sources/Tools/MaxExport/SimpleExport.cpp index 81ddb4417c..93c31b2d60 100644 --- a/Sources/Tools/MaxExport/SimpleExport.cpp +++ b/Sources/Tools/MaxExport/SimpleExport.cpp @@ -369,7 +369,6 @@ int HSExport2::DoExport(const MCHAR *name,ExpInterface *ei,Interface *gi, BOOL s out_name, tm.wMonth, tm.wDay, tm.wYear, exportTime / 60, exportTime % 60 ) ); - dbLog.Close(); // Allow plugins to clean up after export BroadcastNotification(NOTIFY_POST_EXPORT); diff --git a/Sources/Tools/MaxExport/plExportDlg.cpp b/Sources/Tools/MaxExport/plExportDlg.cpp index 36dc62390d..fd51b0668b 100644 --- a/Sources/Tools/MaxExport/plExportDlg.cpp +++ b/Sources/Tools/MaxExport/plExportDlg.cpp @@ -414,7 +414,6 @@ static bool AutoExportDir(const plFileName& inputDir, const plFileName& outputDi if (log.Open(outputLog, "ab")) { log.WriteString(ST::format("{}\r\n", iter->GetFileName())); - log.Close(); } if (GetCOREInterface()->LoadFromFile(ST2M(iter->AsString()))) @@ -442,7 +441,6 @@ static void ShutdownMax() { hsUNIXStream s; s.Open("log\\AutoExportDone.txt", "wb"); - s.Close(); } GetCOREInterface()->FlushUndoBuffer(); SetSaveRequiredFlag(FALSE); diff --git a/Sources/Tools/MaxExport/plExportLogErrorMsg.cpp b/Sources/Tools/MaxExport/plExportLogErrorMsg.cpp index 2a54f3430f..06b8fa493d 100644 --- a/Sources/Tools/MaxExport/plExportLogErrorMsg.cpp +++ b/Sources/Tools/MaxExport/plExportLogErrorMsg.cpp @@ -64,7 +64,6 @@ plExportLogErrorMsg::~plExportLogErrorMsg() fErrfile->WriteString("(which is a disaster!)"); else fErrfile->WriteString("(which is way too many!)"); - fErrfile->Close(); } #ifdef ERRORLOG_ALWAYS_WRITE_SOMETHING else @@ -73,7 +72,6 @@ plExportLogErrorMsg::~plExportLogErrorMsg() fErrfile->Open(fErrfile_name, "wt"); setbuf(fErrfile->GetFILE(), nullptr); fErrfile->WriteString("No errors found! Good job."); - fErrfile->Close(); } #endif // ERRORLOG_ALWAYS_WRITE_SOMETHING } diff --git a/Sources/Tools/MaxMain/plAgeDescInterface.cpp b/Sources/Tools/MaxMain/plAgeDescInterface.cpp index 5fc6173bdf..5f7dea4914 100644 --- a/Sources/Tools/MaxMain/plAgeDescInterface.cpp +++ b/Sources/Tools/MaxMain/plAgeDescInterface.cpp @@ -1183,7 +1183,6 @@ void plAgeDescInterface::ISaveCurAge( const plFileName &path, bool checkSeqNum ) // write it all out aged.Write(&s); - s.Close(); } //// ICheckSequenceNumber ///////////////////////////////////////////////////// @@ -1310,7 +1309,6 @@ uint32_t plAgeDescInterface::IGetNextFreeSequencePrefix( bool getReservedPrefix if( stream.Open( fAgeFiles[ i ]->fPath, "rt" ) ) { ages[ i ].Read( &stream ); - stream.Close(); } } diff --git a/Sources/Tools/MaxMain/plTextureExportLog.cpp b/Sources/Tools/MaxMain/plTextureExportLog.cpp index 24d63e638b..8056db698e 100644 --- a/Sources/Tools/MaxMain/plTextureExportLog.cpp +++ b/Sources/Tools/MaxMain/plTextureExportLog.cpp @@ -111,21 +111,21 @@ void plTextureExportLog::AddTexture( plBitmap *texture ) void plTextureExportLog::Write() { plBMapNode *node; - hsUNIXStream *stream = new hsUNIXStream; + hsUNIXStream stream; char str[ 128 ]; uint32_t size; - stream->Open( fFileName, "wt" ); - stream->WriteString( "------------------------------------------------------------\n" ); - stream->WriteString( "- Texture Export Data Log -\n" ); - stream->WriteString( "------------------------------------------------------------\n" ); - stream->WriteString( "\n" ); + stream.Open(fFileName, "wt"); + stream.WriteString("------------------------------------------------------------\n"); + stream.WriteString("- Texture Export Data Log -\n"); + stream.WriteString("------------------------------------------------------------\n"); + stream.WriteString("\n"); IWriteTabbedString( stream, "Name", 4 ); IWriteTabbedString( stream, "Size", 3 ); IWriteTabbedString( stream, "Type", 4 ); - stream->WriteString( "\n" ); - stream->WriteString( "------------------------------------------------------------\n" ); + stream.WriteString("\n"); + stream.WriteString("------------------------------------------------------------\n"); for (node = fNodeList; node != nullptr; node = node->fNextNode) { @@ -229,23 +229,20 @@ void plTextureExportLog::Write() { IWriteTabbedString( stream, "Unknown", 3 ); } - stream->WriteString( "\n" ); + stream.WriteString("\n"); } - stream->Close(); - delete stream; - // HACK: Prevent the destructor from writing out now fFileName = plFileName(); } -void plTextureExportLog::IWriteTabbedString( hsStream *stream, const char *string, int numTabs ) +void plTextureExportLog::IWriteTabbedString(hsStream& stream, const char *string, int numTabs) { static char tabs[ 64 ]; int i; - stream->WriteString( string ); + stream.WriteString(string); // Assumes 8 spaces per tab numTabs -= strlen( string ) / 8; @@ -256,5 +253,5 @@ void plTextureExportLog::IWriteTabbedString( hsStream *stream, const char *st tabs[ i ] = '\t'; tabs[ i ] = 0; - stream->WriteString( tabs ); + stream.WriteString(tabs); } diff --git a/Sources/Tools/MaxMain/plTextureExportLog.h b/Sources/Tools/MaxMain/plTextureExportLog.h index 068b1dcc35..38f2cf24b9 100644 --- a/Sources/Tools/MaxMain/plTextureExportLog.h +++ b/Sources/Tools/MaxMain/plTextureExportLog.h @@ -77,7 +77,7 @@ class plTextureExportLog void IAddBMapNode( uint32_t rank, plBitmap *bMap ); - void IWriteTabbedString( hsStream *stream, const char *string, int numTabs ); + void IWriteTabbedString(hsStream& stream, const char *string, int numTabs); public: diff --git a/Sources/Tools/plFontConverter/plFontConverter.cpp b/Sources/Tools/plFontConverter/plFontConverter.cpp index 9f02408e0f..e2372893c2 100644 --- a/Sources/Tools/plFontConverter/plFontConverter.cpp +++ b/Sources/Tools/plFontConverter/plFontConverter.cpp @@ -251,7 +251,6 @@ void plFontConverter::ExportP2F() hsgResMgr::ResMgr()->NewKey( fileName, gFont, plLocation::kGlobalFixedLoc ); */ fFont->WriteRaw(&stream); - stream.Close(); } } } @@ -582,7 +581,6 @@ void plFontConverter::IBatchFreeType(const plFileName &path, void *init) else { fFont->WriteRaw(&stream); - stream.Close(); } callback.CharDone(); diff --git a/Sources/Tools/plResBrowser/plResBrowser.cpp b/Sources/Tools/plResBrowser/plResBrowser.cpp index 3c2b78b992..e045f457e7 100644 --- a/Sources/Tools/plResBrowser/plResBrowser.cpp +++ b/Sources/Tools/plResBrowser/plResBrowser.cpp @@ -254,6 +254,7 @@ void plResBrowser::SaveSelectedObject() stream->SetPosition(keyImp->GetStartPos()); stream->Read(keyImp->GetDataLen(), buffer); } + pageNode->CloseStream(); if (!buffer) return; @@ -261,7 +262,6 @@ void plResBrowser::SaveSelectedObject() hsUNIXStream outStream; outStream.Open(fileName.toUtf8().constData(), "wb"); outStream.Write(keyImp->GetDataLen(), buffer); - outStream.Close(); delete[] buffer; } diff --git a/Sources/Tools/plShaderAssembler/main.cpp b/Sources/Tools/plShaderAssembler/main.cpp index e454f3f991..cc025e7838 100644 --- a/Sources/Tools/plShaderAssembler/main.cpp +++ b/Sources/Tools/plShaderAssembler/main.cpp @@ -143,7 +143,6 @@ static void IAssShader(const plDXShaderAssembler& ass, const char* name) hsUNIXStream inFp; if (!inFp.Open(inFile, "r")) { - outFp.Close(); fputs("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr); ST::printf(stderr, "Error opening file {} for input\n", inFile); fputs("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr); @@ -153,7 +152,6 @@ static void IAssShader(const plDXShaderAssembler& ass, const char* name) uint32_t shaderCodeLen = inFp.GetEOF(); auto shaderCode = std::make_unique(shaderCodeLen); inFp.Read(shaderCodeLen, shaderCode.get()); - inFp.Close(); try { auto compiledShader = ass.AssShader(shaderCode.get(), shaderCodeLen); @@ -163,8 +161,6 @@ static void IAssShader(const plDXShaderAssembler& ass, const char* name) fputs(error.c_str(), stderr); fputs("%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%\n", stderr); } - - outFp.Close(); } int main(int argc, char* argv[])