1
0
mirror of https://github.com/cookiengineer/audacity synced 2025-08-01 16:39:30 +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;
{
Maybe<wxLogNull> silence{};
Optional<wxLogNull> 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<char> &data)
wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb"));
{
Maybe<wxLogNull> silence{};
Optional<wxLogNull> silence{};
if (mSilentLog)
silence.create();
silence.emplace();
if (!summaryFile.IsOpened()){

View File

@ -204,16 +204,16 @@ int DirManager::RecursivelyEnumerateWithProgress(const FilePath &dirPath,
int progress_count,
const TranslatableString &message)
{
Maybe<ProgressDialog> progress{};
Optional<ProgressDialog> 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<ProgressDialog> progress{};
Optional<ProgressDialog> 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> dirCleaner;
Optional<DirCleaner> 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.

View File

@ -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;

View File

@ -1005,7 +1005,7 @@ struct streamContext
AVStream *m_stream{}; // an AVStream *
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
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
// so just use the the top level window instead.
{
Maybe<wxWindowDisabler> blocker;
Optional<wxWindowDisabler> blocker;
if (IsShown())
blocker.create(this);
blocker.emplace(this);
wxYieldIfNeeded();
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 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.
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<typename X>
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<typename... Args>
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>(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()
{

View File

@ -515,7 +515,7 @@ bool ProjectFileManager::DoSave (const bool fromSaveAs,
{
std::vector<std::unique_ptr<WaveTrack::Locker>> lockers;
Maybe<DirManager::ProjectSetter> pSetter;
Optional<DirManager::ProjectSetter> 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;

View File

@ -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();

View File

@ -570,7 +570,7 @@ private:
std::vector<EnumValueSymbol> mRadioSymbols;
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.
wxString mRadioValueString; /// Unwrapped string value.
wxRadioButton * DoAddRadioButton(

View File

@ -73,11 +73,11 @@ void ComputeLegacySummaryInfo(const wxFileName &fileName,
int read;
{
Maybe<wxLogNull> silence{};
Optional<wxLogNull> 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<char> &data)
wxFFile summaryFile(mFileName.GetFullPath(), wxT("rb"));
size_t read;
{
Maybe<wxLogNull> silence{};
Optional<wxLogNull> silence{};
if (mSilentLog)
silence.create();
silence.emplace();
if (!summaryFile.IsOpened()) {

View File

@ -356,9 +356,9 @@ bool SimpleBlockFile::ReadSummary(ArrayOf<char> &data)
wxFFile file(mFileName.GetFullPath(), wxT("rb"));
{
Maybe<wxLogNull> silence{};
Optional<wxLogNull> 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()){

View File

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

View File

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

View File

@ -105,7 +105,7 @@ bool EffectFindClipping::SetAutomationParameters(CommandParameters & parms)
bool EffectFindClipping::Process()
{
std::shared_ptr<AddedAnalysisTrack> addedTrack;
Maybe<ModifiedAnalysisTrack> modifiedTrack;
Optional<ModifiedAnalysisTrack> 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;

View File

@ -517,7 +517,7 @@ unsigned VSTEffectsModule::DiscoverPluginsAtPath(
wxString effectIDs = wxT("0;");
wxStringTokenizer effectTzr(effectIDs, wxT(";"));
Maybe<wxProgressDialog> progress{};
Optional<wxProgressDialog> 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<int>(idCnt),

View File

@ -789,9 +789,9 @@ bool NyquistEffect::Process()
XO("Nyquist Error") );
}
Maybe<TrackIterRange<WaveTrack>> pRange;
Optional<TrackIterRange<WaveTrack>> 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

View File

@ -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);

View File

@ -93,7 +93,7 @@ bool DoPasteNothingSelected(AudacityProject &project)
Track* pFirstNewTrack = NULL;
for (auto pClip : clipTrackRange) {
Maybe<WaveTrack::Locker> locker;
Optional<WaveTrack::Locker> 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<WaveTrack::Locker> locker;
Optional<WaveTrack::Locker> 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<WaveTrack::Locker> locker;
Optional<WaveTrack::Locker> locker;
if (clipboard.Project() != &project && wc)
// Cause duplication of block files on disk, when copy is
// between projects
locker.create(static_cast<const WaveTrack*>(wc));
locker.emplace(static_cast<const WaveTrack*>(wc));
tracks.Any().StartingWith(*pN).Visit(
[&](WaveTrack *wt, const Track::Fallthrough &fallthrough) {

View File

@ -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<ProgressDialog> mProgress;
Optional<ProgressDialog> 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,

View File

@ -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();

View File

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