1
0
mirror of https://github.com/cookiengineer/audacity synced 2025-08-02 08:59:28 +02:00

Rename Maybe and its members more like std::optional of C++17

This commit is contained in:
Paul Licameli 2020-01-19 09:51:50 -05:00
parent 30999ab134
commit 2570b56176
21 changed files with 75 additions and 73 deletions

View File

@ -545,9 +545,9 @@ size_t BlockFile::CommonReadData(
SFFile sf; SFFile sf;
{ {
Maybe<wxLogNull> silence{}; Optional<wxLogNull> silence{};
if (mSilentLog) if (mSilentLog)
silence.create(); silence.emplace();
const auto fullPath = fileName.GetFullPath(); const auto fullPath = fileName.GetFullPath();
if (wxFile::Exists(fullPath) && f.Open(fullPath)) { if (wxFile::Exists(fullPath) && f.Open(fullPath)) {
@ -756,9 +756,9 @@ bool AliasBlockFile::ReadSummary(ArrayOf<char> &data)
wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb")); wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb"));
{ {
Maybe<wxLogNull> silence{}; Optional<wxLogNull> silence{};
if (mSilentLog) if (mSilentLog)
silence.create(); silence.emplace();
if (!summaryFile.IsOpened()){ if (!summaryFile.IsOpened()){

View File

@ -204,16 +204,16 @@ int DirManager::RecursivelyEnumerateWithProgress(const FilePath &dirPath,
int progress_count, int progress_count,
const TranslatableString &message) const TranslatableString &message)
{ {
Maybe<ProgressDialog> progress{}; Optional<ProgressDialog> progress{};
if (!message.empty()) if (!message.empty())
progress.create( XO("Progress"), message ); progress.emplace( XO("Progress"), message );
int count = RecursivelyEnumerate( int count = RecursivelyEnumerate(
dirPath, filePathArray, dirspec,filespec, dirPath, filePathArray, dirspec,filespec,
bFiles, bDirs, bFiles, bDirs,
progress_count, 0, progress_count, 0,
progress.get()); progress ? &*progress : nullptr);
return count; return count;
} }
@ -289,11 +289,11 @@ void DirManager::RecursivelyRemove(const FilePaths& filePathArray, int count, in
bool bFiles= (flags & kCleanFiles) != 0; bool bFiles= (flags & kCleanFiles) != 0;
bool bDirs = (flags & kCleanDirs) != 0; bool bDirs = (flags & kCleanDirs) != 0;
bool bDirsMustBeEmpty = (flags & kCleanDirsOnlyIfEmpty) != 0; bool bDirsMustBeEmpty = (flags & kCleanDirsOnlyIfEmpty) != 0;
Maybe<ProgressDialog> progress{}; Optional<ProgressDialog> progress{};
if (!message.empty()) if (!message.empty())
progress.create( XO("Progress"), message ); progress.emplace( XO("Progress"), message );
auto nn = filePathArray.size(); auto nn = filePathArray.size();
for ( size_t ii = 0; ii < nn; ++ii ) { for ( size_t ii = 0; ii < nn; ++ii ) {
@ -568,7 +568,7 @@ struct DirManager::ProjectSetter::Impl
// Another RAII object // Another RAII object
// Be prepared to un-create directory on failure // Be prepared to un-create directory on failure
Maybe<DirCleaner> dirCleaner; Optional<DirCleaner> dirCleaner;
// State variables to carry over into Commit() // State variables to carry over into Commit()
// Remember old path to be cleaned up in case of successful move // 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 // Be prepared to un-create directory on failure
if (bCreate) if (bCreate)
dirCleaner.create( committed, dirManager.projFull ); dirCleaner.emplace( committed, dirManager.projFull );
/* Hard-link or copy all files into this NEW directory. /* Hard-link or copy all files into this NEW directory.

View File

@ -335,7 +335,7 @@ streamContext *import_ffmpeg_read_next_frame(AVFormatContext* formatContext,
} }
// Copy the frame to the stream context // 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_pktDataPtr = sc->m_pkt->data;
sc->m_pktRemainingSiz = sc->m_pkt->size; sc->m_pktRemainingSiz = sc->m_pkt->size;

View File

@ -1005,7 +1005,7 @@ struct streamContext
AVStream *m_stream{}; // an AVStream * AVStream *m_stream{}; // an AVStream *
AVCodecContext *m_codecCtx{}; // pointer to m_stream->codec AVCodecContext *m_codecCtx{}; // pointer to m_stream->codec
Maybe<AVPacketEx> m_pkt; // the last AVPacket we read for this stream Optional<AVPacketEx> m_pkt; // the last AVPacket we read for this stream
uint8_t *m_pktDataPtr{}; // pointer into m_pkt.data uint8_t *m_pktDataPtr{}; // pointer into m_pkt.data
int m_pktRemainingSiz{}; int m_pktRemainingSiz{};

View File

@ -1012,9 +1012,9 @@ void FrequencyPlotDialog::Recalc()
// controls while the plot was being recalculated. This doesn't appear to be necessary // controls while the plot was being recalculated. This doesn't appear to be necessary
// so just use the the top level window instead. // so just use the the top level window instead.
{ {
Maybe<wxWindowDisabler> blocker; Optional<wxWindowDisabler> blocker;
if (IsShown()) if (IsShown())
blocker.create(this); blocker.emplace(this);
wxYieldIfNeeded(); wxYieldIfNeeded();
mAnalyst->Calculate(alg, windowFunc, mWindowSize, mRate, mAnalyst->Calculate(alg, windowFunc, mWindowSize, mRate,

View File

@ -185,16 +185,15 @@ public:
}; };
/** /**
\class Maybe \class Optional
\brief Like a smart pointer, allows for object to not exist (nullptr) \brief Like a smart pointer, allows for object to not exist (nullptr)
\brief emulating some of std::optional of C++17
template class Maybe<X> template class Optional<X>
Can be used for monomorphic objects that are stack-allocable, but only conditionally constructed. Can be used for monomorphic objects that are stack-allocable, but only conditionally constructed.
You might also use it as a member. You might also use it as a member.
Initialize with create(), then use like a smart pointer, Initialize with emplace(), then use like a smart pointer,
with *, ->, get(), reset(), or in if() with *, ->, reset(), or in if()
Like std::optional of C++17 but with other member naming conventions
*/ */
// Placement-NEW is used below, and that does not cooperate with the DEBUG_NEW for Visual Studio // Placement-NEW is used below, and that does not cooperate with the DEBUG_NEW for Visual Studio
@ -206,41 +205,43 @@ public:
template<typename X> template<typename X>
class Maybe { class Optional {
public: public:
using value_type = X;
// Construct as NULL // Construct as NULL
Maybe() {} Optional() {}
// Supply the copy and move, so you might use this as a class member too // 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()) if (that)
create(*that); emplace(*that);
} }
Maybe& operator= (const Maybe &that) Optional& operator= (const Optional &that)
{ {
if (this != &that) { if (this != &that) {
if (that.get()) if (that)
create(*that); emplace(*that);
else else
reset(); reset();
} }
return *this; return *this;
} }
Maybe(Maybe &&that) Optional(Optional &&that)
{ {
if (that.get()) if (that)
create(::std::move(*that)); emplace(::std::move(*that));
} }
Maybe& operator= (Maybe &&that) Optional& operator= (Optional &&that)
{ {
if (this != &that) { if (this != &that) {
if (that.get()) if (that)
create(::std::move(*that)); emplace(::std::move(*that));
else else
reset(); reset();
} }
@ -253,16 +254,17 @@ public:
/// NULL state -- giving exception safety but only weakly /// NULL state -- giving exception safety but only weakly
/// (previous value was lost if present) /// (previous value was lost if present)
template<typename... Args> template<typename... Args>
void create(Args&&... args) X& emplace(Args&&... args)
{ {
// Lose any old value // Lose any old value
reset(); reset();
// Create NEW value // emplace NEW value
pp = safenew(address()) X(std::forward<Args>(args)...); pp = safenew(address()) X(std::forward<Args>(args)...);
return **this;
} }
// Destroy any object that was built in it // Destroy any object that was built in it
~Maybe() ~Optional()
{ {
reset(); reset();
} }
@ -280,11 +282,6 @@ public:
return pp; return pp;
} }
X* get() const
{
return pp;
}
void reset() void reset()
{ {
if (pp) if (pp)
@ -297,6 +294,11 @@ public:
return pp != nullptr; return pp != nullptr;
} }
bool has_value() const
{
return pp != nullptr;
}
private: private:
X* address() X* address()
{ {

View File

@ -515,7 +515,7 @@ bool ProjectFileManager::DoSave (const bool fromSaveAs,
{ {
std::vector<std::unique_ptr<WaveTrack::Locker>> lockers; std::vector<std::unique_ptr<WaveTrack::Locker>> lockers;
Maybe<DirManager::ProjectSetter> pSetter; Optional<DirManager::ProjectSetter> pSetter;
bool moving = true; bool moving = true;
if (fromSaveAs && !bWantSaveCopy) { if (fromSaveAs && !bWantSaveCopy) {
@ -536,7 +536,7 @@ bool ProjectFileManager::DoSave (const bool fromSaveAs,
// This renames the project directory, and moves or copies // This renames the project directory, and moves or copies
// all of our block files over. // all of our block files over.
pSetter.create( dirManager, projPath, projName, true, moving ); pSetter.emplace( dirManager, projPath, projName, true, moving );
if (!pSetter->Ok()){ if (!pSetter->Ok()){
success = false; success = false;

View File

@ -1561,7 +1561,7 @@ void ShuttleGuiBase::StartRadioButtonGroup( const ChoiceSetting &Setting )
// Configure the generic type mechanism to use OUR string. // Configure the generic type mechanism to use OUR string.
mRadioValueString = Setting.Default().Internal(); mRadioValueString = Setting.Default().Internal();
mRadioValue.create( mRadioValueString ); mRadioValue.emplace( mRadioValueString );
// Now actually start the radio button group. // Now actually start the radio button group.
mRadioSettingName = Setting.Key(); mRadioSettingName = Setting.Key();

View File

@ -570,7 +570,7 @@ private:
std::vector<EnumValueSymbol> mRadioSymbols; std::vector<EnumValueSymbol> mRadioSymbols;
wxString mRadioSettingName; /// The setting controlled by a group. wxString mRadioSettingName; /// The setting controlled by a group.
Maybe<WrappedType> mRadioValue; /// The wrapped value associated with the active radio button. Optional<WrappedType> mRadioValue; /// The wrapped value associated with the active radio button.
int mRadioCount; /// The index of this radio item. -1 for none. int mRadioCount; /// The index of this radio item. -1 for none.
wxString mRadioValueString; /// Unwrapped string value. wxString mRadioValueString; /// Unwrapped string value.
wxRadioButton * DoAddRadioButton( wxRadioButton * DoAddRadioButton(

View File

@ -73,11 +73,11 @@ void ComputeLegacySummaryInfo(const wxFileName &fileName,
int read; int read;
{ {
Maybe<wxLogNull> silence{}; Optional<wxLogNull> silence{};
const wxString fullPath{ fileName.GetFullPath() }; const wxString fullPath{ fileName.GetFullPath() };
wxFFile summaryFile(fullPath, wxT("rb")); wxFFile summaryFile(fullPath, wxT("rb"));
if (Silent) if (Silent)
silence.create(); silence.emplace();
// FIXME: TRAP_ERR no report to user of absent summary files. // FIXME: TRAP_ERR no report to user of absent summary files.
if (!summaryFile.IsOpened()) { if (!summaryFile.IsOpened()) {
@ -160,9 +160,9 @@ bool LegacyBlockFile::ReadSummary(ArrayOf<char> &data)
wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb")); wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb"));
size_t read; size_t read;
{ {
Maybe<wxLogNull> silence{}; Optional<wxLogNull> silence{};
if (mSilentLog) if (mSilentLog)
silence.create(); silence.emplace();
if (!summaryFile.IsOpened()) { if (!summaryFile.IsOpened()) {

View File

@ -356,9 +356,9 @@ bool SimpleBlockFile::ReadSummary(ArrayOf<char> &data)
wxFFile file(mFileName.GetFullPath(), wxT("rb")); wxFFile file(mFileName.GetFullPath(), wxT("rb"));
{ {
Maybe<wxLogNull> silence{}; Optional<wxLogNull> silence{};
if (mSilentLog) if (mSilentLog)
silence.create(); silence.emplace();
// FIXME: TRAP_ERR no report to user of absent summary files? // FIXME: TRAP_ERR no report to user of absent summary files?
// filled with zero instead. // filled with zero instead.
if (!file.IsOpened()){ if (!file.IsOpened()){

View File

@ -41,7 +41,7 @@ CommandSignature &OldStyleCommandType::GetSignature()
{ {
if (!mSignature) if (!mSignature)
{ {
mSignature.create(); mSignature.emplace();
BuildSignature(*mSignature); BuildSignature(*mSignature);
} }
return *mSignature; return *mSignature;

View File

@ -43,7 +43,7 @@ class OldStyleCommandType : public AudacityCommand
{ {
private: private:
ComponentInterfaceSymbol mSymbol; ComponentInterfaceSymbol mSymbol;
Maybe<CommandSignature> mSignature; Optional<CommandSignature> mSignature;
public: public:
OldStyleCommandType(); OldStyleCommandType();

View File

@ -105,7 +105,7 @@ bool EffectFindClipping::SetAutomationParameters(CommandParameters & parms)
bool EffectFindClipping::Process() bool EffectFindClipping::Process()
{ {
std::shared_ptr<AddedAnalysisTrack> addedTrack; std::shared_ptr<AddedAnalysisTrack> addedTrack;
Maybe<ModifiedAnalysisTrack> modifiedTrack; Optional<ModifiedAnalysisTrack> modifiedTrack;
const wxString name{ _("Clipping") }; const wxString name{ _("Clipping") };
auto clt = *inputTracks()->Any< const LabelTrack >().find_if( auto clt = *inputTracks()->Any< const LabelTrack >().find_if(
@ -115,7 +115,7 @@ bool EffectFindClipping::Process()
if (!clt) if (!clt)
addedTrack = (AddAnalysisTrack(name)), lt = addedTrack->get(); addedTrack = (AddAnalysisTrack(name)), lt = addedTrack->get();
else else
modifiedTrack.create(ModifyAnalysisTrack(clt, name)), modifiedTrack.emplace(ModifyAnalysisTrack(clt, name)),
lt = modifiedTrack->get(); lt = modifiedTrack->get();
int count = 0; int count = 0;

View File

@ -517,7 +517,7 @@ unsigned VSTEffectsModule::DiscoverPluginsAtPath(
wxString effectIDs = wxT("0;"); wxString effectIDs = wxT("0;");
wxStringTokenizer effectTzr(effectIDs, wxT(";")); wxStringTokenizer effectTzr(effectIDs, wxT(";"));
Maybe<wxProgressDialog> progress{}; Optional<wxProgressDialog> progress{};
size_t idCnt = 0; size_t idCnt = 0;
size_t idNdx = 0; size_t idNdx = 0;
@ -577,7 +577,7 @@ unsigned VSTEffectsModule::DiscoverPluginsAtPath(
idCnt = effectTzr.CountTokens(); idCnt = effectTzr.CountTokens();
if (idCnt > 3) if (idCnt > 3)
{ {
progress.create( _("Scanning Shell VST"), progress.emplace( _("Scanning Shell VST"),
wxString::Format(_("Registering %d of %d: %-64.64s"), 0, idCnt, wxString::Format(_("Registering %d of %d: %-64.64s"), 0, idCnt,
proc.GetSymbol().Translation()), proc.GetSymbol().Translation()),
static_cast<int>(idCnt), static_cast<int>(idCnt),

View File

@ -789,9 +789,9 @@ bool NyquistEffect::Process()
XO("Nyquist Error") ); XO("Nyquist Error") );
} }
Maybe<TrackIterRange<WaveTrack>> pRange; Optional<TrackIterRange<WaveTrack>> pRange;
if (!bOnePassTool) 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 // 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 // (we have no idea what the length of the returned audio will be, so we have

View File

@ -667,7 +667,7 @@ ProgressResult FFmpegImportFileHandle::Import(TrackFactory *trackFactory,
for (int i = 0; i < mNumStreams; i++) for (int i = 0; i < mNumStreams; i++)
{ {
auto sc = scs[i].get(); auto sc = scs[i].get();
sc->m_pkt.create(); sc->m_pkt.emplace();
if (DecodeFrame(sc, true) == 0) if (DecodeFrame(sc, true) == 0)
{ {
WriteData(sc); WriteData(sc);

View File

@ -93,7 +93,7 @@ bool DoPasteNothingSelected(AudacityProject &project)
Track* pFirstNewTrack = NULL; Track* pFirstNewTrack = NULL;
for (auto pClip : clipTrackRange) { for (auto pClip : clipTrackRange) {
Maybe<WaveTrack::Locker> locker; Optional<WaveTrack::Locker> locker;
Track::Holder uNewTrack; Track::Holder uNewTrack;
Track *pNewTrack; Track *pNewTrack;
@ -102,7 +102,7 @@ bool DoPasteNothingSelected(AudacityProject &project)
if ((clipboard.Project() != &project)) if ((clipboard.Project() != &project))
// Cause duplication of block files on disk, when copy is // Cause duplication of block files on disk, when copy is
// between projects // between projects
locker.create(wc); locker.emplace(wc);
uNewTrack = trackFactory.NewWaveTrack( uNewTrack = trackFactory.NewWaveTrack(
wc->GetSampleFormat(), wc->GetRate()), wc->GetSampleFormat(), wc->GetRate()),
pNewTrack = uNewTrack.get(); pNewTrack = uNewTrack.get();
@ -505,7 +505,7 @@ void OnPaste(const CommandContext &context)
ff = n; ff = n;
wxASSERT( n && c && n->SameKindAs(*c) ); wxASSERT( n && c && n->SameKindAs(*c) );
Maybe<WaveTrack::Locker> locker; Optional<WaveTrack::Locker> locker;
n->TypeSwitch( n->TypeSwitch(
[&](WaveTrack *wn){ [&](WaveTrack *wn){
@ -513,7 +513,7 @@ void OnPaste(const CommandContext &context)
if (clipboard.Project() != &project) if (clipboard.Project() != &project)
// Cause duplication of block files on disk, when copy is // Cause duplication of block files on disk, when copy is
// between projects // between projects
locker.create(wc); locker.emplace(wc);
bPastedSomething = true; bPastedSomething = true;
wn->ClearAndPaste(t0, t1, wc, true, true); wn->ClearAndPaste(t0, t1, wc, true, true);
}, },
@ -583,11 +583,11 @@ void OnPaste(const CommandContext &context)
{ {
const auto wc = const auto wc =
*clipboard.GetTracks().Any< const WaveTrack >().rbegin(); *clipboard.GetTracks().Any< const WaveTrack >().rbegin();
Maybe<WaveTrack::Locker> locker; Optional<WaveTrack::Locker> locker;
if (clipboard.Project() != &project && wc) if (clipboard.Project() != &project && wc)
// Cause duplication of block files on disk, when copy is // Cause duplication of block files on disk, when copy is
// between projects // between projects
locker.create(static_cast<const WaveTrack*>(wc)); locker.emplace(static_cast<const WaveTrack*>(wc));
tracks.Any().StartingWith(*pN).Visit( tracks.Any().StartingWith(*pN).Visit(
[&](WaveTrack *wt, const Track::Fallthrough &fallthrough) { [&](WaveTrack *wt, const Track::Fallthrough &fallthrough) {

View File

@ -347,7 +347,7 @@ class ASAProgress final : public SAProgress {
long mTotalCells; // how many matrix cells? long mTotalCells; // how many matrix cells?
long mCellCount; // how many cells so far? long mCellCount; // how many cells so far?
long mPrevCellCount; // cell_count last reported with Update() long mPrevCellCount; // cell_count last reported with Update()
Maybe<ProgressDialog> mProgress; Optional<ProgressDialog> mProgress;
#ifdef COLLECT_TIMING_DATA #ifdef COLLECT_TIMING_DATA
FILE *mTimeFile; FILE *mTimeFile;
wxDateTime mStartTime; wxDateTime mStartTime;
@ -409,7 +409,7 @@ class ASAProgress final : public SAProgress {
work[1], mFrames[1], is_audio[1]); work[1], mFrames[1], is_audio[1]);
wxFprintf(mTimeFile, "work2 = %g, work3 = %g\n", work2, work3); wxFprintf(mTimeFile, "work2 = %g, work3 = %g\n", work2, work3);
#endif #endif
mProgress.create(XO("Synchronize MIDI with Audio"), mProgress.emplace(XO("Synchronize MIDI with Audio"),
XO("Synchronizing MIDI and Audio Tracks")); XO("Synchronizing MIDI and Audio Tracks"));
} else if (i < 3) { } else if (i < 3) {
wxFprintf(mTimeFile, wxFprintf(mTimeFile,

View File

@ -428,7 +428,7 @@ int ODFFmpegDecoder::Decode(SampleBuffer & data, sampleFormat & format, sampleCo
for (int i = 0; i < mChannels.size(); i++) for (int i = 0; i < mChannels.size(); i++)
{ {
sc = scs[i].get(); sc = scs[i].get();
sc->m_pkt.create(); sc->m_pkt.emplace();
if (DecodeFrame(sc, true) == 0) if (DecodeFrame(sc, true) == 0)
{ {
sc->m_pkt.reset(); sc->m_pkt.reset();

View File

@ -95,8 +95,8 @@ void OverlayPanel::DrawOverlays(bool repaint_all, wxDC *pDC)
} while (!done); } while (!done);
} }
Maybe<wxClientDC> myDC; Optional<wxClientDC> myDC;
auto &dc = pDC ? *pDC : (myDC.create(this), *myDC); auto &dc = pDC ? *pDC : (myDC.emplace(this), *myDC);
// Erase // Erase
auto it2 = pairs.begin(); auto it2 = pairs.begin();