From 2570b561764741a4d05b7f02312f4d9956f70c75 Mon Sep 17 00:00:00 2001 From: Paul Licameli Date: Sun, 19 Jan 2020 09:51:50 -0500 Subject: [PATCH] Rename Maybe and its members more like std::optional of C++17 --- src/BlockFile.cpp | 8 ++-- src/DirManager.cpp | 14 +++---- src/FFmpeg.cpp | 2 +- src/FFmpeg.h | 2 +- src/FreqWindow.cpp | 4 +- src/MemoryX.h | 58 +++++++++++++++-------------- src/ProjectFileManager.cpp | 4 +- src/ShuttleGui.cpp | 2 +- src/ShuttleGui.h | 2 +- src/blockfile/LegacyBlockFile.cpp | 8 ++-- src/blockfile/SimpleBlockFile.cpp | 4 +- src/commands/CommandType.cpp | 2 +- src/commands/CommandType.h | 2 +- src/effects/FindClipping.cpp | 4 +- src/effects/VST/VSTEffect.cpp | 4 +- src/effects/nyquist/Nyquist.cpp | 4 +- src/import/ImportFFmpeg.cpp | 2 +- src/menus/EditMenus.cpp | 12 +++--- src/menus/TrackMenus.cpp | 4 +- src/ondemand/ODDecodeFFmpegTask.cpp | 2 +- src/widgets/OverlayPanel.cpp | 4 +- 21 files changed, 75 insertions(+), 73 deletions(-) diff --git a/src/BlockFile.cpp b/src/BlockFile.cpp index 4bdcbfd58..a1766656e 100644 --- a/src/BlockFile.cpp +++ b/src/BlockFile.cpp @@ -545,9 +545,9 @@ size_t BlockFile::CommonReadData( SFFile sf; { - Maybe silence{}; + Optional silence{}; if (mSilentLog) - silence.create(); + silence.emplace(); const auto fullPath = fileName.GetFullPath(); if (wxFile::Exists(fullPath) && f.Open(fullPath)) { @@ -756,9 +756,9 @@ bool AliasBlockFile::ReadSummary(ArrayOf &data) wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb")); { - Maybe silence{}; + Optional silence{}; if (mSilentLog) - silence.create(); + silence.emplace(); if (!summaryFile.IsOpened()){ diff --git a/src/DirManager.cpp b/src/DirManager.cpp index 93353a896..52ce2709a 100644 --- a/src/DirManager.cpp +++ b/src/DirManager.cpp @@ -204,16 +204,16 @@ int DirManager::RecursivelyEnumerateWithProgress(const FilePath &dirPath, int progress_count, const TranslatableString &message) { - Maybe progress{}; + Optional progress{}; if (!message.empty()) - progress.create( XO("Progress"), message ); + progress.emplace( XO("Progress"), message ); int count = RecursivelyEnumerate( dirPath, filePathArray, dirspec,filespec, bFiles, bDirs, progress_count, 0, - progress.get()); + progress ? &*progress : nullptr); return count; } @@ -289,11 +289,11 @@ void DirManager::RecursivelyRemove(const FilePaths& filePathArray, int count, in bool bFiles= (flags & kCleanFiles) != 0; bool bDirs = (flags & kCleanDirs) != 0; bool bDirsMustBeEmpty = (flags & kCleanDirsOnlyIfEmpty) != 0; - Maybe progress{}; + Optional progress{}; if (!message.empty()) - progress.create( XO("Progress"), message ); + progress.emplace( XO("Progress"), message ); auto nn = filePathArray.size(); for ( size_t ii = 0; ii < nn; ++ii ) { @@ -568,7 +568,7 @@ struct DirManager::ProjectSetter::Impl // Another RAII object // Be prepared to un-create directory on failure - Maybe dirCleaner; + Optional dirCleaner; // State variables to carry over into Commit() // Remember old path to be cleaned up in case of successful move @@ -646,7 +646,7 @@ DirManager::ProjectSetter::Impl::Impl( // Be prepared to un-create directory on failure if (bCreate) - dirCleaner.create( committed, dirManager.projFull ); + dirCleaner.emplace( committed, dirManager.projFull ); /* Hard-link or copy all files into this NEW directory. diff --git a/src/FFmpeg.cpp b/src/FFmpeg.cpp index 60c9d6b8e..4611bf2f6 100644 --- a/src/FFmpeg.cpp +++ b/src/FFmpeg.cpp @@ -335,7 +335,7 @@ streamContext *import_ffmpeg_read_next_frame(AVFormatContext* formatContext, } // Copy the frame to the stream context - sc->m_pkt.create(std::move(pkt)); + sc->m_pkt.emplace(std::move(pkt)); sc->m_pktDataPtr = sc->m_pkt->data; sc->m_pktRemainingSiz = sc->m_pkt->size; diff --git a/src/FFmpeg.h b/src/FFmpeg.h index c27578ff4..561e7c5c5 100644 --- a/src/FFmpeg.h +++ b/src/FFmpeg.h @@ -1005,7 +1005,7 @@ struct streamContext AVStream *m_stream{}; // an AVStream * AVCodecContext *m_codecCtx{}; // pointer to m_stream->codec - Maybe m_pkt; // the last AVPacket we read for this stream + Optional m_pkt; // the last AVPacket we read for this stream uint8_t *m_pktDataPtr{}; // pointer into m_pkt.data int m_pktRemainingSiz{}; diff --git a/src/FreqWindow.cpp b/src/FreqWindow.cpp index cf2ea5e26..2ff939d20 100644 --- a/src/FreqWindow.cpp +++ b/src/FreqWindow.cpp @@ -1012,9 +1012,9 @@ void FrequencyPlotDialog::Recalc() // controls while the plot was being recalculated. This doesn't appear to be necessary // so just use the the top level window instead. { - Maybe blocker; + Optional blocker; if (IsShown()) - blocker.create(this); + blocker.emplace(this); wxYieldIfNeeded(); mAnalyst->Calculate(alg, windowFunc, mWindowSize, mRate, diff --git a/src/MemoryX.h b/src/MemoryX.h index afde54a06..04bba44d5 100644 --- a/src/MemoryX.h +++ b/src/MemoryX.h @@ -185,16 +185,15 @@ public: }; /** - \class Maybe + \class Optional \brief Like a smart pointer, allows for object to not exist (nullptr) + \brief emulating some of std::optional of C++17 - template class Maybe + template class Optional Can be used for monomorphic objects that are stack-allocable, but only conditionally constructed. You might also use it as a member. - Initialize with create(), then use like a smart pointer, - with *, ->, get(), reset(), or in if() - - Like std::optional of C++17 but with other member naming conventions + Initialize with emplace(), then use like a smart pointer, + with *, ->, reset(), or in if() */ // Placement-NEW is used below, and that does not cooperate with the DEBUG_NEW for Visual Studio @@ -206,41 +205,43 @@ public: template -class Maybe { +class Optional { public: + using value_type = X; + // Construct as NULL - Maybe() {} + Optional() {} // Supply the copy and move, so you might use this as a class member too - Maybe(const Maybe &that) + Optional(const Optional &that) { - if (that.get()) - create(*that); + if (that) + emplace(*that); } - Maybe& operator= (const Maybe &that) + Optional& operator= (const Optional &that) { if (this != &that) { - if (that.get()) - create(*that); + if (that) + emplace(*that); else reset(); } return *this; } - Maybe(Maybe &&that) + Optional(Optional &&that) { - if (that.get()) - create(::std::move(*that)); + if (that) + emplace(::std::move(*that)); } - Maybe& operator= (Maybe &&that) + Optional& operator= (Optional &&that) { if (this != &that) { - if (that.get()) - create(::std::move(*that)); + if (that) + emplace(::std::move(*that)); else reset(); } @@ -253,16 +254,17 @@ public: /// NULL state -- giving exception safety but only weakly /// (previous value was lost if present) template - void create(Args&&... args) + X& emplace(Args&&... args) { // Lose any old value reset(); - // Create NEW value + // emplace NEW value pp = safenew(address()) X(std::forward(args)...); + return **this; } // Destroy any object that was built in it - ~Maybe() + ~Optional() { reset(); } @@ -280,11 +282,6 @@ public: return pp; } - X* get() const - { - return pp; - } - void reset() { if (pp) @@ -297,6 +294,11 @@ public: return pp != nullptr; } + bool has_value() const + { + return pp != nullptr; + } + private: X* address() { diff --git a/src/ProjectFileManager.cpp b/src/ProjectFileManager.cpp index c0b4dee72..7ea6062b3 100644 --- a/src/ProjectFileManager.cpp +++ b/src/ProjectFileManager.cpp @@ -515,7 +515,7 @@ bool ProjectFileManager::DoSave (const bool fromSaveAs, { std::vector> lockers; - Maybe pSetter; + Optional pSetter; bool moving = true; if (fromSaveAs && !bWantSaveCopy) { @@ -536,7 +536,7 @@ bool ProjectFileManager::DoSave (const bool fromSaveAs, // This renames the project directory, and moves or copies // all of our block files over. - pSetter.create( dirManager, projPath, projName, true, moving ); + pSetter.emplace( dirManager, projPath, projName, true, moving ); if (!pSetter->Ok()){ success = false; diff --git a/src/ShuttleGui.cpp b/src/ShuttleGui.cpp index f86de3500..478a79544 100644 --- a/src/ShuttleGui.cpp +++ b/src/ShuttleGui.cpp @@ -1561,7 +1561,7 @@ void ShuttleGuiBase::StartRadioButtonGroup( const ChoiceSetting &Setting ) // Configure the generic type mechanism to use OUR string. mRadioValueString = Setting.Default().Internal(); - mRadioValue.create( mRadioValueString ); + mRadioValue.emplace( mRadioValueString ); // Now actually start the radio button group. mRadioSettingName = Setting.Key(); diff --git a/src/ShuttleGui.h b/src/ShuttleGui.h index db6ffeb8a..2ca5a9709 100644 --- a/src/ShuttleGui.h +++ b/src/ShuttleGui.h @@ -570,7 +570,7 @@ private: std::vector mRadioSymbols; wxString mRadioSettingName; /// The setting controlled by a group. - Maybe mRadioValue; /// The wrapped value associated with the active radio button. + Optional mRadioValue; /// The wrapped value associated with the active radio button. int mRadioCount; /// The index of this radio item. -1 for none. wxString mRadioValueString; /// Unwrapped string value. wxRadioButton * DoAddRadioButton( diff --git a/src/blockfile/LegacyBlockFile.cpp b/src/blockfile/LegacyBlockFile.cpp index 32975958a..cf1e90e7c 100644 --- a/src/blockfile/LegacyBlockFile.cpp +++ b/src/blockfile/LegacyBlockFile.cpp @@ -73,11 +73,11 @@ void ComputeLegacySummaryInfo(const wxFileName &fileName, int read; { - Maybe silence{}; + Optional silence{}; const wxString fullPath{ fileName.GetFullPath() }; wxFFile summaryFile(fullPath, wxT("rb")); if (Silent) - silence.create(); + silence.emplace(); // FIXME: TRAP_ERR no report to user of absent summary files. if (!summaryFile.IsOpened()) { @@ -160,9 +160,9 @@ bool LegacyBlockFile::ReadSummary(ArrayOf &data) wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb")); size_t read; { - Maybe silence{}; + Optional silence{}; if (mSilentLog) - silence.create(); + silence.emplace(); if (!summaryFile.IsOpened()) { diff --git a/src/blockfile/SimpleBlockFile.cpp b/src/blockfile/SimpleBlockFile.cpp index 42db44c88..70a749464 100644 --- a/src/blockfile/SimpleBlockFile.cpp +++ b/src/blockfile/SimpleBlockFile.cpp @@ -356,9 +356,9 @@ bool SimpleBlockFile::ReadSummary(ArrayOf &data) wxFFile file(mFileName.GetFullPath(), wxT("rb")); { - Maybe silence{}; + Optional silence{}; if (mSilentLog) - silence.create(); + silence.emplace(); // FIXME: TRAP_ERR no report to user of absent summary files? // filled with zero instead. if (!file.IsOpened()){ diff --git a/src/commands/CommandType.cpp b/src/commands/CommandType.cpp index d97898703..9f7b2012a 100644 --- a/src/commands/CommandType.cpp +++ b/src/commands/CommandType.cpp @@ -41,7 +41,7 @@ CommandSignature &OldStyleCommandType::GetSignature() { if (!mSignature) { - mSignature.create(); + mSignature.emplace(); BuildSignature(*mSignature); } return *mSignature; diff --git a/src/commands/CommandType.h b/src/commands/CommandType.h index 3ba5a9acc..60781b9f6 100644 --- a/src/commands/CommandType.h +++ b/src/commands/CommandType.h @@ -43,7 +43,7 @@ class OldStyleCommandType : public AudacityCommand { private: ComponentInterfaceSymbol mSymbol; - Maybe mSignature; + Optional mSignature; public: OldStyleCommandType(); diff --git a/src/effects/FindClipping.cpp b/src/effects/FindClipping.cpp index 7bde13929..02410f568 100644 --- a/src/effects/FindClipping.cpp +++ b/src/effects/FindClipping.cpp @@ -105,7 +105,7 @@ bool EffectFindClipping::SetAutomationParameters(CommandParameters & parms) bool EffectFindClipping::Process() { std::shared_ptr addedTrack; - Maybe modifiedTrack; + Optional modifiedTrack; const wxString name{ _("Clipping") }; auto clt = *inputTracks()->Any< const LabelTrack >().find_if( @@ -115,7 +115,7 @@ bool EffectFindClipping::Process() if (!clt) addedTrack = (AddAnalysisTrack(name)), lt = addedTrack->get(); else - modifiedTrack.create(ModifyAnalysisTrack(clt, name)), + modifiedTrack.emplace(ModifyAnalysisTrack(clt, name)), lt = modifiedTrack->get(); int count = 0; diff --git a/src/effects/VST/VSTEffect.cpp b/src/effects/VST/VSTEffect.cpp index 904b0389b..7dfdbf31e 100644 --- a/src/effects/VST/VSTEffect.cpp +++ b/src/effects/VST/VSTEffect.cpp @@ -517,7 +517,7 @@ unsigned VSTEffectsModule::DiscoverPluginsAtPath( wxString effectIDs = wxT("0;"); wxStringTokenizer effectTzr(effectIDs, wxT(";")); - Maybe progress{}; + Optional progress{}; size_t idCnt = 0; size_t idNdx = 0; @@ -577,7 +577,7 @@ unsigned VSTEffectsModule::DiscoverPluginsAtPath( idCnt = effectTzr.CountTokens(); if (idCnt > 3) { - progress.create( _("Scanning Shell VST"), + progress.emplace( _("Scanning Shell VST"), wxString::Format(_("Registering %d of %d: %-64.64s"), 0, idCnt, proc.GetSymbol().Translation()), static_cast(idCnt), diff --git a/src/effects/nyquist/Nyquist.cpp b/src/effects/nyquist/Nyquist.cpp index cab019312..067858155 100644 --- a/src/effects/nyquist/Nyquist.cpp +++ b/src/effects/nyquist/Nyquist.cpp @@ -789,9 +789,9 @@ bool NyquistEffect::Process() XO("Nyquist Error") ); } - Maybe> pRange; + Optional> pRange; if (!bOnePassTool) - pRange.create(mOutputTracks->Selected< WaveTrack >() + &Track::IsLeader); + pRange.emplace(mOutputTracks->Selected< WaveTrack >() + &Track::IsLeader); // Keep track of whether the current track is first selected in its sync-lock group // (we have no idea what the length of the returned audio will be, so we have diff --git a/src/import/ImportFFmpeg.cpp b/src/import/ImportFFmpeg.cpp index fc13daabe..14223eb13 100644 --- a/src/import/ImportFFmpeg.cpp +++ b/src/import/ImportFFmpeg.cpp @@ -667,7 +667,7 @@ ProgressResult FFmpegImportFileHandle::Import(TrackFactory *trackFactory, for (int i = 0; i < mNumStreams; i++) { auto sc = scs[i].get(); - sc->m_pkt.create(); + sc->m_pkt.emplace(); if (DecodeFrame(sc, true) == 0) { WriteData(sc); diff --git a/src/menus/EditMenus.cpp b/src/menus/EditMenus.cpp index 29a51ef10..ab9f86b03 100644 --- a/src/menus/EditMenus.cpp +++ b/src/menus/EditMenus.cpp @@ -93,7 +93,7 @@ bool DoPasteNothingSelected(AudacityProject &project) Track* pFirstNewTrack = NULL; for (auto pClip : clipTrackRange) { - Maybe locker; + Optional locker; Track::Holder uNewTrack; Track *pNewTrack; @@ -102,7 +102,7 @@ bool DoPasteNothingSelected(AudacityProject &project) if ((clipboard.Project() != &project)) // Cause duplication of block files on disk, when copy is // between projects - locker.create(wc); + locker.emplace(wc); uNewTrack = trackFactory.NewWaveTrack( wc->GetSampleFormat(), wc->GetRate()), pNewTrack = uNewTrack.get(); @@ -505,7 +505,7 @@ void OnPaste(const CommandContext &context) ff = n; wxASSERT( n && c && n->SameKindAs(*c) ); - Maybe locker; + Optional locker; n->TypeSwitch( [&](WaveTrack *wn){ @@ -513,7 +513,7 @@ void OnPaste(const CommandContext &context) if (clipboard.Project() != &project) // Cause duplication of block files on disk, when copy is // between projects - locker.create(wc); + locker.emplace(wc); bPastedSomething = true; wn->ClearAndPaste(t0, t1, wc, true, true); }, @@ -583,11 +583,11 @@ void OnPaste(const CommandContext &context) { const auto wc = *clipboard.GetTracks().Any< const WaveTrack >().rbegin(); - Maybe locker; + Optional locker; if (clipboard.Project() != &project && wc) // Cause duplication of block files on disk, when copy is // between projects - locker.create(static_cast(wc)); + locker.emplace(static_cast(wc)); tracks.Any().StartingWith(*pN).Visit( [&](WaveTrack *wt, const Track::Fallthrough &fallthrough) { diff --git a/src/menus/TrackMenus.cpp b/src/menus/TrackMenus.cpp index 2c53646db..508bc6b53 100644 --- a/src/menus/TrackMenus.cpp +++ b/src/menus/TrackMenus.cpp @@ -347,7 +347,7 @@ class ASAProgress final : public SAProgress { long mTotalCells; // how many matrix cells? long mCellCount; // how many cells so far? long mPrevCellCount; // cell_count last reported with Update() - Maybe mProgress; + Optional mProgress; #ifdef COLLECT_TIMING_DATA FILE *mTimeFile; wxDateTime mStartTime; @@ -409,7 +409,7 @@ class ASAProgress final : public SAProgress { work[1], mFrames[1], is_audio[1]); wxFprintf(mTimeFile, "work2 = %g, work3 = %g\n", work2, work3); #endif - mProgress.create(XO("Synchronize MIDI with Audio"), + mProgress.emplace(XO("Synchronize MIDI with Audio"), XO("Synchronizing MIDI and Audio Tracks")); } else if (i < 3) { wxFprintf(mTimeFile, diff --git a/src/ondemand/ODDecodeFFmpegTask.cpp b/src/ondemand/ODDecodeFFmpegTask.cpp index a9c7bdc88..32bcd003d 100644 --- a/src/ondemand/ODDecodeFFmpegTask.cpp +++ b/src/ondemand/ODDecodeFFmpegTask.cpp @@ -428,7 +428,7 @@ int ODFFmpegDecoder::Decode(SampleBuffer & data, sampleFormat & format, sampleCo for (int i = 0; i < mChannels.size(); i++) { sc = scs[i].get(); - sc->m_pkt.create(); + sc->m_pkt.emplace(); if (DecodeFrame(sc, true) == 0) { sc->m_pkt.reset(); diff --git a/src/widgets/OverlayPanel.cpp b/src/widgets/OverlayPanel.cpp index ff4d97228..44ca7e36a 100644 --- a/src/widgets/OverlayPanel.cpp +++ b/src/widgets/OverlayPanel.cpp @@ -95,8 +95,8 @@ void OverlayPanel::DrawOverlays(bool repaint_all, wxDC *pDC) } while (!done); } - Maybe myDC; - auto &dc = pDC ? *pDC : (myDC.create(this), *myDC); + Optional myDC; + auto &dc = pDC ? *pDC : (myDC.emplace(this), *myDC); // Erase auto it2 = pairs.begin();