адаптация s13bby/osc под vst и gui. (вайбкод)
вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio. обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
@@ -0,0 +1,281 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
AbstractFifo::AbstractFifo (int backingBufferSize) noexcept : bufferSize (backingBufferSize)
|
||||
{
|
||||
jassert (bufferSize > 0);
|
||||
}
|
||||
|
||||
int AbstractFifo::getTotalSize() const noexcept { return bufferSize; }
|
||||
int AbstractFifo::getFreeSpace() const noexcept { return bufferSize - getNumReady() - 1; }
|
||||
|
||||
int AbstractFifo::getNumReady() const noexcept
|
||||
{
|
||||
auto vs = validStart.get();
|
||||
auto ve = validEnd.get();
|
||||
return ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
|
||||
}
|
||||
|
||||
void AbstractFifo::reset() noexcept
|
||||
{
|
||||
validEnd = 0;
|
||||
validStart = 0;
|
||||
}
|
||||
|
||||
void AbstractFifo::setTotalSize (int newSize) noexcept
|
||||
{
|
||||
jassert (newSize > 0);
|
||||
reset();
|
||||
bufferSize = newSize;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void AbstractFifo::prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1,
|
||||
int& startIndex2, int& blockSize2) const noexcept
|
||||
{
|
||||
auto vs = validStart.get();
|
||||
auto ve = validEnd.get();
|
||||
|
||||
auto freeSpace = ve >= vs ? (bufferSize - (ve - vs)) : (vs - ve);
|
||||
numToWrite = jmin (numToWrite, freeSpace - 1);
|
||||
|
||||
if (numToWrite <= 0)
|
||||
{
|
||||
startIndex1 = 0;
|
||||
startIndex2 = 0;
|
||||
blockSize1 = 0;
|
||||
blockSize2 = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
startIndex1 = ve;
|
||||
startIndex2 = 0;
|
||||
blockSize1 = jmin (bufferSize - ve, numToWrite);
|
||||
numToWrite -= blockSize1;
|
||||
blockSize2 = numToWrite <= 0 ? 0 : jmin (numToWrite, vs);
|
||||
}
|
||||
}
|
||||
|
||||
void AbstractFifo::finishedWrite (int numWritten) noexcept
|
||||
{
|
||||
jassert (numWritten >= 0 && numWritten < bufferSize);
|
||||
|
||||
auto newEnd = validEnd.get() + numWritten;
|
||||
|
||||
if (newEnd >= bufferSize)
|
||||
newEnd -= bufferSize;
|
||||
|
||||
validEnd = newEnd;
|
||||
}
|
||||
|
||||
void AbstractFifo::prepareToRead (int numWanted, int& startIndex1, int& blockSize1,
|
||||
int& startIndex2, int& blockSize2) const noexcept
|
||||
{
|
||||
auto vs = validStart.get();
|
||||
auto ve = validEnd.get();
|
||||
|
||||
auto numReady = ve >= vs ? (ve - vs) : (bufferSize - (vs - ve));
|
||||
numWanted = jmin (numWanted, numReady);
|
||||
|
||||
if (numWanted <= 0)
|
||||
{
|
||||
startIndex1 = 0;
|
||||
startIndex2 = 0;
|
||||
blockSize1 = 0;
|
||||
blockSize2 = 0;
|
||||
}
|
||||
else
|
||||
{
|
||||
startIndex1 = vs;
|
||||
startIndex2 = 0;
|
||||
blockSize1 = jmin (bufferSize - vs, numWanted);
|
||||
numWanted -= blockSize1;
|
||||
blockSize2 = numWanted <= 0 ? 0 : jmin (numWanted, ve);
|
||||
}
|
||||
}
|
||||
|
||||
void AbstractFifo::finishedRead (int numRead) noexcept
|
||||
{
|
||||
jassert (numRead >= 0 && numRead <= bufferSize);
|
||||
|
||||
auto newStart = validStart.get() + numRead;
|
||||
|
||||
if (newStart >= bufferSize)
|
||||
newStart -= bufferSize;
|
||||
|
||||
validStart = newStart;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <AbstractFifo::ReadOrWrite mode>
|
||||
AbstractFifo::ScopedReadWrite<mode>::ScopedReadWrite (ScopedReadWrite&& other) noexcept
|
||||
: startIndex1 (other.startIndex1),
|
||||
blockSize1 (other.blockSize1),
|
||||
startIndex2 (other.startIndex2),
|
||||
blockSize2 (other.blockSize2)
|
||||
{
|
||||
swap (other);
|
||||
}
|
||||
|
||||
template <AbstractFifo::ReadOrWrite mode>
|
||||
AbstractFifo::ScopedReadWrite<mode>&
|
||||
AbstractFifo::ScopedReadWrite<mode>::operator= (ScopedReadWrite&& other) noexcept
|
||||
{
|
||||
swap (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <AbstractFifo::ReadOrWrite mode>
|
||||
void AbstractFifo::ScopedReadWrite<mode>::swap (ScopedReadWrite& other) noexcept
|
||||
{
|
||||
std::swap (other.fifo, fifo);
|
||||
std::swap (other.startIndex1, startIndex1);
|
||||
std::swap (other.blockSize1, blockSize1);
|
||||
std::swap (other.startIndex2, startIndex2);
|
||||
std::swap (other.blockSize2, blockSize2);
|
||||
}
|
||||
|
||||
template class AbstractFifo::ScopedReadWrite<AbstractFifo::ReadOrWrite::read>;
|
||||
template class AbstractFifo::ScopedReadWrite<AbstractFifo::ReadOrWrite::write>;
|
||||
|
||||
AbstractFifo::ScopedRead AbstractFifo::read (int numToRead) noexcept { return { *this, numToRead }; }
|
||||
AbstractFifo::ScopedWrite AbstractFifo::write (int numToWrite) noexcept { return { *this, numToWrite }; }
|
||||
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class AbstractFifoTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
AbstractFifoTests()
|
||||
: UnitTest ("Abstract Fifo", UnitTestCategories::containers)
|
||||
{}
|
||||
|
||||
struct WriteThread final : public Thread
|
||||
{
|
||||
WriteThread (AbstractFifo& f, int* b, Random rng)
|
||||
: Thread ("fifo writer"), fifo (f), buffer (b), random (rng)
|
||||
{
|
||||
startThread();
|
||||
}
|
||||
|
||||
~WriteThread() override
|
||||
{
|
||||
stopThread (5000);
|
||||
}
|
||||
|
||||
void run() override
|
||||
{
|
||||
int n = 0;
|
||||
|
||||
while (! threadShouldExit())
|
||||
{
|
||||
int num = random.nextInt (2000) + 1;
|
||||
|
||||
auto writer = fifo.write (num);
|
||||
|
||||
jassert (writer.blockSize1 >= 0 && writer.blockSize2 >= 0);
|
||||
jassert (writer.blockSize1 == 0
|
||||
|| (writer.startIndex1 >= 0 && writer.startIndex1 < fifo.getTotalSize()));
|
||||
jassert (writer.blockSize2 == 0
|
||||
|| (writer.startIndex2 >= 0 && writer.startIndex2 < fifo.getTotalSize()));
|
||||
|
||||
writer.forEach ([this, &n] (int index) { this->buffer[index] = n++; });
|
||||
}
|
||||
}
|
||||
|
||||
AbstractFifo& fifo;
|
||||
int* buffer;
|
||||
Random random;
|
||||
};
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6262)
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("AbstractFifo");
|
||||
|
||||
int buffer[5000];
|
||||
AbstractFifo fifo (numElementsInArray (buffer));
|
||||
|
||||
WriteThread writer (fifo, buffer, getRandom());
|
||||
|
||||
int n = 0;
|
||||
Random r = getRandom();
|
||||
r.combineSeed (12345);
|
||||
|
||||
for (int count = 100000; --count >= 0;)
|
||||
{
|
||||
int num = r.nextInt (6000) + 1;
|
||||
|
||||
auto reader = fifo.read (num);
|
||||
|
||||
if (! (reader.blockSize1 >= 0 && reader.blockSize2 >= 0)
|
||||
&& (reader.blockSize1 == 0
|
||||
|| (reader.startIndex1 >= 0 && reader.startIndex1 < fifo.getTotalSize()))
|
||||
&& (reader.blockSize2 == 0
|
||||
|| (reader.startIndex2 >= 0 && reader.startIndex2 < fifo.getTotalSize())))
|
||||
{
|
||||
expect (false, "prepareToRead returned -ve values");
|
||||
break;
|
||||
}
|
||||
|
||||
bool failed = false;
|
||||
|
||||
reader.forEach ([&failed, &buffer, &n] (int index)
|
||||
{
|
||||
failed = (buffer[index] != n++) || failed;
|
||||
});
|
||||
|
||||
if (failed)
|
||||
{
|
||||
expect (false, "read values were incorrect");
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
};
|
||||
|
||||
static AbstractFifoTests fifoUnitTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,349 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Encapsulates the logic required to implement a lock-free FIFO.
|
||||
|
||||
This class handles the logic needed when building a single-reader, single-writer FIFO.
|
||||
|
||||
It doesn't actually hold any data itself, but your FIFO class can use one of these to manage
|
||||
its position and status when reading or writing to it.
|
||||
|
||||
To use it, you can call prepareToWrite() to determine the position within your own buffer that
|
||||
an incoming block of data should be stored, and prepareToRead() to find out when the next
|
||||
outgoing block should be read from.
|
||||
|
||||
e.g.
|
||||
@code
|
||||
struct MyFifo
|
||||
{
|
||||
void addToFifo (const int* someData, int numItems)
|
||||
{
|
||||
const auto scope = abstractFifo.write (numItems);
|
||||
|
||||
if (scope.blockSize1 > 0)
|
||||
copySomeData (myBuffer + scope.startIndex1, someData, scope.blockSize1);
|
||||
|
||||
if (scope.blockSize2 > 0)
|
||||
copySomeData (myBuffer + scope.startIndex2, someData + scope.blockSize1, scope.blockSize2);
|
||||
}
|
||||
|
||||
void readFromFifo (int* someData, int numItems)
|
||||
{
|
||||
const auto scope = abstractFifo.read (numItems);
|
||||
|
||||
if (scope.blockSize1 > 0)
|
||||
copySomeData (someData, myBuffer + scope.startIndex1, scope.blockSize1);
|
||||
|
||||
if (scope.blockSize2 > 0)
|
||||
copySomeData (someData + scope.blockSize1, myBuffer + scope.startIndex2, scope.blockSize2);
|
||||
}
|
||||
|
||||
AbstractFifo abstractFifo { 1024 };
|
||||
int myBuffer[1024];
|
||||
};
|
||||
@endcode
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API AbstractFifo
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a FIFO to manage a buffer with the specified size.
|
||||
|
||||
The maximum number of items managed by the FIFO is 1 less than the buffer size.
|
||||
*/
|
||||
explicit AbstractFifo (int bufferSize) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the total size of the buffer being managed. */
|
||||
int getTotalSize() const noexcept;
|
||||
|
||||
/** Returns the number of items that can currently be added to the buffer without it overflowing. */
|
||||
int getFreeSpace() const noexcept;
|
||||
|
||||
/** Returns the number of items that can currently be read from the buffer. */
|
||||
int getNumReady() const noexcept;
|
||||
|
||||
/** Clears the buffer positions, so that it appears empty. */
|
||||
void reset() noexcept;
|
||||
|
||||
/** Changes the buffer's total size.
|
||||
|
||||
Note that this isn't thread-safe, so don't call it if there's any danger that it
|
||||
might overlap with a call to any other method in this class!
|
||||
*/
|
||||
void setTotalSize (int newSize) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the location within the buffer at which an incoming block of data should be written.
|
||||
|
||||
Because the section of data that you want to add to the buffer may overlap the end
|
||||
and wrap around to the start, two blocks within your buffer are returned, and you
|
||||
should copy your data into the first one, with any remaining data spilling over into
|
||||
the second.
|
||||
|
||||
If the number of items you ask for is too large to fit within the buffer's free space, then
|
||||
blockSize1 + blockSize2 may add up to a lower value than numToWrite. If this happens, you
|
||||
may decide to keep waiting and re-trying the method until there's enough space available.
|
||||
|
||||
After calling this method, if you choose to write your data into the blocks returned, you
|
||||
must call finishedWrite() to tell the FIFO how much data you actually added.
|
||||
|
||||
e.g.
|
||||
@code
|
||||
void addToFifo (const int* someData, int numItems)
|
||||
{
|
||||
int start1, size1, start2, size2;
|
||||
prepareToWrite (numItems, start1, size1, start2, size2);
|
||||
|
||||
if (size1 > 0)
|
||||
copySomeData (myBuffer + start1, someData, size1);
|
||||
|
||||
if (size2 > 0)
|
||||
copySomeData (myBuffer + start2, someData + size1, size2);
|
||||
|
||||
finishedWrite (size1 + size2);
|
||||
}
|
||||
@endcode
|
||||
|
||||
@param numToWrite indicates how many items you'd like to add to the buffer
|
||||
@param startIndex1 on exit, this will contain the start index in your buffer at which your data should be written
|
||||
@param blockSize1 on exit, this indicates how many items can be written to the block starting at startIndex1
|
||||
@param startIndex2 on exit, this will contain the start index in your buffer at which any data that didn't fit into
|
||||
the first block should be written
|
||||
@param blockSize2 on exit, this indicates how many items can be written to the block starting at startIndex2
|
||||
@see finishedWrite
|
||||
*/
|
||||
void prepareToWrite (int numToWrite, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
|
||||
|
||||
/** Called after writing to the FIFO, to indicate that this many items have been added.
|
||||
@see prepareToWrite
|
||||
*/
|
||||
void finishedWrite (int numWritten) noexcept;
|
||||
|
||||
/** Returns the location within the buffer from which the next block of data should be read.
|
||||
|
||||
Because the section of data that you want to read from the buffer may overlap the end
|
||||
and wrap around to the start, two blocks within your buffer are returned, and you
|
||||
should read from both of them.
|
||||
|
||||
If the number of items you ask for is greater than the amount of data available, then
|
||||
blockSize1 + blockSize2 may add up to a lower value than numWanted. If this happens, you
|
||||
may decide to keep waiting and re-trying the method until there's enough data available.
|
||||
|
||||
After calling this method, if you choose to read the data, you must call finishedRead() to
|
||||
tell the FIFO how much data you have consumed.
|
||||
|
||||
e.g.
|
||||
@code
|
||||
void readFromFifo (int* someData, int numItems)
|
||||
{
|
||||
int start1, size1, start2, size2;
|
||||
prepareToRead (numSamples, start1, size1, start2, size2);
|
||||
|
||||
if (size1 > 0)
|
||||
copySomeData (someData, myBuffer + start1, size1);
|
||||
|
||||
if (size2 > 0)
|
||||
copySomeData (someData + size1, myBuffer + start2, size2);
|
||||
|
||||
finishedRead (size1 + size2);
|
||||
}
|
||||
@endcode
|
||||
|
||||
@param numWanted indicates how many items you'd like to read from the buffer
|
||||
@param startIndex1 on exit, this will contain the start index in your buffer from which your data should be read
|
||||
@param blockSize1 on exit, this indicates how many items can be read from the block starting at startIndex1
|
||||
@param startIndex2 on exit, this will contain the start index in your buffer from which any data that didn't fit into
|
||||
the first block should be read
|
||||
@param blockSize2 on exit, this indicates how many items can be read from the block starting at startIndex2
|
||||
@see finishedRead
|
||||
*/
|
||||
void prepareToRead (int numWanted, int& startIndex1, int& blockSize1, int& startIndex2, int& blockSize2) const noexcept;
|
||||
|
||||
/** Called after reading from the FIFO, to indicate that this many items have now been consumed.
|
||||
@see prepareToRead
|
||||
*/
|
||||
void finishedRead (int numRead) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
|
||||
private:
|
||||
enum class ReadOrWrite
|
||||
{
|
||||
read,
|
||||
write
|
||||
};
|
||||
|
||||
public:
|
||||
/** Class for a scoped reader/writer */
|
||||
template <ReadOrWrite mode>
|
||||
class ScopedReadWrite final
|
||||
{
|
||||
public:
|
||||
/** Construct an unassigned reader/writer. Doesn't do anything upon destruction. */
|
||||
ScopedReadWrite() = default;
|
||||
|
||||
/** Construct a reader/writer and immediately call prepareRead/prepareWrite
|
||||
on the abstractFifo which was passed in.
|
||||
This object will hold a pointer back to the fifo, so make sure that
|
||||
the fifo outlives this object.
|
||||
*/
|
||||
ScopedReadWrite (AbstractFifo& f, int num) noexcept : fifo (&f)
|
||||
{
|
||||
prepare (*fifo, num);
|
||||
}
|
||||
|
||||
ScopedReadWrite (const ScopedReadWrite&) = delete;
|
||||
ScopedReadWrite (ScopedReadWrite&&) noexcept;
|
||||
|
||||
ScopedReadWrite& operator= (const ScopedReadWrite&) = delete;
|
||||
ScopedReadWrite& operator= (ScopedReadWrite&&) noexcept;
|
||||
|
||||
/** Calls finishedRead or finishedWrite if this is a non-null scoped
|
||||
reader/writer.
|
||||
*/
|
||||
~ScopedReadWrite() noexcept
|
||||
{
|
||||
if (fifo != nullptr)
|
||||
finish (*fifo, blockSize1 + blockSize2);
|
||||
}
|
||||
|
||||
/** Calls the passed function with each index that was deemed valid
|
||||
for the current read/write operation.
|
||||
*/
|
||||
template <typename FunctionToApply>
|
||||
void forEach (FunctionToApply&& func) const
|
||||
{
|
||||
for (auto i = startIndex1, e = startIndex1 + blockSize1; i != e; ++i) func (i);
|
||||
for (auto i = startIndex2, e = startIndex2 + blockSize2; i != e; ++i) func (i);
|
||||
}
|
||||
|
||||
int startIndex1, blockSize1, startIndex2, blockSize2;
|
||||
|
||||
private:
|
||||
void prepare (AbstractFifo&, int) noexcept;
|
||||
static void finish (AbstractFifo&, int) noexcept;
|
||||
void swap (ScopedReadWrite&) noexcept;
|
||||
|
||||
AbstractFifo* fifo = nullptr;
|
||||
};
|
||||
|
||||
using ScopedRead = ScopedReadWrite<ReadOrWrite::read>;
|
||||
using ScopedWrite = ScopedReadWrite<ReadOrWrite::write>;
|
||||
|
||||
/** Replaces prepareToRead/finishedRead with a single function.
|
||||
This function returns an object which contains the start indices and
|
||||
block sizes, and also automatically finishes the read operation when
|
||||
it goes out of scope.
|
||||
@code
|
||||
{
|
||||
auto readHandle = fifo.read (4);
|
||||
|
||||
for (auto i = 0; i != readHandle.blockSize1; ++i)
|
||||
{
|
||||
// read the item at index readHandle.startIndex1 + i
|
||||
}
|
||||
|
||||
for (auto i = 0; i != readHandle.blockSize2; ++i)
|
||||
{
|
||||
// read the item at index readHandle.startIndex2 + i
|
||||
}
|
||||
} // readHandle goes out of scope here, finishing the read operation
|
||||
@endcode
|
||||
*/
|
||||
ScopedRead read (int numToRead) noexcept;
|
||||
|
||||
/** Replaces prepareToWrite/finishedWrite with a single function.
|
||||
This function returns an object which contains the start indices and
|
||||
block sizes, and also automatically finishes the write operation when
|
||||
it goes out of scope.
|
||||
@code
|
||||
{
|
||||
auto writeHandle = fifo.write (5);
|
||||
|
||||
for (auto i = 0; i != writeHandle.blockSize1; ++i)
|
||||
{
|
||||
// write the item at index writeHandle.startIndex1 + i
|
||||
}
|
||||
|
||||
for (auto i = 0; i != writeHandle.blockSize2; ++i)
|
||||
{
|
||||
// write the item at index writeHandle.startIndex2 + i
|
||||
}
|
||||
} // writeHandle goes out of scope here, finishing the write operation
|
||||
@endcode
|
||||
*/
|
||||
ScopedWrite write (int numToWrite) noexcept;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
int bufferSize;
|
||||
Atomic<int> validStart, validEnd;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AbstractFifo)
|
||||
};
|
||||
|
||||
template <>
|
||||
inline void AbstractFifo::ScopedReadWrite<AbstractFifo::ReadOrWrite::read>::finish (AbstractFifo& f, int num) noexcept
|
||||
{
|
||||
f.finishedRead (num);
|
||||
}
|
||||
|
||||
template <>
|
||||
inline void AbstractFifo::ScopedReadWrite<AbstractFifo::ReadOrWrite::write>::finish (AbstractFifo& f, int num) noexcept
|
||||
{
|
||||
f.finishedWrite (num);
|
||||
}
|
||||
|
||||
template <>
|
||||
inline void AbstractFifo::ScopedReadWrite<AbstractFifo::ReadOrWrite::read>::prepare (AbstractFifo& f, int num) noexcept
|
||||
{
|
||||
f.prepareToRead (num, startIndex1, blockSize1, startIndex2, blockSize2);
|
||||
}
|
||||
|
||||
template <>
|
||||
inline void AbstractFifo::ScopedReadWrite<AbstractFifo::ReadOrWrite::write>::prepare (AbstractFifo& f, int num) noexcept
|
||||
{
|
||||
f.prepareToWrite (num, startIndex1, blockSize1, startIndex2, blockSize2);
|
||||
}
|
||||
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,133 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Implements some basic array storage allocation functions.
|
||||
|
||||
This class isn't really for public use - it used to be part of the
|
||||
container classes but has since been superseded by ArrayBase. Eventually
|
||||
it will be removed from the API.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class ElementType, class TypeOfCriticalSectionToUse>
|
||||
class ArrayAllocationBase : public TypeOfCriticalSectionToUse
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty array. */
|
||||
ArrayAllocationBase() = default;
|
||||
|
||||
/** Destructor. */
|
||||
~ArrayAllocationBase() = default;
|
||||
|
||||
ArrayAllocationBase (ArrayAllocationBase&& other) noexcept
|
||||
: elements (std::move (other.elements)),
|
||||
numAllocated (other.numAllocated)
|
||||
{
|
||||
}
|
||||
|
||||
ArrayAllocationBase& operator= (ArrayAllocationBase&& other) noexcept
|
||||
{
|
||||
elements = std::move (other.elements);
|
||||
numAllocated = other.numAllocated;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Changes the amount of storage allocated.
|
||||
|
||||
This will retain any data currently held in the array, and either add or
|
||||
remove extra space at the end.
|
||||
|
||||
@param numElements the number of elements that are needed
|
||||
*/
|
||||
void setAllocatedSize (int numElements)
|
||||
{
|
||||
if (numAllocated != numElements)
|
||||
{
|
||||
if (numElements > 0)
|
||||
elements.realloc ((size_t) numElements);
|
||||
else
|
||||
elements.free();
|
||||
|
||||
numAllocated = numElements;
|
||||
}
|
||||
}
|
||||
|
||||
/** Increases the amount of storage allocated if it is less than a given amount.
|
||||
|
||||
This will retain any data currently held in the array, but will add
|
||||
extra space at the end to make sure there it's at least as big as the size
|
||||
passed in. If it's already bigger, no action is taken.
|
||||
|
||||
@param minNumElements the minimum number of elements that are needed
|
||||
*/
|
||||
void ensureAllocatedSize (int minNumElements)
|
||||
{
|
||||
if (minNumElements > numAllocated)
|
||||
setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
|
||||
|
||||
jassert (numAllocated <= 0 || elements != nullptr);
|
||||
}
|
||||
|
||||
/** Minimises the amount of storage allocated so that it's no more than
|
||||
the given number of elements.
|
||||
*/
|
||||
void shrinkToNoMoreThan (int maxNumElements)
|
||||
{
|
||||
if (maxNumElements < numAllocated)
|
||||
setAllocatedSize (maxNumElements);
|
||||
}
|
||||
|
||||
/** Swap the contents of two objects. */
|
||||
void swapWith (ArrayAllocationBase& other) noexcept
|
||||
{
|
||||
elements.swapWith (other.elements);
|
||||
std::swap (numAllocated, other.numAllocated);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
HeapBlock<ElementType> elements;
|
||||
int numAllocated = 0;
|
||||
|
||||
private:
|
||||
JUCE_DECLARE_NON_COPYABLE (ArrayAllocationBase)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,612 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
namespace ArrayBaseTestsHelpers
|
||||
{
|
||||
class TriviallyCopyableType
|
||||
{
|
||||
public:
|
||||
TriviallyCopyableType() = default;
|
||||
|
||||
TriviallyCopyableType (int v)
|
||||
: value (v)
|
||||
{}
|
||||
|
||||
TriviallyCopyableType (float v)
|
||||
: value ((int) v)
|
||||
{}
|
||||
|
||||
bool operator== (const TriviallyCopyableType& other) const
|
||||
{
|
||||
return getValue() == other.getValue();
|
||||
}
|
||||
|
||||
int getValue() const { return value; }
|
||||
|
||||
private:
|
||||
int value { -1111 };
|
||||
};
|
||||
|
||||
class NonTriviallyCopyableType
|
||||
{
|
||||
public:
|
||||
NonTriviallyCopyableType() = default;
|
||||
|
||||
NonTriviallyCopyableType (int v)
|
||||
: value (v)
|
||||
{}
|
||||
|
||||
NonTriviallyCopyableType (float v)
|
||||
: value ((int) v)
|
||||
{}
|
||||
|
||||
NonTriviallyCopyableType (const NonTriviallyCopyableType& other)
|
||||
: value (other.value)
|
||||
{}
|
||||
|
||||
NonTriviallyCopyableType& operator= (const NonTriviallyCopyableType& other)
|
||||
{
|
||||
value = other.value;
|
||||
return *this;
|
||||
}
|
||||
|
||||
bool operator== (const NonTriviallyCopyableType& other) const
|
||||
{
|
||||
return getValue() == other.getValue();
|
||||
}
|
||||
|
||||
int getValue() const { return *ptr; }
|
||||
|
||||
private:
|
||||
int value { -1111 };
|
||||
int* ptr = &value;
|
||||
};
|
||||
}
|
||||
|
||||
static bool operator== (const ArrayBaseTestsHelpers::TriviallyCopyableType& tct,
|
||||
const ArrayBaseTestsHelpers::NonTriviallyCopyableType& ntct)
|
||||
{
|
||||
return tct.getValue() == ntct.getValue();
|
||||
}
|
||||
|
||||
static bool operator== (const ArrayBaseTestsHelpers::NonTriviallyCopyableType& ntct,
|
||||
const ArrayBaseTestsHelpers::TriviallyCopyableType& tct)
|
||||
{
|
||||
return tct == ntct;
|
||||
}
|
||||
|
||||
class ArrayBaseTests final : public UnitTest
|
||||
{
|
||||
using CopyableType = ArrayBaseTestsHelpers::TriviallyCopyableType;
|
||||
using NoncopyableType = ArrayBaseTestsHelpers::NonTriviallyCopyableType;
|
||||
|
||||
#if ! (defined (__GNUC__) && __GNUC__ < 5 && ! defined (__clang__))
|
||||
static_assert (std::is_trivially_copyable_v<CopyableType>,
|
||||
"Test TriviallyCopyableType is not trivially copyable");
|
||||
static_assert (! std::is_trivially_copyable_v<NoncopyableType>,
|
||||
"Test NonTriviallyCopyableType is trivially copyable");
|
||||
#endif
|
||||
|
||||
public:
|
||||
ArrayBaseTests()
|
||||
: UnitTest ("ArrayBase", UnitTestCategories::containers)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("grow capacity");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
int originalCapacity = 4;
|
||||
referenceContainer.reserve ((size_t) originalCapacity);
|
||||
expectEquals ((int) referenceContainer.capacity(), originalCapacity);
|
||||
copyableContainer.setAllocatedSize (originalCapacity);
|
||||
expectEquals (copyableContainer.capacity(), originalCapacity);
|
||||
noncopyableContainer.setAllocatedSize (originalCapacity);
|
||||
expectEquals (noncopyableContainer.capacity(), originalCapacity);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, 33);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
expect ((int) referenceContainer.capacity() != originalCapacity);
|
||||
expect (copyableContainer.capacity() != originalCapacity);
|
||||
expect (noncopyableContainer.capacity() != originalCapacity);
|
||||
}
|
||||
|
||||
beginTest ("shrink capacity");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
int numElements = 45;
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, numElements);
|
||||
|
||||
copyableContainer.shrinkToNoMoreThan (numElements);
|
||||
noncopyableContainer.setAllocatedSize (numElements + 1);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
referenceContainer.clear();
|
||||
copyableContainer.removeElements (0, numElements);
|
||||
noncopyableContainer.removeElements (0, numElements);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
copyableContainer.setAllocatedSize (0);
|
||||
noncopyableContainer.setAllocatedSize (0);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, numElements);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("equality");
|
||||
{
|
||||
std::vector<int> referenceContainer = { 1, 2, 3 };
|
||||
ArrayBase<int, DummyCriticalSection> testContainer1, testContainer2;
|
||||
|
||||
for (auto i : referenceContainer)
|
||||
{
|
||||
testContainer1.add (i);
|
||||
testContainer2.add (i);
|
||||
}
|
||||
|
||||
expect (testContainer1 == referenceContainer);
|
||||
expect (testContainer2 == testContainer1);
|
||||
|
||||
testContainer1.ensureAllocatedSize (257);
|
||||
referenceContainer.shrink_to_fit();
|
||||
|
||||
expect (testContainer1 == referenceContainer);
|
||||
expect (testContainer2 == testContainer1);
|
||||
|
||||
testContainer1.removeElements (0, 1);
|
||||
|
||||
expect (testContainer1 != referenceContainer);
|
||||
expect (testContainer2 != testContainer1);
|
||||
}
|
||||
|
||||
beginTest ("accessors");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, 3);
|
||||
|
||||
int testValue = -123;
|
||||
referenceContainer[0] = testValue;
|
||||
copyableContainer[0] = testValue;
|
||||
noncopyableContainer[0] = testValue;
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
expect (copyableContainer .getFirst().getValue() == testValue);
|
||||
expect (noncopyableContainer.getFirst().getValue() == testValue);
|
||||
|
||||
auto last = referenceContainer.back().getValue();
|
||||
|
||||
expectEquals (copyableContainer .getLast().getValue(), last);
|
||||
expectEquals (noncopyableContainer.getLast().getValue(), last);
|
||||
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableEmpty;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableEmpty;
|
||||
|
||||
auto defualtValue = CopyableType().getValue();
|
||||
expectEquals (defualtValue, NoncopyableType().getValue());
|
||||
|
||||
expectEquals (copyableEmpty .getFirst().getValue(), defualtValue);
|
||||
expectEquals (noncopyableEmpty.getFirst().getValue(), defualtValue);
|
||||
expectEquals (copyableEmpty .getLast() .getValue(), defualtValue);
|
||||
expectEquals (noncopyableEmpty.getLast() .getValue(), defualtValue);
|
||||
|
||||
ArrayBase<float*, DummyCriticalSection> floatPointers;
|
||||
expect (floatPointers.getValueWithDefault (-3) == nullptr);
|
||||
}
|
||||
|
||||
beginTest ("add moved");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
CopyableType ref (-i);
|
||||
CopyableType ct (-i);
|
||||
NoncopyableType nct (-i);
|
||||
referenceContainer.push_back (std::move (ref));
|
||||
copyableContainer.add (std::move (ct));
|
||||
noncopyableContainer.add (std::move (nct));
|
||||
}
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("add multiple");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
for (int i = 4; i < 7; ++i)
|
||||
referenceContainer.push_back ({ -i });
|
||||
|
||||
copyableContainer.add (CopyableType (-4), CopyableType (-5), CopyableType (-6));
|
||||
noncopyableContainer.add (NoncopyableType (-4), NoncopyableType (-5), NoncopyableType (-6));
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("add array from a pointer");
|
||||
{
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
std::vector<CopyableType> copyableData = { 3, 4, 5 };
|
||||
std::vector<NoncopyableType> noncopyableData = { 3, 4, 5 };
|
||||
|
||||
copyableContainer.addArray (copyableData.data(), (int) copyableData.size());
|
||||
noncopyableContainer.addArray (noncopyableData.data(), (int) noncopyableData.size());
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, copyableData);
|
||||
}
|
||||
|
||||
beginTest ("add array from a pointer of a different type");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
std::vector<float> floatData = { 1.4f, 2.5f, 3.6f };
|
||||
|
||||
for (auto f : floatData)
|
||||
referenceContainer.push_back ({ f });
|
||||
|
||||
copyableContainer.addArray (floatData.data(), (int) floatData.size());
|
||||
noncopyableContainer.addArray (floatData.data(), (int) floatData.size());
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("add array from initializer_list");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
std::initializer_list<CopyableType> ilct { { 3 }, { 4 }, { 5 } };
|
||||
std::initializer_list<NoncopyableType> ilnct { { 3 }, { 4 }, { 5 } };
|
||||
|
||||
for (auto v : ilct)
|
||||
referenceContainer.push_back ({ v });
|
||||
|
||||
copyableContainer.addArray (ilct);
|
||||
noncopyableContainer.addArray (ilnct);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("add array from containers");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, 5);
|
||||
|
||||
std::vector<CopyableType> referenceContainerCopy (referenceContainer);
|
||||
std::vector<NoncopyableType> noncopyableReferenceContainerCopy;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainerCopy;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainerCopy;
|
||||
|
||||
for (auto& v : referenceContainerCopy)
|
||||
noncopyableReferenceContainerCopy.push_back ({ v.getValue() });
|
||||
|
||||
for (size_t i = 0; i < referenceContainerCopy.size(); ++i)
|
||||
{
|
||||
auto value = referenceContainerCopy[i].getValue();
|
||||
copyableContainerCopy.add ({ value });
|
||||
noncopyableContainerCopy.add ({ value });
|
||||
}
|
||||
|
||||
// From self-types
|
||||
copyableContainer.addArray (copyableContainerCopy);
|
||||
noncopyableContainer.addArray (noncopyableContainerCopy);
|
||||
|
||||
for (auto v : referenceContainerCopy)
|
||||
referenceContainer.push_back (v);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
// From std containers
|
||||
copyableContainer.addArray (referenceContainerCopy);
|
||||
noncopyableContainer.addArray (noncopyableReferenceContainerCopy);
|
||||
|
||||
for (auto v : referenceContainerCopy)
|
||||
referenceContainer.push_back (v);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
// From std containers with offset
|
||||
int offset = 5;
|
||||
copyableContainer.addArray (referenceContainerCopy, offset);
|
||||
noncopyableContainer.addArray (noncopyableReferenceContainerCopy, offset);
|
||||
|
||||
for (size_t i = 5; i < referenceContainerCopy.size(); ++i)
|
||||
referenceContainer.push_back (referenceContainerCopy[i]);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("insert");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, 8);
|
||||
|
||||
referenceContainer.insert (referenceContainer.begin(), -4);
|
||||
copyableContainer.insert (0, -4, 1);
|
||||
noncopyableContainer.insert (0, -4, 1);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
for (int i = 0; i < 3; ++i)
|
||||
referenceContainer.insert (referenceContainer.begin() + 1, -3);
|
||||
|
||||
copyableContainer.insert (1, -3, 3);
|
||||
noncopyableContainer.insert (1, -3, 3);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
for (int i = 0; i < 50; ++i)
|
||||
referenceContainer.insert (referenceContainer.end() - 1, -9);
|
||||
|
||||
copyableContainer.insert (copyableContainer.size() - 2, -9, 50);
|
||||
noncopyableContainer.insert (noncopyableContainer.size() - 2, -9, 50);
|
||||
}
|
||||
|
||||
beginTest ("insert array");
|
||||
{
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
std::vector<CopyableType> copyableData = { 3, 4, 5, 6, 7, 8 };
|
||||
std::vector<NoncopyableType> noncopyableData = { 3, 4, 5, 6, 7, 8 };
|
||||
|
||||
std::vector<CopyableType> referenceContainer { copyableData };
|
||||
|
||||
copyableContainer.insertArray (0, copyableData.data(), (int) copyableData.size());
|
||||
noncopyableContainer.insertArray (0, noncopyableData.data(), (int) noncopyableData.size());
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
int insertPos = copyableContainer.size() - 1;
|
||||
|
||||
for (auto it = copyableData.end(); it != copyableData.begin(); --it)
|
||||
referenceContainer.insert (referenceContainer.begin() + insertPos, CopyableType (*(it - 1)));
|
||||
|
||||
copyableContainer.insertArray (insertPos, copyableData.data(), (int) copyableData.size());
|
||||
noncopyableContainer.insertArray (insertPos, noncopyableData.data(), (int) noncopyableData.size());
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("remove");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, 17);
|
||||
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
referenceContainer.erase (referenceContainer.begin() + i);
|
||||
copyableContainer.removeElements (i, 1);
|
||||
noncopyableContainer.removeElements (i, 1);
|
||||
}
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, 17);
|
||||
int blockSize = 3;
|
||||
|
||||
for (int i = 0; i < 4; ++i)
|
||||
{
|
||||
for (int j = 0; j < blockSize; ++j)
|
||||
referenceContainer.erase (referenceContainer.begin() + i);
|
||||
|
||||
copyableContainer.removeElements (i, blockSize);
|
||||
noncopyableContainer.removeElements (i, blockSize);
|
||||
}
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
|
||||
auto numToRemove = copyableContainer.size() - 2;
|
||||
|
||||
for (int i = 0; i < numToRemove; ++i)
|
||||
referenceContainer.erase (referenceContainer.begin() + 1);
|
||||
|
||||
copyableContainer.removeElements (1, numToRemove);
|
||||
noncopyableContainer.removeElements (1, numToRemove);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
|
||||
beginTest ("move");
|
||||
{
|
||||
std::vector<CopyableType> referenceContainer;
|
||||
ArrayBase<CopyableType, DummyCriticalSection> copyableContainer;
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection> noncopyableContainer;
|
||||
|
||||
addData (referenceContainer, copyableContainer, noncopyableContainer, 6);
|
||||
|
||||
std::vector<std::pair<int, int>> testValues;
|
||||
testValues.emplace_back (2, 4);
|
||||
testValues.emplace_back (0, 5);
|
||||
testValues.emplace_back (4, 1);
|
||||
testValues.emplace_back (5, 0);
|
||||
|
||||
for (auto p : testValues)
|
||||
{
|
||||
if (p.second > p.first)
|
||||
std::rotate (referenceContainer.begin() + p.first,
|
||||
referenceContainer.begin() + p.first + 1,
|
||||
referenceContainer.begin() + p.second + 1);
|
||||
else
|
||||
std::rotate (referenceContainer.begin() + p.second,
|
||||
referenceContainer.begin() + p.first,
|
||||
referenceContainer.begin() + p.first + 1);
|
||||
|
||||
copyableContainer.move (p.first, p.second);
|
||||
noncopyableContainer.move (p.first, p.second);
|
||||
|
||||
checkEqual (copyableContainer, noncopyableContainer, referenceContainer);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("After converting move construction, ownership is transferred");
|
||||
{
|
||||
Derived obj;
|
||||
ArrayBase<Derived*, DummyCriticalSection> derived;
|
||||
derived.setAllocatedSize (5);
|
||||
derived.add (&obj);
|
||||
|
||||
ArrayBase<Base*, DummyCriticalSection> base { std::move (derived) };
|
||||
|
||||
expectEquals (base.capacity(), 5);
|
||||
expectEquals (base.size(), 1);
|
||||
expect (base.getFirst() == &obj);
|
||||
expectEquals (derived.capacity(), 0);
|
||||
expectEquals (derived.size(), 0);
|
||||
expect (derived.data() == nullptr);
|
||||
}
|
||||
|
||||
beginTest ("After converting move assignment, ownership is transferred");
|
||||
{
|
||||
Derived obj;
|
||||
ArrayBase<Derived*, DummyCriticalSection> derived;
|
||||
derived.setAllocatedSize (5);
|
||||
derived.add (&obj);
|
||||
ArrayBase<Base*, DummyCriticalSection> base;
|
||||
|
||||
base = std::move (derived);
|
||||
|
||||
expectEquals (base.capacity(), 5);
|
||||
expectEquals (base.size(), 1);
|
||||
expect (base.getFirst() == &obj);
|
||||
expectEquals (derived.capacity(), 0);
|
||||
expectEquals (derived.size(), 0);
|
||||
expect (derived.data() == nullptr);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
struct Base
|
||||
{
|
||||
virtual ~Base() = default;
|
||||
};
|
||||
|
||||
struct Derived final : public Base
|
||||
{
|
||||
};
|
||||
|
||||
static void addData (std::vector<CopyableType>& referenceContainer,
|
||||
ArrayBase<CopyableType, DummyCriticalSection>& copyableContainer,
|
||||
ArrayBase<NoncopyableType, DummyCriticalSection>& NoncopyableContainer,
|
||||
int numValues)
|
||||
{
|
||||
for (int i = 0; i < numValues; ++i)
|
||||
{
|
||||
referenceContainer.push_back ({ i });
|
||||
copyableContainer.add ({ i });
|
||||
NoncopyableContainer.add ({ i });
|
||||
}
|
||||
}
|
||||
|
||||
template <typename A, typename B>
|
||||
void checkEqual (const ArrayBase<A, DummyCriticalSection>& a,
|
||||
const ArrayBase<B, DummyCriticalSection>& b)
|
||||
{
|
||||
expectEquals ((int) a.size(), (int) b.size());
|
||||
|
||||
for (int i = 0; i < (int) a.size(); ++i)
|
||||
expect (a[i] == b[i]);
|
||||
}
|
||||
|
||||
template <typename A, typename B>
|
||||
void checkEqual (ArrayBase<A, DummyCriticalSection>& a,
|
||||
std::vector<B>& b)
|
||||
{
|
||||
expectEquals ((int) a.size(), (int) b.size());
|
||||
|
||||
for (int i = 0; i < (int) a.size(); ++i)
|
||||
expect (a[i] == b[(size_t) i]);
|
||||
}
|
||||
|
||||
template <typename A, typename B, typename C>
|
||||
void checkEqual (ArrayBase<A, DummyCriticalSection>& a,
|
||||
ArrayBase<B, DummyCriticalSection>& b,
|
||||
std::vector<C>& c)
|
||||
{
|
||||
checkEqual (a, b);
|
||||
checkEqual (a, c);
|
||||
checkEqual (b, c);
|
||||
}
|
||||
};
|
||||
|
||||
static ArrayBaseTests arrayBaseTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,614 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/**
|
||||
A basic object container.
|
||||
|
||||
This class isn't really for public use - it's used by the other
|
||||
array classes, but might come in handy for some purposes.
|
||||
|
||||
It inherits from a critical section class to allow the arrays to use
|
||||
the "empty base class optimisation" pattern to reduce their footprint.
|
||||
|
||||
@see Array, OwnedArray, ReferenceCountedArray
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class ElementType, class TypeOfCriticalSectionToUse>
|
||||
class ArrayBase : public TypeOfCriticalSectionToUse
|
||||
{
|
||||
private:
|
||||
using ParameterType = typename TypeHelpers::ParameterType<ElementType>::type;
|
||||
|
||||
static_assert (std::is_nothrow_constructible_v<TypeOfCriticalSectionToUse>,
|
||||
"The critical section type used must not throw during construction");
|
||||
|
||||
template <class OtherElementType, class OtherCriticalSection>
|
||||
using AllowConversion = std::enable_if_t<! std::is_same_v<std::tuple<ElementType, TypeOfCriticalSectionToUse>,
|
||||
std::tuple<OtherElementType, OtherCriticalSection>>>;
|
||||
|
||||
public:
|
||||
//==============================================================================
|
||||
ArrayBase() noexcept = default;
|
||||
|
||||
~ArrayBase()
|
||||
{
|
||||
clear();
|
||||
}
|
||||
|
||||
ArrayBase (ArrayBase&& other) noexcept
|
||||
: elements (std::move (other.elements)),
|
||||
numAllocated (other.numAllocated),
|
||||
numUsed (other.numUsed)
|
||||
{
|
||||
other.numAllocated = 0;
|
||||
other.numUsed = 0;
|
||||
}
|
||||
|
||||
ArrayBase& operator= (ArrayBase&& other) noexcept
|
||||
{
|
||||
if (this != &other)
|
||||
{
|
||||
auto tmp (std::move (other));
|
||||
swapWith (tmp);
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Converting move constructor.
|
||||
Only enabled when the other array has a different type to this one.
|
||||
If you see a compile error here, it's probably because you're attempting a conversion that
|
||||
HeapBlock won't allow.
|
||||
*/
|
||||
template <class OtherElementType,
|
||||
class OtherCriticalSection,
|
||||
typename = AllowConversion<OtherElementType, OtherCriticalSection>>
|
||||
ArrayBase (ArrayBase<OtherElementType, OtherCriticalSection>&& other) noexcept
|
||||
: elements (std::move (other.elements)),
|
||||
numAllocated (other.numAllocated),
|
||||
numUsed (other.numUsed)
|
||||
{
|
||||
other.numAllocated = 0;
|
||||
other.numUsed = 0;
|
||||
}
|
||||
|
||||
/** Converting move assignment operator.
|
||||
Only enabled when the other array has a different type to this one.
|
||||
If you see a compile error here, it's probably because you're attempting a conversion that
|
||||
HeapBlock won't allow.
|
||||
*/
|
||||
template <class OtherElementType,
|
||||
class OtherCriticalSection,
|
||||
typename = AllowConversion<OtherElementType, OtherCriticalSection>>
|
||||
ArrayBase& operator= (ArrayBase<OtherElementType, OtherCriticalSection>&& other) noexcept
|
||||
{
|
||||
// No need to worry about assignment to *this, because 'other' must be of a different type.
|
||||
elements = std::move (other.elements);
|
||||
numAllocated = other.numAllocated;
|
||||
numUsed = other.numUsed;
|
||||
|
||||
other.numAllocated = 0;
|
||||
other.numUsed = 0;
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <class OtherArrayType>
|
||||
bool operator== (const OtherArrayType& other) const noexcept
|
||||
{
|
||||
if (size() != (int) other.size())
|
||||
return false;
|
||||
|
||||
auto* e = begin();
|
||||
|
||||
for (auto& o : other)
|
||||
if (! exactlyEqual (*e++, o))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <class OtherArrayType>
|
||||
bool operator!= (const OtherArrayType& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
inline ElementType& operator[] (const int index) noexcept
|
||||
{
|
||||
jassert (elements != nullptr);
|
||||
jassert (isPositiveAndBelow (index, numUsed));
|
||||
return elements[index];
|
||||
}
|
||||
|
||||
inline const ElementType& operator[] (const int index) const noexcept
|
||||
{
|
||||
jassert (elements != nullptr);
|
||||
jassert (isPositiveAndBelow (index, numUsed));
|
||||
return elements[index];
|
||||
}
|
||||
|
||||
inline ElementType getValueWithDefault (const int index) const noexcept
|
||||
{
|
||||
return isPositiveAndBelow (index, numUsed) ? elements[index] : ElementType();
|
||||
}
|
||||
|
||||
inline ElementType getFirst() const noexcept
|
||||
{
|
||||
return numUsed > 0 ? elements[0] : ElementType();
|
||||
}
|
||||
|
||||
inline ElementType getLast() const noexcept
|
||||
{
|
||||
return numUsed > 0 ? elements[numUsed - 1] : ElementType();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
inline ElementType* begin() noexcept
|
||||
{
|
||||
return elements;
|
||||
}
|
||||
|
||||
inline const ElementType* begin() const noexcept
|
||||
{
|
||||
return elements;
|
||||
}
|
||||
|
||||
inline ElementType* end() noexcept
|
||||
{
|
||||
return elements + numUsed;
|
||||
}
|
||||
|
||||
inline const ElementType* end() const noexcept
|
||||
{
|
||||
return elements + numUsed;
|
||||
}
|
||||
|
||||
inline ElementType* data() noexcept
|
||||
{
|
||||
return elements;
|
||||
}
|
||||
|
||||
inline const ElementType* data() const noexcept
|
||||
{
|
||||
return elements;
|
||||
}
|
||||
|
||||
inline int size() const noexcept
|
||||
{
|
||||
return numUsed;
|
||||
}
|
||||
|
||||
inline int capacity() const noexcept
|
||||
{
|
||||
return numAllocated;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void setAllocatedSize (int numElements)
|
||||
{
|
||||
jassert (numElements >= numUsed);
|
||||
|
||||
if (numAllocated != numElements)
|
||||
{
|
||||
if (numElements > 0)
|
||||
setAllocatedSizeInternal (numElements);
|
||||
else
|
||||
elements.free();
|
||||
}
|
||||
|
||||
numAllocated = numElements;
|
||||
}
|
||||
|
||||
void ensureAllocatedSize (int minNumElements)
|
||||
{
|
||||
if (minNumElements > numAllocated)
|
||||
setAllocatedSize ((minNumElements + minNumElements / 2 + 8) & ~7);
|
||||
|
||||
jassert (numAllocated <= 0 || elements != nullptr);
|
||||
}
|
||||
|
||||
void shrinkToNoMoreThan (int maxNumElements)
|
||||
{
|
||||
if (maxNumElements < numAllocated)
|
||||
setAllocatedSize (maxNumElements);
|
||||
}
|
||||
|
||||
void clear()
|
||||
{
|
||||
for (int i = 0; i < numUsed; ++i)
|
||||
elements[i].~ElementType();
|
||||
|
||||
numUsed = 0;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void swapWith (ArrayBase& other) noexcept
|
||||
{
|
||||
elements.swapWith (other.elements);
|
||||
std::swap (numAllocated, other.numAllocated);
|
||||
std::swap (numUsed, other.numUsed);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void add (const ElementType& newElement)
|
||||
{
|
||||
addImpl (newElement);
|
||||
}
|
||||
|
||||
void add (ElementType&& newElement)
|
||||
{
|
||||
addImpl (std::move (newElement));
|
||||
}
|
||||
|
||||
template <typename... OtherElements>
|
||||
void add (const ElementType& firstNewElement, OtherElements&&... otherElements)
|
||||
{
|
||||
addImpl (firstNewElement, std::forward<OtherElements> (otherElements)...);
|
||||
}
|
||||
|
||||
template <typename... OtherElements>
|
||||
void add (ElementType&& firstNewElement, OtherElements&&... otherElements)
|
||||
{
|
||||
addImpl (std::move (firstNewElement), std::forward<OtherElements> (otherElements)...);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <typename Type>
|
||||
void addArray (const Type* elementsToAdd, int numElementsToAdd)
|
||||
{
|
||||
ensureAllocatedSize (numUsed + numElementsToAdd);
|
||||
addArrayInternal (elementsToAdd, numElementsToAdd);
|
||||
numUsed += numElementsToAdd;
|
||||
}
|
||||
|
||||
template <typename TypeToCreateFrom>
|
||||
void addArray (const std::initializer_list<TypeToCreateFrom>& items)
|
||||
{
|
||||
ensureAllocatedSize (numUsed + (int) items.size());
|
||||
|
||||
for (auto& item : items)
|
||||
new (elements + numUsed++) ElementType (item);
|
||||
}
|
||||
|
||||
template <class OtherArrayType>
|
||||
void addArray (const OtherArrayType& arrayToAddFrom)
|
||||
{
|
||||
jassert ((const void*) this != (const void*) &arrayToAddFrom); // can't add from our own elements!
|
||||
ensureAllocatedSize (numUsed + (int) arrayToAddFrom.size());
|
||||
|
||||
for (auto& e : arrayToAddFrom)
|
||||
addAssumingCapacityIsReady (e);
|
||||
}
|
||||
|
||||
template <class OtherArrayType>
|
||||
std::enable_if_t<! std::is_pointer_v<OtherArrayType>, int>
|
||||
addArray (const OtherArrayType& arrayToAddFrom,
|
||||
int startIndex, int numElementsToAdd = -1)
|
||||
{
|
||||
jassert ((const void*) this != (const void*) &arrayToAddFrom); // can't add from our own elements!
|
||||
|
||||
if (startIndex < 0)
|
||||
{
|
||||
jassertfalse;
|
||||
startIndex = 0;
|
||||
}
|
||||
|
||||
if (numElementsToAdd < 0 || startIndex + numElementsToAdd > (int) arrayToAddFrom.size())
|
||||
numElementsToAdd = (int) arrayToAddFrom.size() - startIndex;
|
||||
|
||||
addArray (arrayToAddFrom.data() + startIndex, numElementsToAdd);
|
||||
|
||||
return numElementsToAdd;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void insert (int indexToInsertAt, ParameterType newElement, int numberOfTimesToInsertIt)
|
||||
{
|
||||
checkSourceIsNotAMember (newElement);
|
||||
auto* space = createInsertSpace (indexToInsertAt, numberOfTimesToInsertIt);
|
||||
|
||||
for (int i = 0; i < numberOfTimesToInsertIt; ++i)
|
||||
new (space++) ElementType (newElement);
|
||||
|
||||
numUsed += numberOfTimesToInsertIt;
|
||||
}
|
||||
|
||||
void insertArray (int indexToInsertAt, const ElementType* newElements, int numberOfElements)
|
||||
{
|
||||
auto* space = createInsertSpace (indexToInsertAt, numberOfElements);
|
||||
|
||||
for (int i = 0; i < numberOfElements; ++i)
|
||||
new (space++) ElementType (*(newElements++));
|
||||
|
||||
numUsed += numberOfElements;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void removeElements (int indexToRemoveAt, int numElementsToRemove)
|
||||
{
|
||||
jassert (indexToRemoveAt >= 0);
|
||||
jassert (numElementsToRemove >= 0);
|
||||
jassert (indexToRemoveAt + numElementsToRemove <= numUsed);
|
||||
|
||||
if (numElementsToRemove > 0)
|
||||
{
|
||||
removeElementsInternal (indexToRemoveAt, numElementsToRemove);
|
||||
numUsed -= numElementsToRemove;
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void swap (int index1, int index2)
|
||||
{
|
||||
if (isPositiveAndBelow (index1, numUsed)
|
||||
&& isPositiveAndBelow (index2, numUsed))
|
||||
{
|
||||
std::swap (elements[index1],
|
||||
elements[index2]);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void move (int currentIndex, int newIndex) noexcept
|
||||
{
|
||||
if (isPositiveAndBelow (currentIndex, numUsed))
|
||||
{
|
||||
if (! isPositiveAndBelow (newIndex, numUsed))
|
||||
newIndex = numUsed - 1;
|
||||
|
||||
moveInternal (currentIndex, newIndex);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
#if defined (__GNUC__) && __GNUC__ < 5 && ! defined (__clang__)
|
||||
static constexpr auto isTriviallyCopyable = std::is_scalar_v<ElementType>;
|
||||
#else
|
||||
static constexpr auto isTriviallyCopyable = std::is_trivially_copyable_v<ElementType>;
|
||||
#endif
|
||||
|
||||
//==============================================================================
|
||||
template <typename Type>
|
||||
void addArrayInternal (const Type* otherElements, int numElements)
|
||||
{
|
||||
if constexpr (isTriviallyCopyable && std::is_same_v<Type, ElementType>)
|
||||
{
|
||||
if (numElements > 0)
|
||||
memcpy (elements + numUsed, otherElements, (size_t) numElements * sizeof (ElementType));
|
||||
}
|
||||
else
|
||||
{
|
||||
auto* start = elements + numUsed;
|
||||
|
||||
while (--numElements >= 0)
|
||||
new (start++) ElementType (*(otherElements++));
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void setAllocatedSizeInternal (int numElements)
|
||||
{
|
||||
if constexpr (isTriviallyCopyable)
|
||||
{
|
||||
elements.realloc ((size_t) numElements);
|
||||
}
|
||||
else
|
||||
{
|
||||
HeapBlock<ElementType> newElements (numElements);
|
||||
|
||||
for (int i = 0; i < numUsed; ++i)
|
||||
{
|
||||
new (newElements + i) ElementType (std::move (elements[i]));
|
||||
elements[i].~ElementType();
|
||||
}
|
||||
|
||||
elements = std::move (newElements);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
ElementType* createInsertSpace (int indexToInsertAt, int numElements)
|
||||
{
|
||||
ensureAllocatedSize (numUsed + numElements);
|
||||
|
||||
if (! isPositiveAndBelow (indexToInsertAt, numUsed))
|
||||
return elements + numUsed;
|
||||
|
||||
createInsertSpaceInternal (indexToInsertAt, numElements);
|
||||
|
||||
return elements + indexToInsertAt;
|
||||
}
|
||||
|
||||
void createInsertSpaceInternal (int indexToInsertAt, int numElements)
|
||||
{
|
||||
if constexpr (isTriviallyCopyable)
|
||||
{
|
||||
auto* start = elements + indexToInsertAt;
|
||||
auto numElementsToShift = numUsed - indexToInsertAt;
|
||||
memmove (start + numElements, start, (size_t) numElementsToShift * sizeof (ElementType));
|
||||
}
|
||||
else
|
||||
{
|
||||
auto* end = elements + numUsed;
|
||||
auto* newEnd = end + numElements;
|
||||
auto numElementsToShift = numUsed - indexToInsertAt;
|
||||
|
||||
for (int i = 0; i < numElementsToShift; ++i)
|
||||
{
|
||||
new (--newEnd) ElementType (std::move (*(--end)));
|
||||
end->~ElementType();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void removeElementsInternal (int indexToRemoveAt, int numElementsToRemove)
|
||||
{
|
||||
jassert (0 <= indexToRemoveAt);
|
||||
jassert (0 <= numElementsToRemove);
|
||||
|
||||
const auto endOfRemovedRange = indexToRemoveAt + numElementsToRemove;
|
||||
jassert (endOfRemovedRange <= numUsed);
|
||||
|
||||
const auto numElementsToShift = numUsed - endOfRemovedRange;
|
||||
|
||||
if constexpr (isTriviallyCopyable)
|
||||
{
|
||||
auto* start = elements + indexToRemoveAt;
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wstringop-overflow")
|
||||
memmove (start, start + numElementsToRemove, (size_t) numElementsToShift * sizeof (ElementType));
|
||||
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
|
||||
}
|
||||
else
|
||||
{
|
||||
auto* destination = elements + indexToRemoveAt;
|
||||
auto* source = destination + numElementsToRemove;
|
||||
|
||||
for (int i = 0; i < numElementsToShift; ++i)
|
||||
moveAssignElement (destination++, std::move (*(source++)));
|
||||
|
||||
for (int i = 0; i < numElementsToRemove; ++i)
|
||||
(destination++)->~ElementType();
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void moveInternal (int currentIndex, int newIndex) noexcept
|
||||
{
|
||||
if constexpr (isTriviallyCopyable)
|
||||
{
|
||||
char tempCopy[sizeof (ElementType)];
|
||||
memcpy (tempCopy, elements + currentIndex, sizeof (ElementType));
|
||||
|
||||
if (newIndex > currentIndex)
|
||||
{
|
||||
memmove (elements + currentIndex,
|
||||
elements + currentIndex + 1,
|
||||
(size_t) (newIndex - currentIndex) * sizeof (ElementType));
|
||||
}
|
||||
else
|
||||
{
|
||||
memmove (elements + newIndex + 1,
|
||||
elements + newIndex,
|
||||
(size_t) (currentIndex - newIndex) * sizeof (ElementType));
|
||||
}
|
||||
|
||||
memcpy (elements + newIndex, tempCopy, sizeof (ElementType));
|
||||
}
|
||||
else
|
||||
{
|
||||
auto* e = elements + currentIndex;
|
||||
ElementType tempCopy (std::move (*e));
|
||||
auto delta = newIndex - currentIndex;
|
||||
|
||||
if (delta > 0)
|
||||
{
|
||||
for (int i = 0; i < delta; ++i)
|
||||
{
|
||||
moveAssignElement (e, std::move (*(e + 1)));
|
||||
++e;
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = 0; i < -delta; ++i)
|
||||
{
|
||||
moveAssignElement (e, std::move (*(e - 1)));
|
||||
--e;
|
||||
}
|
||||
}
|
||||
|
||||
moveAssignElement (e, std::move (tempCopy));
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <typename... Elements>
|
||||
void addImpl (Elements&&... toAdd)
|
||||
{
|
||||
(checkSourceIsNotAMember (toAdd), ...);
|
||||
ensureAllocatedSize (numUsed + (int) sizeof... (toAdd));
|
||||
addAssumingCapacityIsReady (std::forward<Elements> (toAdd)...);
|
||||
}
|
||||
|
||||
template <typename... Elements>
|
||||
void addAssumingCapacityIsReady (Elements&&... toAdd)
|
||||
{
|
||||
(new (elements + numUsed++) ElementType (std::forward<Elements> (toAdd)), ...);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
void moveAssignElement (ElementType* destination, ElementType&& source)
|
||||
{
|
||||
if constexpr (std::is_move_assignable_v<ElementType>)
|
||||
{
|
||||
*destination = std::move (source);
|
||||
}
|
||||
else
|
||||
{
|
||||
destination->~ElementType();
|
||||
new (destination) ElementType (std::move (source));
|
||||
}
|
||||
}
|
||||
|
||||
void checkSourceIsNotAMember ([[maybe_unused]] const ElementType& element)
|
||||
{
|
||||
// when you pass a reference to an existing element into a method like add() which
|
||||
// may need to reallocate the array to make more space, the incoming reference may
|
||||
// be deleted indirectly during the reallocation operation! To work around this,
|
||||
// make a local copy of the item you're trying to add (and maybe use std::move to
|
||||
// move it into the add() method to avoid any extra overhead)
|
||||
jassert (std::addressof (element) < begin() || end() <= std::addressof (element));
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
HeapBlock<ElementType> elements;
|
||||
int numAllocated = 0, numUsed = 0;
|
||||
|
||||
template <class OtherElementType, class OtherCriticalSection>
|
||||
friend class ArrayBase;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (ArrayBase)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,283 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
DynamicObject::DynamicObject() = default;
|
||||
|
||||
DynamicObject::DynamicObject (const DynamicObject& other)
|
||||
: ReferenceCountedObject(), properties (other.properties)
|
||||
{
|
||||
}
|
||||
|
||||
bool DynamicObject::hasProperty (const Identifier& propertyName) const
|
||||
{
|
||||
const var* const v = properties.getVarPointer (propertyName);
|
||||
return v != nullptr && ! v->isMethod();
|
||||
}
|
||||
|
||||
const var& DynamicObject::getProperty (const Identifier& propertyName) const
|
||||
{
|
||||
return properties [propertyName];
|
||||
}
|
||||
|
||||
void DynamicObject::setProperty (const Identifier& propertyName, const var& newValue)
|
||||
{
|
||||
properties.set (propertyName, newValue);
|
||||
didModifyProperty (propertyName, newValue);
|
||||
}
|
||||
|
||||
void DynamicObject::removeProperty (const Identifier& propertyName)
|
||||
{
|
||||
properties.remove (propertyName);
|
||||
didModifyProperty (propertyName, std::nullopt);
|
||||
}
|
||||
|
||||
bool DynamicObject::hasMethod (const Identifier& methodName) const
|
||||
{
|
||||
return getProperty (methodName).isMethod();
|
||||
}
|
||||
|
||||
var DynamicObject::invokeMethod (Identifier method, const var::NativeFunctionArgs& args)
|
||||
{
|
||||
if (auto function = properties [method].getNativeFunction())
|
||||
return function (args);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void DynamicObject::setMethod (Identifier name, var::NativeFunction function)
|
||||
{
|
||||
setProperty (name, var (function));
|
||||
}
|
||||
|
||||
void DynamicObject::clear()
|
||||
{
|
||||
auto copy = properties;
|
||||
properties.clear();
|
||||
|
||||
for (auto& prop : copy)
|
||||
didModifyProperty (prop.name, std::nullopt);
|
||||
}
|
||||
|
||||
void DynamicObject::cloneAllProperties()
|
||||
{
|
||||
for (int i = properties.size(); --i >= 0;)
|
||||
if (auto* v = properties.getVarPointerAt (i))
|
||||
*v = v->clone();
|
||||
}
|
||||
|
||||
std::unique_ptr<DynamicObject> DynamicObject::clone() const
|
||||
{
|
||||
auto result = std::make_unique<DynamicObject> (*this);
|
||||
result->cloneAllProperties();
|
||||
return result;
|
||||
}
|
||||
|
||||
void DynamicObject::writeAsJSON (OutputStream& out, const JSON::FormatOptions& format)
|
||||
{
|
||||
out << '{';
|
||||
if (format.getSpacing() == JSON::Spacing::multiLine)
|
||||
out << newLine;
|
||||
|
||||
const int numValues = properties.size();
|
||||
|
||||
for (int i = 0; i < numValues; ++i)
|
||||
{
|
||||
if (format.getSpacing() == JSON::Spacing::multiLine)
|
||||
JSONFormatter::writeSpaces (out, format.getIndentLevel() + JSONFormatter::indentSize);
|
||||
|
||||
out << '"';
|
||||
JSONFormatter::writeString (out, properties.getName (i), format.getEncoding());
|
||||
out << "\":";
|
||||
|
||||
if (format.getSpacing() != JSON::Spacing::none)
|
||||
out << ' ';
|
||||
|
||||
JSON::writeToStream (out,
|
||||
properties.getValueAt (i),
|
||||
format.withIndentLevel (format.getIndentLevel() + JSONFormatter::indentSize));
|
||||
|
||||
if (i < numValues - 1)
|
||||
{
|
||||
out << ",";
|
||||
|
||||
switch (format.getSpacing())
|
||||
{
|
||||
case JSON::Spacing::none: break;
|
||||
case JSON::Spacing::singleLine: out << ' '; break;
|
||||
case JSON::Spacing::multiLine: out << newLine; break;
|
||||
}
|
||||
}
|
||||
else if (format.getSpacing() == JSON::Spacing::multiLine)
|
||||
out << newLine;
|
||||
}
|
||||
|
||||
if (format.getSpacing() == JSON::Spacing::multiLine)
|
||||
JSONFormatter::writeSpaces (out, format.getIndentLevel());
|
||||
|
||||
out << '}';
|
||||
}
|
||||
|
||||
bool DynamicObject::equals (const DynamicObject& other) const
|
||||
{
|
||||
return properties == other.properties;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
//==============================================================================
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class DynamicObjectTests : public UnitTest
|
||||
{
|
||||
public:
|
||||
DynamicObjectTests() : UnitTest { "DynamicObject", UnitTestCategories::containers } {}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
struct Action
|
||||
{
|
||||
Identifier key;
|
||||
std::optional<var> value;
|
||||
|
||||
bool operator== (const Action& other) const
|
||||
{
|
||||
return other.key == key && other.value == value;
|
||||
}
|
||||
};
|
||||
|
||||
using Actions = std::vector<Action>;
|
||||
|
||||
struct DerivedObject : public DynamicObject
|
||||
{
|
||||
explicit DerivedObject (Actions& a) : actions (a) {}
|
||||
|
||||
void didModifyProperty (const Identifier& key, const std::optional<var>& value) override
|
||||
{
|
||||
actions.push_back (Action { key, value });
|
||||
}
|
||||
|
||||
Actions& actions;
|
||||
};
|
||||
|
||||
Actions actions;
|
||||
DerivedObject object { actions };
|
||||
|
||||
beginTest ("didModifyProperty is emitted on setProperty");
|
||||
{
|
||||
expect (object.getProperties().isEmpty());
|
||||
|
||||
const Identifier key = "foo";
|
||||
const var value = 123;
|
||||
object.setProperty (key, value);
|
||||
|
||||
expect (actions == Actions { Action { key, value } });
|
||||
expect (object.getProperties() == NamedValueSet { { key, value } });
|
||||
}
|
||||
|
||||
object.clear();
|
||||
actions.clear();
|
||||
|
||||
beginTest ("didModifyProperty is emitted on setMethod");
|
||||
{
|
||||
expect (object.getProperties().isEmpty());
|
||||
|
||||
const Identifier key = "foo";
|
||||
const var::NativeFunction value = [] (const var::NativeFunctionArgs&) { return var{}; };
|
||||
object.setMethod (key, value);
|
||||
|
||||
expect (actions.size() == 1);
|
||||
expect (actions.back().key == key);
|
||||
|
||||
expect (object.getProperties().size() == 1);
|
||||
expect (object.hasMethod (key));
|
||||
}
|
||||
|
||||
object.clear();
|
||||
actions.clear();
|
||||
|
||||
beginTest ("didModifyProperty is emitted on removeProperty");
|
||||
{
|
||||
expect (object.getProperties().isEmpty());
|
||||
|
||||
const Identifier key = "bar";
|
||||
object.removeProperty (key);
|
||||
|
||||
expect (actions == Actions { Action { key, std::nullopt } });
|
||||
expect (object.getProperties().isEmpty());
|
||||
}
|
||||
|
||||
object.clear();
|
||||
actions.clear();
|
||||
|
||||
beginTest ("didModifyProperty is emitted on clear");
|
||||
{
|
||||
expect (object.getProperties().isEmpty());
|
||||
|
||||
object.clear();
|
||||
|
||||
expect (actions.empty());
|
||||
|
||||
const Identifier keys[] { "foo", "bar", "baz" };
|
||||
|
||||
for (auto [index, key] : enumerate (keys, int{}))
|
||||
object.setProperty (key, index);
|
||||
|
||||
for (auto& key : keys)
|
||||
expect (object.hasProperty (key));
|
||||
|
||||
actions.clear();
|
||||
|
||||
object.clear();
|
||||
|
||||
expect (actions.size() == std::size (keys));
|
||||
|
||||
for (auto& key : keys)
|
||||
{
|
||||
expect (std::find_if (actions.begin(), actions.end(), [&key] (auto& action)
|
||||
{
|
||||
return action.key == key && action.value == std::nullopt;
|
||||
}) != actions.end());
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static DynamicObjectTests dynamicObjectTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,158 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Represents a dynamically implemented object.
|
||||
|
||||
This class is primarily intended for wrapping scripting language objects,
|
||||
but could be used for other purposes.
|
||||
|
||||
An instance of a DynamicObject can be used to store named properties, and
|
||||
by subclassing hasMethod() and invokeMethod(), you can give your object
|
||||
methods.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API DynamicObject : public ReferenceCountedObject
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
DynamicObject();
|
||||
DynamicObject (const DynamicObject&);
|
||||
|
||||
using Ptr = ReferenceCountedObjectPtr<DynamicObject>;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns true if the object has a property with this name.
|
||||
Note that if the property is actually a method, this will return false.
|
||||
*/
|
||||
bool hasProperty (const Identifier& propertyName) const;
|
||||
|
||||
/** Returns a named property.
|
||||
This returns var() if no such property exists.
|
||||
*/
|
||||
const var& getProperty (const Identifier& propertyName) const;
|
||||
|
||||
/** Sets a named property. */
|
||||
void setProperty (const Identifier& propertyName, const var& newValue);
|
||||
|
||||
/** Removes a named property. */
|
||||
void removeProperty (const Identifier& propertyName);
|
||||
|
||||
//==============================================================================
|
||||
/** Checks whether this object has a property with the given name that has a
|
||||
value of type NativeFunction.
|
||||
*/
|
||||
bool hasMethod (const Identifier& methodName) const;
|
||||
|
||||
/** Invokes a named method on this object.
|
||||
|
||||
The default implementation looks up the named property, and if it's a method
|
||||
call, then it invokes it.
|
||||
*/
|
||||
var invokeMethod (Identifier methodName,
|
||||
const var::NativeFunctionArgs& args);
|
||||
|
||||
/** Adds a method to the class.
|
||||
|
||||
This is basically the same as calling setProperty (methodName, (var::NativeFunction) myFunction), but
|
||||
helps to avoid accidentally invoking the wrong type of var constructor. It also makes
|
||||
the code easier to read.
|
||||
*/
|
||||
void setMethod (Identifier methodName, var::NativeFunction function);
|
||||
|
||||
//==============================================================================
|
||||
/** Removes all properties and methods from the object. */
|
||||
void clear();
|
||||
|
||||
/** Returns the NamedValueSet that holds the object's properties. */
|
||||
NamedValueSet& getProperties() noexcept { return properties; }
|
||||
|
||||
/** Returns the NamedValueSet that holds the object's properties. */
|
||||
const NamedValueSet& getProperties() const noexcept { return properties; }
|
||||
|
||||
/** Calls var::clone() on all the properties that this object contains. */
|
||||
void cloneAllProperties();
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a clone of this object.
|
||||
The default implementation of this method just returns a new DynamicObject
|
||||
with a (deep) copy of all of its properties. Subclasses can override this to
|
||||
implement their own custom copy routines.
|
||||
*/
|
||||
virtual std::unique_ptr<DynamicObject> clone() const;
|
||||
|
||||
//==============================================================================
|
||||
/** Writes this object to a text stream in JSON format.
|
||||
This method is used by JSON::toString and JSON::writeToStream, and you should
|
||||
never need to call it directly, but it's virtual so that custom object types
|
||||
can stringify themselves appropriately.
|
||||
*/
|
||||
virtual void writeAsJSON (OutputStream&, const JSON::FormatOptions&);
|
||||
|
||||
/** Returns true if the properties of this object match the properties of the specified object,
|
||||
or false otherwise.
|
||||
*/
|
||||
bool equals (const DynamicObject& other) const;
|
||||
|
||||
/** Returns true if the properties of this object match the properties of the specified object,
|
||||
or false otherwise.
|
||||
*/
|
||||
bool operator== (const DynamicObject& other) const { return equals (other); }
|
||||
|
||||
/** The inverse of operator==() */
|
||||
bool operator!= (const DynamicObject& other) const { return ! operator== (other); }
|
||||
|
||||
private:
|
||||
/** Derived classes may override this function to take additional actions after
|
||||
properties are assigned or removed.
|
||||
|
||||
@param name the name of the property that changed
|
||||
@param value if non-null, the value of the property after assignment
|
||||
if null, indicates that the property was removed
|
||||
*/
|
||||
virtual void didModifyProperty ([[maybe_unused]] const Identifier& name,
|
||||
[[maybe_unused]] const std::optional<var>& value) {}
|
||||
|
||||
//==============================================================================
|
||||
NamedValueSet properties;
|
||||
|
||||
JUCE_LEAK_DETECTOR (DynamicObject)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,206 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/** @cond */
|
||||
/** This is an internal helper class which converts a juce ElementComparator style
|
||||
class (using a "compareElements" method) into a class that's compatible with
|
||||
std::sort (i.e. using an operator() to compare the elements)
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename ElementComparator>
|
||||
struct SortFunctionConverter
|
||||
{
|
||||
SortFunctionConverter (ElementComparator& e) : comparator (e) {}
|
||||
SortFunctionConverter (const SortFunctionConverter&) = default;
|
||||
|
||||
template <typename Type>
|
||||
bool operator() (Type a, Type b) { return comparator.compareElements (a, b) < 0; }
|
||||
|
||||
private:
|
||||
ElementComparator& comparator;
|
||||
|
||||
SortFunctionConverter& operator= (const SortFunctionConverter&) = delete;
|
||||
};
|
||||
/** @endcond */
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Sorts a range of elements in an array.
|
||||
|
||||
The comparator object that is passed-in must define a public method with the following
|
||||
signature:
|
||||
@code
|
||||
int compareElements (ElementType first, ElementType second);
|
||||
@endcode
|
||||
|
||||
...and this method must return:
|
||||
- a value of < 0 if the first comes before the second
|
||||
- a value of 0 if the two objects are equivalent
|
||||
- a value of > 0 if the second comes before the first
|
||||
|
||||
To improve performance, the compareElements() method can be declared as static or const.
|
||||
|
||||
@param comparator an object which defines a compareElements() method
|
||||
@param array the array to sort
|
||||
@param firstElement the index of the first element of the range to be sorted
|
||||
@param lastElement the index of the last element in the range that needs
|
||||
sorting (this is inclusive)
|
||||
@param retainOrderOfEquivalentItems if true, the order of items that the
|
||||
comparator deems the same will be maintained - this will be
|
||||
a slower algorithm than if they are allowed to be moved around.
|
||||
|
||||
@see sortArrayRetainingOrder
|
||||
*/
|
||||
template <class ElementType, class ElementComparator>
|
||||
static void sortArray (ElementComparator& comparator,
|
||||
ElementType* const array,
|
||||
int firstElement,
|
||||
int lastElement,
|
||||
const bool retainOrderOfEquivalentItems)
|
||||
{
|
||||
jassert (firstElement >= 0);
|
||||
|
||||
if (lastElement > firstElement)
|
||||
{
|
||||
SortFunctionConverter<ElementComparator> converter (comparator);
|
||||
|
||||
if (retainOrderOfEquivalentItems)
|
||||
std::stable_sort (array + firstElement, array + lastElement + 1, converter);
|
||||
else
|
||||
std::sort (array + firstElement, array + lastElement + 1, converter);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Searches a sorted array of elements, looking for the index at which a specified value
|
||||
should be inserted for it to be in the correct order.
|
||||
|
||||
The comparator object that is passed-in must define a public method with the following
|
||||
signature:
|
||||
@code
|
||||
int compareElements (ElementType first, ElementType second);
|
||||
@endcode
|
||||
|
||||
...and this method must return:
|
||||
- a value of < 0 if the first comes before the second
|
||||
- a value of 0 if the two objects are equivalent
|
||||
- a value of > 0 if the second comes before the first
|
||||
|
||||
To improve performance, the compareElements() method can be declared as static or const.
|
||||
|
||||
@param comparator an object which defines a compareElements() method
|
||||
@param array the array to search
|
||||
@param newElement the value that is going to be inserted
|
||||
@param firstElement the index of the first element to search
|
||||
@param lastElement the index of the last element in the range (this is non-inclusive)
|
||||
*/
|
||||
template <class ElementType, class ElementComparator>
|
||||
static int findInsertIndexInSortedArray ([[maybe_unused]] ElementComparator& comparator,
|
||||
ElementType* const array,
|
||||
const ElementType newElement,
|
||||
int firstElement,
|
||||
int lastElement)
|
||||
{
|
||||
jassert (firstElement <= lastElement);
|
||||
|
||||
while (firstElement < lastElement)
|
||||
{
|
||||
if (comparator.compareElements (newElement, array [firstElement]) == 0)
|
||||
{
|
||||
++firstElement;
|
||||
break;
|
||||
}
|
||||
else
|
||||
{
|
||||
const int halfway = (firstElement + lastElement) >> 1;
|
||||
|
||||
if (halfway == firstElement)
|
||||
{
|
||||
if (comparator.compareElements (newElement, array [halfway]) >= 0)
|
||||
++firstElement;
|
||||
|
||||
break;
|
||||
}
|
||||
else if (comparator.compareElements (newElement, array [halfway]) >= 0)
|
||||
{
|
||||
firstElement = halfway;
|
||||
}
|
||||
else
|
||||
{
|
||||
lastElement = halfway;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return firstElement;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A simple ElementComparator class that can be used to sort an array of
|
||||
objects that support the '<' operator.
|
||||
|
||||
This will work for primitive types and objects that implement operator<().
|
||||
|
||||
Example: @code
|
||||
Array<int> myArray;
|
||||
DefaultElementComparator<int> sorter;
|
||||
myArray.sort (sorter);
|
||||
@endcode
|
||||
|
||||
@see ElementComparator
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class ElementType>
|
||||
class DefaultElementComparator
|
||||
{
|
||||
private:
|
||||
using ParameterType = typename TypeHelpers::ParameterType<ElementType>::type;
|
||||
|
||||
public:
|
||||
static int compareElements (ParameterType first, ParameterType second)
|
||||
{
|
||||
return (first < second) ? -1 : ((second < first) ? 1 : 0);
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,439 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
namespace detail
|
||||
{
|
||||
|
||||
template <typename T, typename = void>
|
||||
constexpr auto canPreDecrement = false;
|
||||
|
||||
template <typename T>
|
||||
constexpr auto canPreDecrement<T, std::void_t<decltype (--std::declval<T>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canAddAssign = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canAddAssign<T, I, std::void_t<decltype (std::declval<T>() += std::declval<I>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canSubAssign = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canSubAssign<T, I, std::void_t<decltype (std::declval<T>() -= std::declval<I>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canAdd = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canAdd<T, I, std::void_t<decltype (std::declval<T>() + std::declval<I>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canSub = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canSub<T, I, std::void_t<decltype (std::declval<T>() - std::declval<I>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canLessThan = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canLessThan<T, I, std::void_t<decltype (std::declval<T>() < std::declval<I>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canLessThanEqual = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canLessThanEqual<T, I, std::void_t<decltype (std::declval<T>() <= std::declval<I>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canGreaterThan = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canGreaterThan<T, I, std::void_t<decltype (std::declval<T>() > std::declval<I>())>> = true;
|
||||
|
||||
template <typename T, typename I, typename = void>
|
||||
constexpr auto canGreaterThanEqual = false;
|
||||
|
||||
template <typename T, typename I>
|
||||
constexpr auto canGreaterThanEqual<T, I, std::void_t<decltype (std::declval<T>() >= std::declval<I>())>> = true;
|
||||
|
||||
namespace withAdlSize
|
||||
{
|
||||
using std::size;
|
||||
|
||||
template <typename Range>
|
||||
using AdlSize = decltype (size (std::declval<Range>()));
|
||||
|
||||
template <typename Range>
|
||||
using AdlSignedSize = std::common_type_t<std::ptrdiff_t, std::make_signed_t<AdlSize<Range>>>;
|
||||
}
|
||||
|
||||
} // namespace detail
|
||||
|
||||
/**
|
||||
Returned when dereferencing an EnumerateIterator.
|
||||
|
||||
Allows querying the index associated with an element, along with a reference to the element
|
||||
itself.
|
||||
|
||||
You should never need to construct an instance of this type yourself. Instead, use the
|
||||
enumerate() function to construct a range that can be enumerated.
|
||||
|
||||
@see enumerate()
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Index, typename Value>
|
||||
struct Enumerated
|
||||
{
|
||||
Index index;
|
||||
Value value;
|
||||
};
|
||||
|
||||
/**
|
||||
An iterator that wraps some other iterator, keeping track of the relative position of that
|
||||
iterator based on calls to arithmetic operators such as
|
||||
operator++(), operator--(), operator+(), and operator-().
|
||||
|
||||
You should never need to construct an instance of this type yourself. Instead, use the
|
||||
enumerate() function to construct a range that can be enumerated.
|
||||
|
||||
@see enumerate()
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Iter, typename Index = ptrdiff_t>
|
||||
class EnumerateIterator
|
||||
{
|
||||
public:
|
||||
/** Default constructor. */
|
||||
constexpr EnumerateIterator() = default;
|
||||
|
||||
/** Wraps the provided iterator, and sets the internal count to 0. */
|
||||
constexpr explicit EnumerateIterator (Iter iter)
|
||||
: EnumerateIterator (std::move (iter), Index{}) {}
|
||||
|
||||
/** Wraps the provided iterator, and sets the internal count to the provided value. */
|
||||
constexpr EnumerateIterator (Iter iter, Index ind)
|
||||
: iterator (std::move (iter)), index (ind) {}
|
||||
|
||||
/** Two EnumerateIterators are considered equal if the wrapped iterators are equal. */
|
||||
template <typename OtherIter, typename OtherInd>
|
||||
[[nodiscard]] constexpr bool operator== (const EnumerateIterator<OtherIter, OtherInd>& other) const
|
||||
{
|
||||
return iterator == other.iterator;
|
||||
}
|
||||
|
||||
/** @see operator==() */
|
||||
template <typename OtherIter, typename OtherInd>
|
||||
[[nodiscard]] constexpr bool operator!= (const EnumerateIterator<OtherIter, OtherInd>& other) const
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
/** Dereferencing the iterator produces an Enumerated instance *by value*. This type holds
|
||||
a copy of the iterator's current index, along with the result of dereferencing the
|
||||
wrapped iterator (normally a reference type).
|
||||
*/
|
||||
[[nodiscard]] constexpr Enumerated<Index, decltype (*std::declval<Iter>())> operator*() const
|
||||
{
|
||||
return { index, *iterator };
|
||||
}
|
||||
|
||||
/** Increments the iterator and the index. */
|
||||
constexpr EnumerateIterator& operator++()
|
||||
{
|
||||
++iterator;
|
||||
++index;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Increments the iterator and the index. */
|
||||
constexpr EnumerateIterator operator++ (int)
|
||||
{
|
||||
auto copy = *this;
|
||||
operator++();
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Decrements the iterator and the index.
|
||||
Only participates in overload resolution if the iterator can be pre-decremented.
|
||||
*/
|
||||
template <typename T = Iter, std::enable_if_t<detail::canPreDecrement<T>, int> = 0>
|
||||
constexpr EnumerateIterator& operator--()
|
||||
{
|
||||
--iterator;
|
||||
--index;
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Decrements the iterator and the index.
|
||||
Only participates in overload resolution if the iterator can be pre-decremented.
|
||||
*/
|
||||
template <typename T = Iter, std::enable_if_t<detail::canPreDecrement<T>, int> = 0>
|
||||
constexpr EnumerateIterator operator-- (int)
|
||||
{
|
||||
auto copy = *this;
|
||||
operator--();
|
||||
return copy;
|
||||
}
|
||||
|
||||
/** Adds an integral value to both the iterator and the index.
|
||||
Only participates in overload resolution if the iterator can be add-assigned.
|
||||
*/
|
||||
template <typename I, std::enable_if_t<detail::canAddAssign<Iter&, I>, int> = 0>
|
||||
constexpr EnumerateIterator& operator+= (I diff)
|
||||
{
|
||||
iterator += diff;
|
||||
index += static_cast<Index> (diff);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Subtracts an integral value from both the iterator and the index.
|
||||
Only participates in overload resolution if the iterator can be sub-assigned.
|
||||
*/
|
||||
template <typename I, std::enable_if_t<detail::canSubAssign<Iter&, I>, int> = 0>
|
||||
constexpr EnumerateIterator& operator-= (I diff)
|
||||
{
|
||||
iterator -= diff;
|
||||
index -= static_cast<Index> (diff);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Subtracts another enumerate iterator from this one, producing the same result as
|
||||
subtracting the two wrapped iterators. For random-access iterators, this will normally
|
||||
return the distance between the two iterators.
|
||||
Only participates in overload resolution if the wrapped iterators can be subtracted.
|
||||
*/
|
||||
template <typename OtherIter, typename OtherInd, std::enable_if_t<detail::canSub<Iter, OtherIter>, int> = 0>
|
||||
[[nodiscard]] constexpr auto operator- (const EnumerateIterator<OtherIter, OtherInd>& other) const
|
||||
{
|
||||
return iterator - other.iterator;
|
||||
}
|
||||
|
||||
/** Indexes into this iterator, equivalent to adding an integral value to this iterator and
|
||||
then dereferencing the result.
|
||||
Only participates in overload resolution if the wrapped iterator allows addition of
|
||||
integral values.
|
||||
*/
|
||||
template <typename I, std::enable_if_t<detail::canAdd<EnumerateIterator, I>, int> = 0>
|
||||
[[nodiscard]] constexpr auto operator[] (I diff) const
|
||||
{
|
||||
return *(*this + diff);
|
||||
}
|
||||
|
||||
/** Returns the result of comparing the two wrapped iterators.
|
||||
Only participates in overload resolution if the wrapped iterators are comparable.
|
||||
*/
|
||||
template <typename OtherIter, typename OtherInd, std::enable_if_t<detail::canLessThan<Iter, OtherIter>, int> = 0>
|
||||
[[nodiscard]] constexpr bool operator< (const EnumerateIterator<OtherIter, OtherInd>& other) const
|
||||
{
|
||||
return iterator < other.iterator;
|
||||
}
|
||||
|
||||
/** Returns the result of comparing the two wrapped iterators.
|
||||
Only participates in overload resolution if the wrapped iterators are comparable.
|
||||
*/
|
||||
template <typename OtherIter, typename OtherInd, std::enable_if_t<detail::canLessThanEqual<Iter, OtherIter>, int> = 0>
|
||||
[[nodiscard]] constexpr bool operator<= (const EnumerateIterator<OtherIter, OtherInd>& other) const
|
||||
{
|
||||
return iterator <= other.iterator;
|
||||
}
|
||||
|
||||
/** Returns the result of comparing the two wrapped iterators.
|
||||
Only participates in overload resolution if the wrapped iterators are comparable.
|
||||
*/
|
||||
template <typename OtherIter, typename OtherInd, std::enable_if_t<detail::canGreaterThan<Iter, OtherIter>, int> = 0>
|
||||
[[nodiscard]] constexpr bool operator> (const EnumerateIterator<OtherIter, OtherInd>& other) const
|
||||
{
|
||||
return iterator > other.iterator;
|
||||
}
|
||||
|
||||
/** Returns the result of comparing the two wrapped iterators.
|
||||
Only participates in overload resolution if the wrapped iterators are comparable.
|
||||
*/
|
||||
template <typename OtherIter, typename OtherInd, std::enable_if_t<detail::canGreaterThanEqual<Iter, OtherIter>, int> = 0>
|
||||
[[nodiscard]] constexpr bool operator>= (const EnumerateIterator<OtherIter, OtherInd>& other) const
|
||||
{
|
||||
return iterator >= other.iterator;
|
||||
}
|
||||
|
||||
/** Returns the result of adding an integral value to this iterator.
|
||||
Only participates in overload resolution if addition is supported by the wrapped iterator.
|
||||
*/
|
||||
template <typename I, std::enable_if_t<detail::canAddAssign<EnumerateIterator&, I>, int> = 0>
|
||||
constexpr friend auto operator+ (EnumerateIterator iter, I ind)
|
||||
{
|
||||
return iter += ind;
|
||||
}
|
||||
|
||||
/** Returns the result of adding an integral value to this iterator.
|
||||
Only participates in overload resolution if addition is supported by the wrapped iterator.
|
||||
*/
|
||||
template <typename I, std::enable_if_t<detail::canAddAssign<EnumerateIterator&, I>, int> = 0>
|
||||
constexpr friend auto operator+ (I ind, EnumerateIterator iter)
|
||||
{
|
||||
return iter += ind;
|
||||
}
|
||||
|
||||
/** Returns the result of subtracting an integral value from this iterator.
|
||||
Only participates in overload resolution if subtraction is supported by the wrapped iterator.
|
||||
*/
|
||||
template <typename I, std::enable_if_t<detail::canSubAssign<EnumerateIterator&, I>, int> = 0>
|
||||
constexpr friend auto operator- (EnumerateIterator iter, I ind)
|
||||
{
|
||||
return iter -= ind;
|
||||
}
|
||||
|
||||
private:
|
||||
Iter iterator{};
|
||||
Index index = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Wraps a pair of iterators, providing member begin() and end() functions that return
|
||||
those iterators.
|
||||
This is useful in situations where you have an iterator pair, but want to use that
|
||||
pair somewhere that requires an iterable range, such as in a ranged-for loop.
|
||||
|
||||
@see makeRange()
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Begin, typename End>
|
||||
class IteratorPair
|
||||
{
|
||||
public:
|
||||
/** Constructs a pair from a begin and end iterator.
|
||||
Instead of calling this directly, use makeRange().
|
||||
*/
|
||||
constexpr IteratorPair (Begin bIn, End eIn)
|
||||
: b (std::move (bIn)), e (std::move (eIn)) {}
|
||||
|
||||
/** Returns the begin iterator. */
|
||||
constexpr auto begin() const { return b; }
|
||||
|
||||
/** Returns the end iterator. */
|
||||
constexpr auto end() const { return e; }
|
||||
|
||||
private:
|
||||
Begin b;
|
||||
End e;
|
||||
};
|
||||
|
||||
/**
|
||||
Given two iterators "begin" and "end", returns an IteratorPair with a member
|
||||
begin() and end() function. This pair can be used in contexts that expect an
|
||||
iterable range, the most significant of which is ranged-for loops.
|
||||
This automatically deduces the Begin and End types, so it is more concise to use than
|
||||
directly calling the IteratorPair constructor.
|
||||
*/
|
||||
template <typename Begin, typename End = Begin>
|
||||
[[nodiscard]] constexpr auto makeRange (Begin begin, End end)
|
||||
{
|
||||
return IteratorPair<Begin, End> { std::move (begin), std::move (end) };
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Given a range and an optional starting offset, returns an IteratorPair that
|
||||
holds EnumerateIterators wrapping the begin() and end() of the range.
|
||||
|
||||
This is useful in situations where you need to iterate some range, but also query
|
||||
the position of each item in the range.
|
||||
|
||||
A simple usage might look like this:
|
||||
|
||||
@code
|
||||
std::list<int> elements { 10, 20, 30, 40, 50 };
|
||||
|
||||
for (const auto pair : enumerate (elements))
|
||||
std::cout << pair.index << ' ' << pair.value << ' ';
|
||||
|
||||
// output: 0 10 1 20 2 30 3 40 4 50
|
||||
@endcode
|
||||
|
||||
You can also use structured bindings to concisely destructure each Enumerated instance:
|
||||
|
||||
@code
|
||||
for (const auto [index, value] : enumerate (elements))
|
||||
std::cout << index << ' ' << value << ' ';
|
||||
@endcode
|
||||
|
||||
Note that the Enumerated instance is returned by value. This is because each Enumerated
|
||||
instance is created on-demand when the iterator is dereferenced. As a result, the following
|
||||
will result in a dangling reference, and will probably trigger a compiler warning:
|
||||
|
||||
@code
|
||||
// BAD IDEA: creating a reference to a temporary Enumerated instance
|
||||
for (auto& [index, value] : enumerate (elements))
|
||||
...
|
||||
@endcode
|
||||
|
||||
The 'value' member of Enumerated automatically assumes the same type as dereferencing the
|
||||
wrapped iterator, which is normally a reference to an element of a container.
|
||||
In the following snippet, the type of '[index, value]' is 'const Enumerated<ptrdiff_t, int&>',
|
||||
the type of 'index' is 'ptrdiff_t', and the type of 'value' is 'int&'.
|
||||
|
||||
@code
|
||||
std::vector<int> elements { 10, 20, 30, 40, 50 };
|
||||
for (const auto [index, value] : enumerate (elements))
|
||||
...
|
||||
@endcode
|
||||
|
||||
By default, the constness of pair.value will match the constness of the range passed to
|
||||
enumerate. If you pass a mutable lvalue reference to enumerate, then each value will also
|
||||
be mutable. If you pass a constant lvalue reference to enumerate, then each value will be
|
||||
const. If you know that you don't need the iterated elements to be mutable, it's good
|
||||
practice to wrap the range with std::as_const before passing it to enumerate:
|
||||
|
||||
@code
|
||||
for (const auto [index, value] : enumerate (std::as_const (elements)))
|
||||
{
|
||||
// value is immutable here
|
||||
}
|
||||
@endcode
|
||||
*/
|
||||
template <typename Range, typename Index = detail::withAdlSize::AdlSignedSize<Range>>
|
||||
[[nodiscard]] constexpr auto enumerate (Range&& range, Index startingValue = {})
|
||||
{
|
||||
// This ensures argument-dependent lookup works properly for user-defined non-member begin/end
|
||||
using std::begin, std::end;
|
||||
return makeRange (EnumerateIterator { begin (range), startingValue },
|
||||
EnumerateIterator { end (range), startingValue });
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class EnumerateUnitTest : public UnitTest
|
||||
{
|
||||
public:
|
||||
EnumerateUnitTest() : UnitTest ("Enumerate", UnitTestCategories::containers) {}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("enumeration works for bidirectional iterators");
|
||||
{
|
||||
const std::list<int> elements { 10, 20, 30, 40, 50 };
|
||||
std::vector<int> counts;
|
||||
|
||||
for (const auto pair : enumerate (elements))
|
||||
counts.push_back ((int) pair.index);
|
||||
|
||||
expect (counts == std::vector<int> { 0, 1, 2, 3, 4 });
|
||||
}
|
||||
|
||||
beginTest ("enumeration works for random-access iterators");
|
||||
{
|
||||
const std::vector<std::string> strings { "a", "bb", "ccc", "dddd", "eeeee" };
|
||||
|
||||
std::vector<int> counts;
|
||||
|
||||
for (const auto [count, element] : enumerate (strings))
|
||||
counts.push_back ((int) ((size_t) count + element.size()));
|
||||
|
||||
expect (counts == std::vector<int> { 1, 3, 5, 7, 9 });
|
||||
}
|
||||
|
||||
beginTest ("enumeration works for mutable ranges");
|
||||
{
|
||||
std::vector<std::string> strings { "", "", "", "", "" };
|
||||
|
||||
for (const auto [count, element] : enumerate (strings))
|
||||
element = std::to_string (count);
|
||||
|
||||
expect (strings == std::vector<std::string> { "0", "1", "2", "3", "4" });
|
||||
}
|
||||
|
||||
beginTest ("iterator can be incremented by more than one");
|
||||
{
|
||||
std::vector<int> ints (6);
|
||||
|
||||
const auto enumerated = enumerate (ints);
|
||||
|
||||
std::vector<int> counts;
|
||||
|
||||
for (auto b = enumerated.begin(), e = enumerated.end(); b != e; b += 2)
|
||||
counts.push_back ((int) (*b).index);
|
||||
|
||||
expect (counts == std::vector<int> { 0, 2, 4 });
|
||||
}
|
||||
|
||||
beginTest ("iterator can be started at a non-zero value");
|
||||
{
|
||||
const std::vector<int> ints (6);
|
||||
|
||||
std::vector<int> counts;
|
||||
|
||||
for (const auto enumerated : enumerate (ints, 5))
|
||||
counts.push_back ((int) enumerated.index);
|
||||
|
||||
expect (counts == std::vector<int> { 5, 6, 7, 8, 9, 10 });
|
||||
}
|
||||
|
||||
beginTest ("subtracting two EnumerateIterators returns the difference between the base iterators");
|
||||
{
|
||||
const std::vector<int> ints (6);
|
||||
const auto enumerated = enumerate (ints);
|
||||
expect ((int) (enumerated.end() - enumerated.begin()) == (int) ints.size());
|
||||
}
|
||||
|
||||
beginTest ("EnumerateIterator can be decremented");
|
||||
{
|
||||
const std::vector<int> ints (5);
|
||||
std::vector<int> counts;
|
||||
|
||||
const auto enumerated = enumerate (std::as_const (ints));
|
||||
|
||||
for (auto i = enumerated.end(), b = enumerated.begin(); i != b; --i)
|
||||
counts.push_back ((int) (*(i - 1)).index);
|
||||
|
||||
expect (counts == std::vector<int> { -1, -2, -3, -4, -5 });
|
||||
}
|
||||
|
||||
beginTest ("EnumerateIterator can be compared");
|
||||
{
|
||||
const std::vector<int> ints (6);
|
||||
const auto enumerated = enumerate (ints);
|
||||
expect (enumerated.begin() < enumerated.end());
|
||||
expect (enumerated.begin() <= enumerated.end());
|
||||
expect (enumerated.end() > enumerated.begin());
|
||||
expect (enumerated.end() >= enumerated.begin());
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static EnumerateUnitTest enumerateUnitTest;
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,245 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/** @cond */
|
||||
namespace detail
|
||||
{
|
||||
template <typename Ret, typename... Args>
|
||||
struct Vtable
|
||||
{
|
||||
using Storage = void*;
|
||||
|
||||
using Move = void (*) (Storage, Storage);
|
||||
using Call = Ret (*) (Storage, Args...);
|
||||
using Clear = void (*) (Storage);
|
||||
|
||||
constexpr Vtable (Move moveIn, Call callIn, Clear clearIn) noexcept
|
||||
: move (moveIn), call (callIn), clear (clearIn) {}
|
||||
|
||||
Move move = nullptr;
|
||||
Call call = nullptr;
|
||||
Clear clear = nullptr;
|
||||
};
|
||||
|
||||
template <typename Fn>
|
||||
void move (void* from, void* to)
|
||||
{
|
||||
new (to) Fn (std::move (*reinterpret_cast<Fn*> (from)));
|
||||
}
|
||||
|
||||
template <typename Fn, typename Ret, typename... Args>
|
||||
std::enable_if_t<std::is_same_v<Ret, void>, Ret> call (void* s, Args... args)
|
||||
{
|
||||
(*reinterpret_cast<Fn*> (s)) (std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
template <typename Fn, typename Ret, typename... Args>
|
||||
std::enable_if_t<! std::is_same_v<Ret, void>, Ret> call (void* s, Args... args)
|
||||
{
|
||||
return (*reinterpret_cast<Fn*> (s)) (std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
template <typename Fn>
|
||||
void clear (void* s)
|
||||
{
|
||||
// I know this looks insane, for some reason MSVC 14 sometimes thinks fn is unreferenced
|
||||
[[maybe_unused]] auto& fn = *reinterpret_cast<Fn*> (s);
|
||||
fn.~Fn();
|
||||
}
|
||||
|
||||
template <typename Fn, typename Ret, typename... Args>
|
||||
constexpr Vtable<Ret, Args...> makeVtable()
|
||||
{
|
||||
return { move <Fn>, call <Fn, Ret, Args...>, clear<Fn> };
|
||||
}
|
||||
} // namespace detail
|
||||
|
||||
template <size_t len, typename T>
|
||||
class FixedSizeFunction;
|
||||
/** @endcond */
|
||||
|
||||
/**
|
||||
A type similar to `std::function` that holds a callable object.
|
||||
|
||||
Unlike `std::function`, the callable object will always be stored in
|
||||
a buffer of size `len` that is internal to the FixedSizeFunction instance.
|
||||
This in turn means that creating a FixedSizeFunction instance will never allocate,
|
||||
making FixedSizeFunctions suitable for use in realtime contexts.
|
||||
|
||||
@tags{DSP}
|
||||
*/
|
||||
template <size_t len, typename Ret, typename... Args>
|
||||
class FixedSizeFunction<len, Ret (Args...)>
|
||||
{
|
||||
private:
|
||||
template <typename Item>
|
||||
using Decay = std::decay_t<Item>;
|
||||
|
||||
template <typename Item, typename Fn = Decay<Item>>
|
||||
using IntIfValidConversion = std::enable_if_t<sizeof (Fn) <= len
|
||||
&& alignof (Fn) <= alignof (std::max_align_t)
|
||||
&& ! std::is_same_v<FixedSizeFunction, Fn>,
|
||||
int>;
|
||||
|
||||
public:
|
||||
/** Create an empty function. */
|
||||
FixedSizeFunction() noexcept = default;
|
||||
|
||||
/** Create an empty function. */
|
||||
FixedSizeFunction (std::nullptr_t) noexcept
|
||||
: FixedSizeFunction() {}
|
||||
|
||||
FixedSizeFunction (const FixedSizeFunction&) = delete;
|
||||
|
||||
/** Forwards the passed Callable into the internal storage buffer. */
|
||||
template <typename Callable,
|
||||
typename Fn = Decay<Callable>,
|
||||
IntIfValidConversion<Callable> = 0>
|
||||
FixedSizeFunction (Callable&& callable)
|
||||
{
|
||||
static_assert (sizeof (Fn) <= len,
|
||||
"The requested function cannot fit in this FixedSizeFunction");
|
||||
static_assert (alignof (Fn) <= alignof (std::max_align_t),
|
||||
"FixedSizeFunction cannot accommodate the requested alignment requirements");
|
||||
|
||||
static constexpr auto vtableForCallable = detail::makeVtable<Fn, Ret, Args...>();
|
||||
vtable = &vtableForCallable;
|
||||
|
||||
[[maybe_unused]] auto* ptr = new (&storage) Fn (std::forward<Callable> (callable));
|
||||
jassert ((void*) ptr == (void*) &storage);
|
||||
}
|
||||
|
||||
/** Move constructor. */
|
||||
FixedSizeFunction (FixedSizeFunction&& other) noexcept
|
||||
: vtable (other.vtable)
|
||||
{
|
||||
move (std::move (other));
|
||||
}
|
||||
|
||||
/** Converting constructor from smaller FixedSizeFunctions. */
|
||||
template <size_t otherLen, std::enable_if_t<(otherLen < len), int> = 0>
|
||||
FixedSizeFunction (FixedSizeFunction<otherLen, Ret (Args...)>&& other) noexcept
|
||||
: vtable (other.vtable)
|
||||
{
|
||||
move (std::move (other));
|
||||
}
|
||||
|
||||
/** Nulls this instance. */
|
||||
FixedSizeFunction& operator= (std::nullptr_t) noexcept
|
||||
{
|
||||
return *this = FixedSizeFunction();
|
||||
}
|
||||
|
||||
FixedSizeFunction& operator= (const FixedSizeFunction&) = delete;
|
||||
|
||||
/** Assigns a new callable to this instance. */
|
||||
template <typename Callable, IntIfValidConversion<Callable> = 0>
|
||||
FixedSizeFunction& operator= (Callable&& callable)
|
||||
{
|
||||
return *this = FixedSizeFunction (std::forward<Callable> (callable));
|
||||
}
|
||||
|
||||
/** Move assignment from smaller FixedSizeFunctions. */
|
||||
template <size_t otherLen, std::enable_if_t<(otherLen < len), int> = 0>
|
||||
FixedSizeFunction& operator= (FixedSizeFunction<otherLen, Ret (Args...)>&& other) noexcept
|
||||
{
|
||||
return *this = FixedSizeFunction (std::move (other));
|
||||
}
|
||||
|
||||
/** Move assignment operator. */
|
||||
FixedSizeFunction& operator= (FixedSizeFunction&& other) noexcept
|
||||
{
|
||||
clear();
|
||||
vtable = other.vtable;
|
||||
move (std::move (other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Destructor. */
|
||||
~FixedSizeFunction() noexcept { clear(); }
|
||||
|
||||
/** If this instance is currently storing a callable object, calls that object,
|
||||
otherwise throws `std::bad_function_call`.
|
||||
*/
|
||||
Ret operator() (Args... args) const
|
||||
{
|
||||
if (vtable != nullptr)
|
||||
return vtable->call (&storage, std::forward<Args> (args)...);
|
||||
|
||||
throw std::bad_function_call();
|
||||
}
|
||||
|
||||
/** Returns true if this instance currently holds a callable. */
|
||||
explicit operator bool() const noexcept { return vtable != nullptr; }
|
||||
|
||||
private:
|
||||
template <size_t, typename>
|
||||
friend class FixedSizeFunction;
|
||||
|
||||
void clear() noexcept
|
||||
{
|
||||
if (vtable != nullptr)
|
||||
vtable->clear (&storage);
|
||||
}
|
||||
|
||||
template <size_t otherLen, typename T>
|
||||
void move (FixedSizeFunction<otherLen, T>&& other) noexcept
|
||||
{
|
||||
if (vtable != nullptr)
|
||||
vtable->move (&other.storage, &storage);
|
||||
}
|
||||
|
||||
const detail::Vtable<Ret, Args...>* vtable = nullptr;
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4324)
|
||||
alignas (std::max_align_t) mutable std::byte storage[len];
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
};
|
||||
|
||||
template <size_t len, typename T>
|
||||
bool operator!= (const FixedSizeFunction<len, T>& fn, std::nullptr_t) { return bool (fn); }
|
||||
|
||||
template <size_t len, typename T>
|
||||
bool operator!= (std::nullptr_t, const FixedSizeFunction<len, T>& fn) { return bool (fn); }
|
||||
|
||||
template <size_t len, typename T>
|
||||
bool operator== (const FixedSizeFunction<len, T>& fn, std::nullptr_t) { return ! (fn != nullptr); }
|
||||
|
||||
template <size_t len, typename T>
|
||||
bool operator== (std::nullptr_t, const FixedSizeFunction<len, T>& fn) { return ! (fn != nullptr); }
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,373 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
#if JUCE_ENABLE_ALLOCATION_HOOKS
|
||||
#define JUCE_FAIL_ON_ALLOCATION_IN_SCOPE const UnitTestAllocationChecker checker (*this)
|
||||
#else
|
||||
#define JUCE_FAIL_ON_ALLOCATION_IN_SCOPE
|
||||
#endif
|
||||
|
||||
namespace juce
|
||||
{
|
||||
namespace
|
||||
{
|
||||
|
||||
class ConstructCounts
|
||||
{
|
||||
auto tie() const noexcept { return std::tie (constructions, copies, moves, calls, destructions); }
|
||||
|
||||
public:
|
||||
int constructions = 0;
|
||||
int copies = 0;
|
||||
int moves = 0;
|
||||
int calls = 0;
|
||||
int destructions = 0;
|
||||
|
||||
ConstructCounts withConstructions (int i) const noexcept { auto c = *this; c.constructions = i; return c; }
|
||||
ConstructCounts withCopies (int i) const noexcept { auto c = *this; c.copies = i; return c; }
|
||||
ConstructCounts withMoves (int i) const noexcept { auto c = *this; c.moves = i; return c; }
|
||||
ConstructCounts withCalls (int i) const noexcept { auto c = *this; c.calls = i; return c; }
|
||||
ConstructCounts withDestructions (int i) const noexcept { auto c = *this; c.destructions = i; return c; }
|
||||
|
||||
bool operator== (const ConstructCounts& other) const noexcept { return tie() == other.tie(); }
|
||||
bool operator!= (const ConstructCounts& other) const noexcept { return tie() != other.tie(); }
|
||||
};
|
||||
|
||||
String& operator<< (String& str, const ConstructCounts& c)
|
||||
{
|
||||
return str << "{ constructions: " << c.constructions
|
||||
<< ", copies: " << c.copies
|
||||
<< ", moves: " << c.moves
|
||||
<< ", calls: " << c.calls
|
||||
<< ", destructions: " << c.destructions
|
||||
<< " }";
|
||||
}
|
||||
|
||||
class FixedSizeFunctionTest final : public UnitTest
|
||||
{
|
||||
static void toggleBool (bool& b) { b = ! b; }
|
||||
|
||||
struct ConstructCounter
|
||||
{
|
||||
explicit ConstructCounter (ConstructCounts& countsIn)
|
||||
: counts (countsIn) {}
|
||||
|
||||
ConstructCounter (const ConstructCounter& c)
|
||||
: counts (c.counts)
|
||||
{
|
||||
counts.copies += 1;
|
||||
}
|
||||
|
||||
ConstructCounter (ConstructCounter&& c) noexcept
|
||||
: counts (c.counts)
|
||||
{
|
||||
counts.moves += 1;
|
||||
}
|
||||
|
||||
~ConstructCounter() noexcept { counts.destructions += 1; }
|
||||
|
||||
void operator()() const noexcept { counts.calls += 1; }
|
||||
|
||||
ConstructCounts& counts;
|
||||
};
|
||||
|
||||
public:
|
||||
FixedSizeFunctionTest()
|
||||
: UnitTest ("Fixed Size Function", UnitTestCategories::containers)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("Can be constructed and called from a lambda");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
const auto result = 5;
|
||||
bool wasCalled = false;
|
||||
const auto lambda = [&] { wasCalled = true; return result; };
|
||||
|
||||
const FixedSizeFunction<sizeof (lambda), int()> fn (lambda);
|
||||
const auto out = fn();
|
||||
|
||||
expect (wasCalled);
|
||||
expectEquals (result, out);
|
||||
}
|
||||
|
||||
beginTest ("void fn can be constructed from function with return value");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
bool wasCalled = false;
|
||||
const auto lambda = [&] { wasCalled = true; return 5; };
|
||||
const FixedSizeFunction<sizeof (lambda), void()> fn (lambda);
|
||||
|
||||
fn();
|
||||
expect (wasCalled);
|
||||
}
|
||||
|
||||
beginTest ("Can be constructed and called from a function pointer");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
bool state = false;
|
||||
|
||||
const FixedSizeFunction<sizeof (void*), void (bool&)> fn (toggleBool);
|
||||
|
||||
fn (state);
|
||||
expect (state);
|
||||
|
||||
fn (state);
|
||||
expect (! state);
|
||||
|
||||
fn (state);
|
||||
expect (state);
|
||||
}
|
||||
|
||||
beginTest ("Default constructed functions throw if called");
|
||||
{
|
||||
const auto a = FixedSizeFunction<8, void()>();
|
||||
expectThrowsType (a(), std::bad_function_call)
|
||||
|
||||
const auto b = FixedSizeFunction<8, void()> (nullptr);
|
||||
expectThrowsType (b(), std::bad_function_call)
|
||||
}
|
||||
|
||||
beginTest ("Functions can be moved");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
ConstructCounts counts;
|
||||
|
||||
auto a = FixedSizeFunction<sizeof (ConstructCounter), void()> (ConstructCounter { counts });
|
||||
expectEquals (counts, ConstructCounts().withMoves (1).withDestructions (1)); // The temporary gets destroyed
|
||||
|
||||
a();
|
||||
expectEquals (counts, ConstructCounts().withMoves (1).withDestructions (1).withCalls (1));
|
||||
|
||||
const auto b = std::move (a);
|
||||
expectEquals (counts, ConstructCounts().withMoves (2).withDestructions (1).withCalls (1));
|
||||
|
||||
b();
|
||||
expectEquals (counts, ConstructCounts().withMoves (2).withDestructions (1).withCalls (2));
|
||||
|
||||
b();
|
||||
expectEquals (counts, ConstructCounts().withMoves (2).withDestructions (1).withCalls (3));
|
||||
}
|
||||
|
||||
beginTest ("Functions are destructed properly");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
ConstructCounts counts;
|
||||
const ConstructCounter toCopy { counts };
|
||||
|
||||
{
|
||||
auto a = FixedSizeFunction<sizeof (ConstructCounter), void()> (toCopy);
|
||||
expectEquals (counts, ConstructCounts().withCopies (1));
|
||||
}
|
||||
|
||||
expectEquals (counts, ConstructCounts().withCopies (1).withDestructions (1));
|
||||
}
|
||||
|
||||
beginTest ("Avoid destructing functions that fail to construct");
|
||||
{
|
||||
struct BadConstructor
|
||||
{
|
||||
explicit BadConstructor (ConstructCounts& c)
|
||||
: counts (c)
|
||||
{
|
||||
counts.constructions += 1;
|
||||
throw std::runtime_error { "this was meant to happen" };
|
||||
}
|
||||
|
||||
BadConstructor (const BadConstructor&) = default;
|
||||
BadConstructor& operator= (const BadConstructor&) = delete;
|
||||
|
||||
~BadConstructor() noexcept { counts.destructions += 1; }
|
||||
|
||||
void operator()() const noexcept { counts.calls += 1; }
|
||||
|
||||
ConstructCounts& counts;
|
||||
};
|
||||
|
||||
ConstructCounts counts;
|
||||
|
||||
expectThrowsType ((FixedSizeFunction<sizeof (BadConstructor), void()> (BadConstructor { counts })),
|
||||
std::runtime_error)
|
||||
|
||||
expectEquals (counts, ConstructCounts().withConstructions (1));
|
||||
}
|
||||
|
||||
beginTest ("Equality checks work");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
FixedSizeFunction<8, void()> a;
|
||||
expect (! bool (a));
|
||||
expect (a == nullptr);
|
||||
expect (nullptr == a);
|
||||
expect (! (a != nullptr));
|
||||
expect (! (nullptr != a));
|
||||
|
||||
FixedSizeFunction<8, void()> b ([] {});
|
||||
expect (bool (b));
|
||||
expect (b != nullptr);
|
||||
expect (nullptr != b);
|
||||
expect (! (b == nullptr));
|
||||
expect (! (nullptr == b));
|
||||
}
|
||||
|
||||
beginTest ("Functions can be cleared");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
FixedSizeFunction<8, void()> fn ([] {});
|
||||
expect (bool (fn));
|
||||
|
||||
fn = nullptr;
|
||||
expect (! bool (fn));
|
||||
}
|
||||
|
||||
beginTest ("Functions can be assigned");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
using Fn = FixedSizeFunction<8, void()>;
|
||||
|
||||
int numCallsA = 0;
|
||||
int numCallsB = 0;
|
||||
|
||||
Fn x;
|
||||
Fn y;
|
||||
expect (! bool (x));
|
||||
expect (! bool (y));
|
||||
|
||||
x = [&] { numCallsA += 1; };
|
||||
y = [&] { numCallsB += 1; };
|
||||
expect (bool (x));
|
||||
expect (bool (y));
|
||||
|
||||
x();
|
||||
expectEquals (numCallsA, 1);
|
||||
expectEquals (numCallsB, 0);
|
||||
|
||||
y();
|
||||
expectEquals (numCallsA, 1);
|
||||
expectEquals (numCallsB, 1);
|
||||
|
||||
x = std::move (y);
|
||||
expectEquals (numCallsA, 1);
|
||||
expectEquals (numCallsB, 1);
|
||||
|
||||
x();
|
||||
expectEquals (numCallsA, 1);
|
||||
expectEquals (numCallsB, 2);
|
||||
}
|
||||
|
||||
beginTest ("Functions may mutate internal state");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
using Fn = FixedSizeFunction<64, void()>;
|
||||
|
||||
Fn x;
|
||||
expect (! bool (x));
|
||||
|
||||
int numCalls = 0;
|
||||
x = [&numCalls, counter = 0]() mutable { counter += 1; numCalls = counter; };
|
||||
expect (bool (x));
|
||||
|
||||
expectEquals (numCalls, 0);
|
||||
|
||||
x();
|
||||
expectEquals (numCalls, 1);
|
||||
|
||||
x();
|
||||
expectEquals (numCalls, 2);
|
||||
}
|
||||
|
||||
beginTest ("Functions can sink move-only parameters");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
using FnA = FixedSizeFunction<64, int (std::unique_ptr<int>)>;
|
||||
|
||||
auto value = 5;
|
||||
auto ptr = std::make_unique<int> (value);
|
||||
|
||||
FnA fnA = [] (std::unique_ptr<int> p) { return *p; };
|
||||
|
||||
expect (value == fnA (std::move (ptr)));
|
||||
|
||||
using FnB = FixedSizeFunction<64, void (std::unique_ptr<int>&&)>;
|
||||
|
||||
FnB fnB = [&value] (std::unique_ptr<int>&& p)
|
||||
{
|
||||
auto x = std::move (p);
|
||||
value = *x;
|
||||
};
|
||||
|
||||
const auto newValue = 10;
|
||||
fnB (std::make_unique<int> (newValue));
|
||||
expect (value == newValue);
|
||||
}
|
||||
|
||||
beginTest ("Functions be converted from smaller functions");
|
||||
{
|
||||
JUCE_FAIL_ON_ALLOCATION_IN_SCOPE;
|
||||
|
||||
using SmallFn = FixedSizeFunction<20, void()>;
|
||||
using LargeFn = FixedSizeFunction<21, void()>;
|
||||
|
||||
bool smallCalled = false;
|
||||
bool largeCalled = false;
|
||||
|
||||
SmallFn small = [&smallCalled, a = std::array<char, 8>{}] { smallCalled = true; ignoreUnused (a); };
|
||||
LargeFn large = [&largeCalled, a = std::array<char, 8>{}] { largeCalled = true; ignoreUnused (a); };
|
||||
|
||||
large = std::move (small);
|
||||
|
||||
large();
|
||||
|
||||
expect (smallCalled);
|
||||
expect (! largeCalled);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
FixedSizeFunctionTest fixedSizedFunctionTest;
|
||||
|
||||
}
|
||||
} // namespace juce
|
||||
#undef JUCE_FAIL_ON_ALLOCATION_IN_SCOPE
|
||||
@@ -0,0 +1,518 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A simple class to generate hash functions for some primitive types, intended for
|
||||
use with the HashMap class.
|
||||
@see HashMap
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
struct DefaultHashFunctions
|
||||
{
|
||||
/** Generates a simple hash from an unsigned int. */
|
||||
static int generateHash (uint32 key, int upperLimit) noexcept { return (int) (key % (uint32) upperLimit); }
|
||||
/** Generates a simple hash from an integer. */
|
||||
static int generateHash (int32 key, int upperLimit) noexcept { return generateHash ((uint32) key, upperLimit); }
|
||||
/** Generates a simple hash from a uint64. */
|
||||
static int generateHash (uint64 key, int upperLimit) noexcept { return (int) (key % (uint64) upperLimit); }
|
||||
/** Generates a simple hash from an int64. */
|
||||
static int generateHash (int64 key, int upperLimit) noexcept { return generateHash ((uint64) key, upperLimit); }
|
||||
/** Generates a simple hash from a string. */
|
||||
static int generateHash (const String& key, int upperLimit) noexcept { return generateHash ((uint32) key.hashCode(), upperLimit); }
|
||||
/** Generates a simple hash from a variant. */
|
||||
static int generateHash (const var& key, int upperLimit) noexcept { return generateHash (key.toString(), upperLimit); }
|
||||
/** Generates a simple hash from a void ptr. */
|
||||
static int generateHash (const void* key, int upperLimit) noexcept { return generateHash ((uint64) (pointer_sized_uint) key, upperLimit); }
|
||||
/** Generates a simple hash from a UUID. */
|
||||
static int generateHash (const Uuid& key, int upperLimit) noexcept { return generateHash (key.hash(), upperLimit); }
|
||||
};
|
||||
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Holds a set of mappings between some key/value pairs.
|
||||
|
||||
The types of the key and value objects are set as template parameters.
|
||||
You can also specify a class to supply a hash function that converts a key value
|
||||
into an hashed integer. This class must have the form:
|
||||
|
||||
@code
|
||||
struct MyHashGenerator
|
||||
{
|
||||
int generateHash (MyKeyType key, int upperLimit) const
|
||||
{
|
||||
// The function must return a value 0 <= x < upperLimit
|
||||
return someFunctionOfMyKeyType (key) % upperLimit;
|
||||
}
|
||||
};
|
||||
@endcode
|
||||
|
||||
Like the Array class, the key and value types are expected to be copy-by-value
|
||||
types, so if you define them to be pointer types, this class won't delete the
|
||||
objects that they point to.
|
||||
|
||||
If you don't supply a class for the HashFunctionType template parameter, the
|
||||
default one provides some simple mappings for strings and ints.
|
||||
|
||||
@code
|
||||
HashMap<int, String> hash;
|
||||
hash.set (1, "item1");
|
||||
hash.set (2, "item2");
|
||||
|
||||
DBG (hash [1]); // prints "item1"
|
||||
DBG (hash [2]); // prints "item2"
|
||||
|
||||
// This iterates the map, printing all of its key -> value pairs.
|
||||
for (HashMap<int, String>::Iterator i (hash); i.next();)
|
||||
DBG (i.getKey() << " -> " << i.getValue());
|
||||
@endcode
|
||||
|
||||
@tparam HashFunctionType The class of hash function, which must be copy-constructible.
|
||||
@see CriticalSection, DefaultHashFunctions, NamedValueSet, SortedSet
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename KeyType,
|
||||
typename ValueType,
|
||||
class HashFunctionType = DefaultHashFunctions,
|
||||
class TypeOfCriticalSectionToUse = DummyCriticalSection>
|
||||
class HashMap
|
||||
{
|
||||
private:
|
||||
using KeyTypeParameter = typename TypeHelpers::ParameterType<KeyType>::type;
|
||||
using ValueTypeParameter = typename TypeHelpers::ParameterType<ValueType>::type;
|
||||
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty hash-map.
|
||||
|
||||
@param numberOfSlots Specifies the number of hash entries the map will use. This will be
|
||||
the "upperLimit" parameter that is passed to your generateHash()
|
||||
function. The number of hash slots will grow automatically if necessary,
|
||||
or it can be remapped manually using remapTable().
|
||||
@param hashFunction An instance of HashFunctionType, which will be copied and
|
||||
stored to use with the HashMap. This parameter can be omitted
|
||||
if HashFunctionType has a default constructor.
|
||||
*/
|
||||
explicit HashMap (int numberOfSlots = defaultHashTableSize,
|
||||
HashFunctionType hashFunction = HashFunctionType())
|
||||
: hashFunctionToUse (hashFunction)
|
||||
{
|
||||
hashSlots.insertMultiple (0, nullptr, numberOfSlots);
|
||||
}
|
||||
|
||||
/** Destructor. */
|
||||
~HashMap()
|
||||
{
|
||||
clear();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Removes all values from the map.
|
||||
Note that this will clear the content, but won't affect the number of slots (see
|
||||
remapTable and getNumSlots).
|
||||
*/
|
||||
void clear()
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
|
||||
for (auto i = hashSlots.size(); --i >= 0;)
|
||||
{
|
||||
auto* h = hashSlots.getUnchecked (i);
|
||||
|
||||
while (h != nullptr)
|
||||
{
|
||||
const std::unique_ptr<HashEntry> deleter (h);
|
||||
h = h->nextEntry;
|
||||
}
|
||||
|
||||
hashSlots.set (i, nullptr);
|
||||
}
|
||||
|
||||
totalNumItems = 0;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the current number of items in the map. */
|
||||
inline int size() const noexcept
|
||||
{
|
||||
return totalNumItems;
|
||||
}
|
||||
|
||||
/** Returns the value corresponding to a given key.
|
||||
If the map doesn't contain the key, a default instance of the value type is returned.
|
||||
@param keyToLookFor the key of the item being requested
|
||||
*/
|
||||
inline ValueType operator[] (KeyTypeParameter keyToLookFor) const
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
|
||||
if (auto* entry = getEntry (getSlot (keyToLookFor), keyToLookFor))
|
||||
return entry->value;
|
||||
|
||||
return ValueType();
|
||||
}
|
||||
|
||||
/** Returns a reference to the value corresponding to a given key.
|
||||
If the map doesn't contain the key, a default instance of the value type is
|
||||
added to the map and a reference to this is returned.
|
||||
@param keyToLookFor the key of the item being requested
|
||||
*/
|
||||
inline ValueType& getReference (KeyTypeParameter keyToLookFor)
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
auto hashIndex = generateHashFor (keyToLookFor, getNumSlots());
|
||||
|
||||
auto* firstEntry = hashSlots.getUnchecked (hashIndex);
|
||||
|
||||
if (auto* entry = getEntry (firstEntry, keyToLookFor))
|
||||
return entry->value;
|
||||
|
||||
auto* entry = new HashEntry (keyToLookFor, ValueType(), firstEntry);
|
||||
hashSlots.set (hashIndex, entry);
|
||||
++totalNumItems;
|
||||
|
||||
if (totalNumItems > (getNumSlots() * 3) / 2)
|
||||
remapTable (getNumSlots() * 2);
|
||||
|
||||
return entry->value;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns true if the map contains an item with the specified key. */
|
||||
bool contains (KeyTypeParameter keyToLookFor) const
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
|
||||
return (getEntry (getSlot (keyToLookFor), keyToLookFor) != nullptr);
|
||||
}
|
||||
|
||||
/** Returns true if the hash contains at least one occurrence of a given value. */
|
||||
bool containsValue (ValueTypeParameter valueToLookFor) const
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
|
||||
for (auto i = getNumSlots(); --i >= 0;)
|
||||
for (auto* entry = hashSlots.getUnchecked (i); entry != nullptr; entry = entry->nextEntry)
|
||||
if (entry->value == valueToLookFor)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Adds or replaces an element in the hash-map.
|
||||
If there's already an item with the given key, this will replace its value. Otherwise, a new item
|
||||
will be added to the map.
|
||||
*/
|
||||
void set (KeyTypeParameter newKey, ValueTypeParameter newValue) { getReference (newKey) = newValue; }
|
||||
|
||||
/** Removes an item with the given key. */
|
||||
void remove (KeyTypeParameter keyToRemove)
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
auto hashIndex = generateHashFor (keyToRemove, getNumSlots());
|
||||
auto* entry = hashSlots.getUnchecked (hashIndex);
|
||||
HashEntry* previous = nullptr;
|
||||
|
||||
while (entry != nullptr)
|
||||
{
|
||||
if (entry->key == keyToRemove)
|
||||
{
|
||||
const std::unique_ptr<HashEntry> deleter (entry);
|
||||
|
||||
entry = entry->nextEntry;
|
||||
|
||||
if (previous != nullptr)
|
||||
previous->nextEntry = entry;
|
||||
else
|
||||
hashSlots.set (hashIndex, entry);
|
||||
|
||||
--totalNumItems;
|
||||
}
|
||||
else
|
||||
{
|
||||
previous = entry;
|
||||
entry = entry->nextEntry;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes all items with the given value. */
|
||||
void removeValue (ValueTypeParameter valueToRemove)
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
|
||||
for (auto i = getNumSlots(); --i >= 0;)
|
||||
{
|
||||
auto* entry = hashSlots.getUnchecked (i);
|
||||
HashEntry* previous = nullptr;
|
||||
|
||||
while (entry != nullptr)
|
||||
{
|
||||
if (entry->value == valueToRemove)
|
||||
{
|
||||
const std::unique_ptr<HashEntry> deleter (entry);
|
||||
|
||||
entry = entry->nextEntry;
|
||||
|
||||
if (previous != nullptr)
|
||||
previous->nextEntry = entry;
|
||||
else
|
||||
hashSlots.set (i, entry);
|
||||
|
||||
--totalNumItems;
|
||||
}
|
||||
else
|
||||
{
|
||||
previous = entry;
|
||||
entry = entry->nextEntry;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Remaps the hash-map to use a different number of slots for its hash function.
|
||||
Each slot corresponds to a single hash-code, and each one can contain multiple items.
|
||||
@see getNumSlots()
|
||||
*/
|
||||
void remapTable (int newNumberOfSlots)
|
||||
{
|
||||
const ScopedLockType sl (getLock());
|
||||
|
||||
Array<HashEntry*> newSlots;
|
||||
newSlots.insertMultiple (0, nullptr, newNumberOfSlots);
|
||||
|
||||
for (auto i = getNumSlots(); --i >= 0;)
|
||||
{
|
||||
HashEntry* nextEntry = nullptr;
|
||||
|
||||
for (auto* entry = hashSlots.getUnchecked (i); entry != nullptr; entry = nextEntry)
|
||||
{
|
||||
auto hashIndex = generateHashFor (entry->key, newNumberOfSlots);
|
||||
|
||||
nextEntry = entry->nextEntry;
|
||||
entry->nextEntry = newSlots.getUnchecked (hashIndex);
|
||||
|
||||
newSlots.set (hashIndex, entry);
|
||||
}
|
||||
}
|
||||
|
||||
hashSlots.swapWith (newSlots);
|
||||
}
|
||||
|
||||
/** Returns the number of slots which are available for hashing.
|
||||
Each slot corresponds to a single hash-code, and each one can contain multiple items.
|
||||
@see getNumSlots()
|
||||
*/
|
||||
inline int getNumSlots() const noexcept
|
||||
{
|
||||
return hashSlots.size();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Efficiently swaps the contents of two hash-maps. */
|
||||
template <class OtherHashMapType>
|
||||
void swapWith (OtherHashMapType& otherHashMap) noexcept
|
||||
{
|
||||
const ScopedLockType lock1 (getLock());
|
||||
const typename OtherHashMapType::ScopedLockType lock2 (otherHashMap.getLock());
|
||||
|
||||
hashSlots.swapWith (otherHashMap.hashSlots);
|
||||
std::swap (totalNumItems, otherHashMap.totalNumItems);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the CriticalSection that locks this structure.
|
||||
To lock, you can call getLock().enter() and getLock().exit(), or preferably use
|
||||
an object of ScopedLockType as an RAII lock for it.
|
||||
*/
|
||||
inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return lock; }
|
||||
|
||||
/** Returns the type of scoped lock to use for locking this array */
|
||||
using ScopedLockType = typename TypeOfCriticalSectionToUse::ScopedLockType;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
class HashEntry
|
||||
{
|
||||
public:
|
||||
HashEntry (KeyTypeParameter k, ValueTypeParameter val, HashEntry* const next)
|
||||
: key (k), value (val), nextEntry (next)
|
||||
{}
|
||||
|
||||
const KeyType key;
|
||||
ValueType value;
|
||||
HashEntry* nextEntry;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (HashEntry)
|
||||
};
|
||||
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Iterates over the items in a HashMap.
|
||||
|
||||
To use it, repeatedly call next() until it returns false, e.g.
|
||||
@code
|
||||
HashMap <String, String> myMap;
|
||||
|
||||
HashMap<String, String>::Iterator i (myMap);
|
||||
|
||||
while (i.next())
|
||||
{
|
||||
DBG (i.getKey() << " -> " << i.getValue());
|
||||
}
|
||||
@endcode
|
||||
|
||||
The order in which items are iterated bears no resemblance to the order in which
|
||||
they were originally added!
|
||||
|
||||
Obviously as soon as you call any non-const methods on the original hash-map, any
|
||||
iterators that were created beforehand will cease to be valid, and should not be used.
|
||||
|
||||
@see HashMap
|
||||
*/
|
||||
struct Iterator
|
||||
{
|
||||
Iterator (const HashMap& hashMapToIterate) noexcept
|
||||
: hashMap (hashMapToIterate), entry (nullptr), index (0)
|
||||
{}
|
||||
|
||||
Iterator (const Iterator& other) noexcept
|
||||
: hashMap (other.hashMap), entry (other.entry), index (other.index)
|
||||
{}
|
||||
|
||||
/** Moves to the next item, if one is available.
|
||||
When this returns true, you can get the item's key and value using getKey() and
|
||||
getValue(). If it returns false, the iteration has finished and you should stop.
|
||||
*/
|
||||
bool next() noexcept
|
||||
{
|
||||
if (entry != nullptr)
|
||||
entry = entry->nextEntry;
|
||||
|
||||
while (entry == nullptr)
|
||||
{
|
||||
if (index >= hashMap.getNumSlots())
|
||||
return false;
|
||||
|
||||
entry = hashMap.hashSlots.getUnchecked (index++);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Returns the current item's key.
|
||||
This should only be called when a call to next() has just returned true.
|
||||
*/
|
||||
KeyType getKey() const
|
||||
{
|
||||
return entry != nullptr ? entry->key : KeyType();
|
||||
}
|
||||
|
||||
/** Returns the current item's value.
|
||||
This should only be called when a call to next() has just returned true.
|
||||
*/
|
||||
ValueType getValue() const
|
||||
{
|
||||
return entry != nullptr ? entry->value : ValueType();
|
||||
}
|
||||
|
||||
/** Resets the iterator to its starting position. */
|
||||
void reset() noexcept
|
||||
{
|
||||
entry = nullptr;
|
||||
index = 0;
|
||||
}
|
||||
|
||||
Iterator& operator++() noexcept { next(); return *this; }
|
||||
ValueType operator*() const { return getValue(); }
|
||||
bool operator!= (const Iterator& other) const noexcept { return entry != other.entry || index != other.index; }
|
||||
void resetToEnd() noexcept { index = hashMap.getNumSlots(); }
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
const HashMap& hashMap;
|
||||
HashEntry* entry;
|
||||
int index;
|
||||
|
||||
// using the copy constructor is ok, but you cannot assign iterators
|
||||
Iterator& operator= (const Iterator&) = delete;
|
||||
|
||||
JUCE_LEAK_DETECTOR (Iterator)
|
||||
};
|
||||
|
||||
/** Returns a start iterator for the values in this tree. */
|
||||
Iterator begin() const noexcept { Iterator i (*this); i.next(); return i; }
|
||||
|
||||
/** Returns an end iterator for the values in this tree. */
|
||||
Iterator end() const noexcept { Iterator i (*this); i.resetToEnd(); return i; }
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
enum { defaultHashTableSize = 101 };
|
||||
friend struct Iterator;
|
||||
|
||||
HashFunctionType hashFunctionToUse;
|
||||
Array<HashEntry*> hashSlots;
|
||||
int totalNumItems = 0;
|
||||
TypeOfCriticalSectionToUse lock;
|
||||
|
||||
int generateHashFor (KeyTypeParameter key, int numSlots) const
|
||||
{
|
||||
const int hash = hashFunctionToUse.generateHash (key, numSlots);
|
||||
jassert (isPositiveAndBelow (hash, numSlots)); // your hash function is generating out-of-range numbers!
|
||||
return hash;
|
||||
}
|
||||
|
||||
static HashEntry* getEntry (HashEntry* firstEntry, KeyType keyToLookFor) noexcept
|
||||
{
|
||||
for (auto* entry = firstEntry; entry != nullptr; entry = entry->nextEntry)
|
||||
if (entry->key == keyToLookFor)
|
||||
return entry;
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
inline HashEntry* getSlot (KeyType key) const noexcept { return hashSlots.getUnchecked (generateHashFor (key, getNumSlots())); }
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (HashMap)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,290 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
struct HashMapTest final : public UnitTest
|
||||
{
|
||||
HashMapTest()
|
||||
: UnitTest ("HashMap", UnitTestCategories::containers)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
doTest<AddElementsTest> ("AddElementsTest");
|
||||
doTest<AccessTest> ("AccessTest");
|
||||
doTest<RemoveTest> ("RemoveTest");
|
||||
doTest<PersistantMemoryLocationOfValues> ("PersistantMemoryLocationOfValues");
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
struct AddElementsTest
|
||||
{
|
||||
template <typename KeyType>
|
||||
static void run (UnitTest& u)
|
||||
{
|
||||
AssociativeMap<KeyType, int> groundTruth;
|
||||
HashMap<KeyType, int> hashMap;
|
||||
|
||||
RandomKeys<KeyType> keyOracle (300, 3827829);
|
||||
Random valueOracle (48735);
|
||||
|
||||
int totalValues = 0;
|
||||
for (int i = 0; i < 10000; ++i)
|
||||
{
|
||||
auto key = keyOracle.next();
|
||||
auto value = valueOracle.nextInt();
|
||||
|
||||
bool contains = (groundTruth.find (key) != nullptr);
|
||||
u.expectEquals ((int) contains, (int) hashMap.contains (key));
|
||||
|
||||
groundTruth.add (key, value);
|
||||
hashMap.set (key, value);
|
||||
|
||||
if (! contains) totalValues++;
|
||||
|
||||
u.expectEquals (hashMap.size(), totalValues);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
struct AccessTest
|
||||
{
|
||||
template <typename KeyType>
|
||||
static void run (UnitTest& u)
|
||||
{
|
||||
AssociativeMap<KeyType, int> groundTruth;
|
||||
HashMap<KeyType, int> hashMap;
|
||||
|
||||
fillWithRandomValues (hashMap, groundTruth);
|
||||
|
||||
for (auto pair : groundTruth.pairs)
|
||||
u.expectEquals (hashMap[pair.key], pair.value);
|
||||
}
|
||||
};
|
||||
|
||||
struct RemoveTest
|
||||
{
|
||||
template <typename KeyType>
|
||||
static void run (UnitTest& u)
|
||||
{
|
||||
AssociativeMap<KeyType, int> groundTruth;
|
||||
HashMap<KeyType, int> hashMap;
|
||||
|
||||
fillWithRandomValues (hashMap, groundTruth);
|
||||
auto n = groundTruth.size();
|
||||
|
||||
Random r (3827387);
|
||||
|
||||
for (int i = 0; i < 100; ++i)
|
||||
{
|
||||
auto idx = r.nextInt (n-- - 1);
|
||||
auto key = groundTruth.pairs.getReference (idx).key;
|
||||
|
||||
groundTruth.pairs.remove (idx);
|
||||
hashMap.remove (key);
|
||||
|
||||
u.expect (! hashMap.contains (key));
|
||||
|
||||
for (auto pair : groundTruth.pairs)
|
||||
u.expectEquals (hashMap[pair.key], pair.value);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// ensure that the addresses of object references don't change
|
||||
struct PersistantMemoryLocationOfValues
|
||||
{
|
||||
struct AddressAndValue { int value; const int* valueAddress; };
|
||||
|
||||
template <typename KeyType>
|
||||
static void run (UnitTest& u)
|
||||
{
|
||||
AssociativeMap<KeyType, AddressAndValue> groundTruth;
|
||||
HashMap<KeyType, int> hashMap;
|
||||
|
||||
RandomKeys<KeyType> keyOracle (300, 3827829);
|
||||
Random valueOracle (48735);
|
||||
|
||||
for (int i = 0; i < 1000; ++i)
|
||||
{
|
||||
auto key = keyOracle.next();
|
||||
auto value = valueOracle.nextInt();
|
||||
|
||||
hashMap.set (key, value);
|
||||
|
||||
if (auto* existing = groundTruth.find (key))
|
||||
{
|
||||
// don't change the address: only the value
|
||||
existing->value = value;
|
||||
}
|
||||
else
|
||||
{
|
||||
groundTruth.add (key, { value, &hashMap.getReference (key) });
|
||||
}
|
||||
|
||||
for (auto pair : groundTruth.pairs)
|
||||
{
|
||||
const auto& hashMapValue = hashMap.getReference (pair.key);
|
||||
|
||||
u.expectEquals (hashMapValue, pair.value.value);
|
||||
u.expect (&hashMapValue == pair.value.valueAddress);
|
||||
}
|
||||
}
|
||||
|
||||
auto n = groundTruth.size();
|
||||
Random r (3827387);
|
||||
|
||||
for (int i = 0; i < 100; ++i)
|
||||
{
|
||||
auto idx = r.nextInt (n-- - 1);
|
||||
auto key = groundTruth.pairs.getReference (idx).key;
|
||||
|
||||
groundTruth.pairs.remove (idx);
|
||||
hashMap.remove (key);
|
||||
|
||||
for (auto pair : groundTruth.pairs)
|
||||
{
|
||||
const auto& hashMapValue = hashMap.getReference (pair.key);
|
||||
|
||||
u.expectEquals (hashMapValue, pair.value.value);
|
||||
u.expect (&hashMapValue == pair.value.valueAddress);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
template <class Test>
|
||||
void doTest (const String& testName)
|
||||
{
|
||||
beginTest (testName);
|
||||
|
||||
Test::template run<int> (*this);
|
||||
Test::template run<void*> (*this);
|
||||
Test::template run<String> (*this);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <typename KeyType, typename ValueType>
|
||||
struct AssociativeMap
|
||||
{
|
||||
struct KeyValuePair { KeyType key; ValueType value; };
|
||||
|
||||
ValueType* find (KeyType key)
|
||||
{
|
||||
auto n = pairs.size();
|
||||
|
||||
for (int i = 0; i < n; ++i)
|
||||
{
|
||||
auto& pair = pairs.getReference (i);
|
||||
|
||||
if (pair.key == key)
|
||||
return &pair.value;
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
void add (KeyType key, ValueType value)
|
||||
{
|
||||
if (ValueType* v = find (key))
|
||||
*v = value;
|
||||
else
|
||||
pairs.add ({key, value});
|
||||
}
|
||||
|
||||
int size() const { return pairs.size(); }
|
||||
|
||||
Array<KeyValuePair> pairs;
|
||||
};
|
||||
|
||||
template <typename KeyType, typename ValueType>
|
||||
static void fillWithRandomValues (HashMap<KeyType, int>& hashMap, AssociativeMap<KeyType, ValueType>& groundTruth)
|
||||
{
|
||||
RandomKeys<KeyType> keyOracle (300, 3827829);
|
||||
Random valueOracle (48735);
|
||||
|
||||
for (int i = 0; i < 10000; ++i)
|
||||
{
|
||||
auto key = keyOracle.next();
|
||||
auto value = valueOracle.nextInt();
|
||||
|
||||
groundTruth.add (key, value);
|
||||
hashMap.set (key, value);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
template <typename KeyType>
|
||||
class RandomKeys
|
||||
{
|
||||
public:
|
||||
RandomKeys (int maxUniqueKeys, int seed) : r (seed)
|
||||
{
|
||||
for (int i = 0; i < maxUniqueKeys; ++i)
|
||||
keys.add (generateRandomKey (r));
|
||||
}
|
||||
|
||||
const KeyType& next()
|
||||
{
|
||||
int i = r.nextInt (keys.size() - 1);
|
||||
return keys.getReference (i);
|
||||
}
|
||||
private:
|
||||
static KeyType generateRandomKey (Random&);
|
||||
|
||||
Random r;
|
||||
Array<KeyType> keys;
|
||||
};
|
||||
};
|
||||
|
||||
template <> int HashMapTest::RandomKeys<int> ::generateRandomKey (Random& rnd) { return rnd.nextInt(); }
|
||||
template <> void* HashMapTest::RandomKeys<void*>::generateRandomKey (Random& rnd) { return reinterpret_cast<void*> (rnd.nextInt64()); }
|
||||
|
||||
template <> String HashMapTest::RandomKeys<String>::generateRandomKey (Random& rnd)
|
||||
{
|
||||
String str;
|
||||
|
||||
int len = rnd.nextInt (8)+1;
|
||||
for (int i = 0; i < len; ++i)
|
||||
str += static_cast<char> (rnd.nextInt (95) + 32);
|
||||
|
||||
return str;
|
||||
}
|
||||
|
||||
static HashMapTest hashMapTest;
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,382 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Helps to manipulate singly-linked lists of objects.
|
||||
|
||||
For objects that are designed to contain a pointer to the subsequent item in the
|
||||
list, this class contains methods to deal with the list. To use it, the ObjectType
|
||||
class that it points to must contain a LinkedListPointer called nextListItem, e.g.
|
||||
|
||||
@code
|
||||
struct MyObject
|
||||
{
|
||||
int x, y, z;
|
||||
|
||||
// A linkable object must contain a member with this name and type, which must be
|
||||
// accessible by the LinkedListPointer class. (This doesn't mean it has to be public -
|
||||
// you could make your class a friend of a LinkedListPointer<MyObject> instead).
|
||||
LinkedListPointer<MyObject> nextListItem;
|
||||
};
|
||||
|
||||
LinkedListPointer<MyObject> myList;
|
||||
myList.append (new MyObject());
|
||||
myList.append (new MyObject());
|
||||
|
||||
int numItems = myList.size(); // returns 2
|
||||
MyObject* lastInList = myList.getLast();
|
||||
@endcode
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class ObjectType>
|
||||
class LinkedListPointer
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates a null pointer to an empty list. */
|
||||
LinkedListPointer() noexcept
|
||||
: item (nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
/** Creates a pointer to a list whose head is the item provided. */
|
||||
explicit LinkedListPointer (ObjectType* const headItem) noexcept
|
||||
: item (headItem)
|
||||
{
|
||||
}
|
||||
|
||||
/** Sets this pointer to point to a new list. */
|
||||
LinkedListPointer& operator= (ObjectType* const newItem) noexcept
|
||||
{
|
||||
item = newItem;
|
||||
return *this;
|
||||
}
|
||||
|
||||
LinkedListPointer (LinkedListPointer&& other) noexcept
|
||||
: item (other.item)
|
||||
{
|
||||
other.item = nullptr;
|
||||
}
|
||||
|
||||
LinkedListPointer& operator= (LinkedListPointer&& other) noexcept
|
||||
{
|
||||
jassert (this != &other); // hopefully the compiler should make this situation impossible!
|
||||
|
||||
item = other.item;
|
||||
other.item = nullptr;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the item which this pointer points to. */
|
||||
inline operator ObjectType*() const noexcept
|
||||
{
|
||||
return item;
|
||||
}
|
||||
|
||||
/** Returns the item which this pointer points to. */
|
||||
inline ObjectType* get() const noexcept
|
||||
{
|
||||
return item;
|
||||
}
|
||||
|
||||
/** Returns the last item in the list which this pointer points to.
|
||||
This will iterate the list and return the last item found. Obviously the speed
|
||||
of this operation will be proportional to the size of the list. If the list is
|
||||
empty the return value will be this object.
|
||||
If you're planning on appending a number of items to your list, it's much more
|
||||
efficient to use the Appender class than to repeatedly call getLast() to find the end.
|
||||
*/
|
||||
LinkedListPointer& getLast() noexcept
|
||||
{
|
||||
auto* l = this;
|
||||
|
||||
while (l->item != nullptr)
|
||||
l = &(l->item->nextListItem);
|
||||
|
||||
return *l;
|
||||
}
|
||||
|
||||
/** Returns the number of items in the list.
|
||||
Obviously with a simple linked list, getting the size involves iterating the list, so
|
||||
this can be a lengthy operation - be careful when using this method in your code.
|
||||
*/
|
||||
int size() const noexcept
|
||||
{
|
||||
int total = 0;
|
||||
|
||||
for (auto* i = item; i != nullptr; i = i->nextListItem)
|
||||
++total;
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Returns the item at a given index in the list.
|
||||
Since the only way to find an item is to iterate the list, this operation can obviously
|
||||
be slow, depending on its size, so you should be careful when using this in algorithms.
|
||||
*/
|
||||
LinkedListPointer& operator[] (int index) noexcept
|
||||
{
|
||||
auto* l = this;
|
||||
|
||||
while (--index >= 0 && l->item != nullptr)
|
||||
l = &(l->item->nextListItem);
|
||||
|
||||
return *l;
|
||||
}
|
||||
|
||||
/** Returns the item at a given index in the list.
|
||||
Since the only way to find an item is to iterate the list, this operation can obviously
|
||||
be slow, depending on its size, so you should be careful when using this in algorithms.
|
||||
*/
|
||||
const LinkedListPointer& operator[] (int index) const noexcept
|
||||
{
|
||||
auto* l = this;
|
||||
|
||||
while (--index >= 0 && l->item != nullptr)
|
||||
l = &(l->item->nextListItem);
|
||||
|
||||
return *l;
|
||||
}
|
||||
|
||||
/** Returns true if the list contains the given item. */
|
||||
bool contains (const ObjectType* const itemToLookFor) const noexcept
|
||||
{
|
||||
for (auto* i = item; i != nullptr; i = i->nextListItem)
|
||||
if (itemToLookFor == i)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Inserts an item into the list, placing it before the item that this pointer
|
||||
currently points to.
|
||||
*/
|
||||
void insertNext (ObjectType* const newItem)
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6011)
|
||||
jassert (newItem != nullptr);
|
||||
jassert (newItem->nextListItem == nullptr);
|
||||
newItem->nextListItem = item;
|
||||
item = newItem;
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
}
|
||||
|
||||
/** Inserts an item at a numeric index in the list.
|
||||
Obviously this will involve iterating the list to find the item at the given index,
|
||||
so be careful about the impact this may have on execution time.
|
||||
*/
|
||||
void insertAtIndex (int index, ObjectType* newItem)
|
||||
{
|
||||
jassert (newItem != nullptr);
|
||||
auto* l = this;
|
||||
|
||||
while (index != 0 && l->item != nullptr)
|
||||
{
|
||||
l = &(l->item->nextListItem);
|
||||
--index;
|
||||
}
|
||||
|
||||
l->insertNext (newItem);
|
||||
}
|
||||
|
||||
/** Replaces the object that this pointer points to, appending the rest of the list to
|
||||
the new object, and returning the old one.
|
||||
*/
|
||||
ObjectType* replaceNext (ObjectType* const newItem) noexcept
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6011 28182)
|
||||
jassert (newItem != nullptr);
|
||||
jassert (newItem->nextListItem == nullptr);
|
||||
|
||||
auto oldItem = item;
|
||||
item = newItem;
|
||||
item->nextListItem = oldItem->nextListItem.item;
|
||||
oldItem->nextListItem.item = nullptr;
|
||||
return oldItem;
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
}
|
||||
|
||||
/** Adds an item to the end of the list.
|
||||
|
||||
This operation involves iterating the whole list, so can be slow - if you need to
|
||||
append a number of items to your list, it's much more efficient to use the Appender
|
||||
class than to repeatedly call append().
|
||||
*/
|
||||
void append (ObjectType* const newItem)
|
||||
{
|
||||
getLast().item = newItem;
|
||||
}
|
||||
|
||||
/** Creates copies of all the items in another list and adds them to this one.
|
||||
This will use the ObjectType's copy constructor to try to create copies of each
|
||||
item in the other list, and appends them to this list.
|
||||
*/
|
||||
void addCopyOfList (const LinkedListPointer& other)
|
||||
{
|
||||
auto* insertPoint = this;
|
||||
|
||||
for (auto* i = other.item; i != nullptr; i = i->nextListItem)
|
||||
{
|
||||
insertPoint->insertNext (new ObjectType (*i));
|
||||
insertPoint = &(insertPoint->item->nextListItem);
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes the head item from the list.
|
||||
This won't delete the object that is removed, but returns it, so the caller can
|
||||
delete it if necessary.
|
||||
*/
|
||||
ObjectType* removeNext() noexcept
|
||||
{
|
||||
auto oldItem = item;
|
||||
|
||||
if (oldItem != nullptr)
|
||||
{
|
||||
item = oldItem->nextListItem;
|
||||
oldItem->nextListItem.item = nullptr;
|
||||
}
|
||||
|
||||
return oldItem;
|
||||
}
|
||||
|
||||
/** Removes a specific item from the list.
|
||||
Note that this will not delete the item, it simply unlinks it from the list.
|
||||
*/
|
||||
void remove (ObjectType* const itemToRemove)
|
||||
{
|
||||
if (auto* l = findPointerTo (itemToRemove))
|
||||
l->removeNext();
|
||||
}
|
||||
|
||||
/** Iterates the list, calling the delete operator on all of its elements and
|
||||
leaving this pointer empty.
|
||||
*/
|
||||
void deleteAll()
|
||||
{
|
||||
while (item != nullptr)
|
||||
{
|
||||
auto oldItem = item;
|
||||
item = oldItem->nextListItem;
|
||||
delete oldItem;
|
||||
}
|
||||
}
|
||||
|
||||
/** Finds a pointer to a given item.
|
||||
If the item is found in the list, this returns the pointer that points to it. If
|
||||
the item isn't found, this returns null.
|
||||
*/
|
||||
LinkedListPointer* findPointerTo (ObjectType* const itemToLookFor) noexcept
|
||||
{
|
||||
auto* l = this;
|
||||
|
||||
while (l->item != nullptr)
|
||||
{
|
||||
if (l->item == itemToLookFor)
|
||||
return l;
|
||||
|
||||
l = &(l->item->nextListItem);
|
||||
}
|
||||
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
/** Copies the items in the list to an array.
|
||||
The destArray must contain enough elements to hold the entire list - no checks are
|
||||
made for this!
|
||||
*/
|
||||
void copyToArray (ObjectType** destArray) const noexcept
|
||||
{
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6011)
|
||||
jassert (destArray != nullptr);
|
||||
|
||||
for (auto* i = item; i != nullptr; i = i->nextListItem)
|
||||
*destArray++ = i;
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
}
|
||||
|
||||
/** Swaps this pointer with another one */
|
||||
void swapWith (LinkedListPointer& other) noexcept
|
||||
{
|
||||
std::swap (item, other.item);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Allows efficient repeated insertions into a list.
|
||||
|
||||
You can create an Appender object which points to the last element in your
|
||||
list, and then repeatedly call Appender::append() to add items to the end
|
||||
of the list in O(1) time.
|
||||
*/
|
||||
class Appender
|
||||
{
|
||||
public:
|
||||
/** Creates an appender which will add items to the given list.
|
||||
*/
|
||||
Appender (LinkedListPointer& endOfListPointer) noexcept
|
||||
: endOfList (&endOfListPointer)
|
||||
{
|
||||
// This can only be used to add to the end of a list.
|
||||
jassert (endOfListPointer.item == nullptr);
|
||||
}
|
||||
|
||||
/** Appends an item to the list. */
|
||||
void append (ObjectType* const newItem) noexcept
|
||||
{
|
||||
*endOfList = newItem;
|
||||
endOfList = &(newItem->nextListItem);
|
||||
}
|
||||
|
||||
private:
|
||||
LinkedListPointer* endOfList;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (Appender)
|
||||
};
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
ObjectType* item;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (LinkedListPointer)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,721 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Holds a set of objects and can invoke a member function callback on each object in the set with
|
||||
a single call.
|
||||
|
||||
It is safe to add listeners, remove listeners, clear the listeners, and even delete the
|
||||
ListenerList itself during any listener callback. If you don't need these extra guarantees
|
||||
consider using a LightweightListenerList instead.
|
||||
|
||||
If a Listener is added during a callback, it is guaranteed not to be called in the same
|
||||
iteration.
|
||||
|
||||
If a Listener is removed during a callback, it is guaranteed not to be called if it hasn't
|
||||
already been called.
|
||||
|
||||
If the ListenerList is cleared or deleted during a callback, it is guaranteed that no more
|
||||
listeners will be called.
|
||||
|
||||
It is NOT safe to make concurrent calls to the listeners without a mutex. If you need this
|
||||
functionality, either use a LightweightListenerList or a ThreadSafeListenerList.
|
||||
|
||||
When calling listeners the iteration can be escaped early by using a "BailOutChecker".
|
||||
A BailOutChecker is a type that has a public member function with the following signature:
|
||||
@code bool shouldBailOut() const @endcode
|
||||
This function will be called before making a call to each listener.
|
||||
For an example see the DummyBailOutChecker.
|
||||
|
||||
@see LightweightListenerList, ThreadSafeListenerList
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename ListenerClass,
|
||||
typename ArrayType = Array<ListenerClass*>>
|
||||
class ListenerList
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty list. */
|
||||
ListenerList() = default;
|
||||
|
||||
/** Destructor. */
|
||||
~ListenerList() { clear(); }
|
||||
|
||||
//==============================================================================
|
||||
/** Adds a listener to the list.
|
||||
A listener can only be added once, so if the listener is already in the list, this method
|
||||
has no effect.
|
||||
|
||||
If a Listener is added during a callback, it is guaranteed not to be called in the same
|
||||
iteration.
|
||||
|
||||
@see remove
|
||||
*/
|
||||
void add (ListenerClass* listenerToAdd)
|
||||
{
|
||||
initialiseIfNeeded();
|
||||
|
||||
if (listenerToAdd != nullptr)
|
||||
data->listeners.addIfNotAlreadyThere (listenerToAdd);
|
||||
else
|
||||
jassertfalse; // Listeners can't be null pointers!
|
||||
}
|
||||
|
||||
/** Adds a listener to the list.
|
||||
A listener can only be added once, so if the listener is already in the list, this method
|
||||
has no effect.
|
||||
|
||||
If a Listener is added during a callback, it is guaranteed not to be called in the same
|
||||
iteration.
|
||||
|
||||
@see remove
|
||||
*/
|
||||
void add (ListenerClass& listenerToAdd) { add (&listenerToAdd); }
|
||||
void add (ListenerClass&&) = delete;
|
||||
|
||||
/** Removes a listener from the list.
|
||||
If the listener wasn't in the list, this has no effect.
|
||||
|
||||
If a Listener is removed during a callback, it is guaranteed not to be called if it hasn't
|
||||
already been called.
|
||||
*/
|
||||
void remove (ListenerClass* listenerToRemove)
|
||||
{
|
||||
jassert (listenerToRemove != nullptr); // Listeners can't be null pointers!
|
||||
|
||||
if (! initialised())
|
||||
return;
|
||||
|
||||
const ScopedLockType lock (data->listeners.getLock());
|
||||
|
||||
if (const auto index = data->listeners.removeFirstMatchingValue (listenerToRemove); index >= 0)
|
||||
{
|
||||
for (auto* it : data->iterators)
|
||||
{
|
||||
if (index < it->end)
|
||||
--it->end;
|
||||
|
||||
if (index <= it->index)
|
||||
--it->index;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes a listener from the list.
|
||||
If the listener wasn't in the list, this has no effect.
|
||||
|
||||
If a Listener is removed during a callback, it is guaranteed not to be called if it hasn't
|
||||
already been called.
|
||||
*/
|
||||
void remove (ListenerClass& listenerToRemove) { remove (&listenerToRemove); }
|
||||
void remove (ListenerClass&&) = delete;
|
||||
|
||||
/** Adds a listener that will be automatically removed again when the Guard is destroyed.
|
||||
|
||||
Be very careful to ensure that the ErasedScopeGuard is destroyed or released before the
|
||||
ListenerList is destroyed, otherwise the ErasedScopeGuard may attempt to dereference a
|
||||
dangling pointer when it is destroyed, which will result in a crash.
|
||||
*/
|
||||
[[nodiscard]] ErasedScopeGuard addScoped (ListenerClass& listenerToAdd)
|
||||
{
|
||||
add (&listenerToAdd);
|
||||
return ErasedScopeGuard { [this, &listenerToAdd] { remove (&listenerToAdd); } };
|
||||
}
|
||||
|
||||
ErasedScopeGuard addScoped (ListenerClass&&) = delete;
|
||||
|
||||
/** Returns the number of registered listeners. */
|
||||
[[nodiscard]] int size() const noexcept { return ! initialised() ? 0 : data->listeners.size(); }
|
||||
|
||||
/** Returns true if no listeners are registered, false otherwise. */
|
||||
[[nodiscard]] bool isEmpty() const noexcept { return ! initialised() || data->listeners.isEmpty(); }
|
||||
|
||||
/** Clears the list.
|
||||
|
||||
If the ListenerList is cleared during a callback, it is guaranteed that no more
|
||||
listeners will be called.
|
||||
*/
|
||||
void clear()
|
||||
{
|
||||
if (! initialised())
|
||||
return;
|
||||
|
||||
const ScopedLockType lock { data->listeners.getLock() };
|
||||
|
||||
data->listeners.clear();
|
||||
|
||||
for (auto* it : data->iterators)
|
||||
it->end = 0;
|
||||
}
|
||||
|
||||
/** Returns true if the specified listener has been added to the list. */
|
||||
[[nodiscard]] bool contains (ListenerClass* listener) const noexcept
|
||||
{
|
||||
return initialised()
|
||||
&& data->listeners.contains (listener);
|
||||
}
|
||||
|
||||
/** Returns the raw array of listeners.
|
||||
|
||||
Any attempt to mutate the array may result in undefined behaviour.
|
||||
|
||||
If the array uses a mutex/CriticalSection, reading from the array without first obtaining
|
||||
the lock may potentially result in undefined behaviour.
|
||||
|
||||
@see add, remove, clear, contains
|
||||
*/
|
||||
[[nodiscard]] const ArrayType& getListeners() const noexcept
|
||||
{
|
||||
const_cast<ListenerList*> (this)->initialiseIfNeeded();
|
||||
return data->listeners;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Calls an invokable object for each listener in the list. */
|
||||
template <typename Callback>
|
||||
void call (Callback&& callback)
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
DummyBailOutChecker{},
|
||||
std::forward<Callback> (callback));
|
||||
}
|
||||
|
||||
/** Calls an invokable object for each listener in the list, except for the listener specified
|
||||
by listenerToExclude.
|
||||
*/
|
||||
template <typename Callback>
|
||||
void callExcluding (ListenerClass* listenerToExclude, Callback&& callback)
|
||||
{
|
||||
callCheckedExcluding (listenerToExclude,
|
||||
DummyBailOutChecker{},
|
||||
std::forward<Callback> (callback));
|
||||
|
||||
}
|
||||
|
||||
/** Calls an invokable object for each listener in the list, additionally checking the bail-out
|
||||
checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename Callback, typename BailOutCheckerType>
|
||||
void callChecked (const BailOutCheckerType& bailOutChecker, Callback&& callback)
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
bailOutChecker,
|
||||
std::forward<Callback> (callback));
|
||||
}
|
||||
|
||||
/** Calls an invokable object for each listener in the list, except for the listener specified
|
||||
by listenerToExclude, additionally checking the bail-out checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename Callback, typename BailOutCheckerType>
|
||||
void callCheckedExcluding (ListenerClass* listenerToExclude,
|
||||
const BailOutCheckerType& bailOutChecker,
|
||||
Callback&& callback)
|
||||
{
|
||||
if (! initialised())
|
||||
return;
|
||||
|
||||
callCheckedExcluding (data,
|
||||
listenerToExclude,
|
||||
bailOutChecker,
|
||||
std::forward<Callback> (callback));
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Calls a specific listener method for each listener in the list. */
|
||||
template <typename... MethodArgs, typename... Args>
|
||||
void call (void (ListenerClass::*callbackFunction) (MethodArgs...), Args&&... args)
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
DummyBailOutChecker{},
|
||||
callbackFunction,
|
||||
std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
/** Calls a specific listener method for each listener in the list, except for the listener
|
||||
specified by listenerToExclude.
|
||||
*/
|
||||
template <typename... MethodArgs, typename... Args>
|
||||
void callExcluding (ListenerClass* listenerToExclude,
|
||||
void (ListenerClass::*callbackFunction) (MethodArgs...),
|
||||
Args&&... args)
|
||||
{
|
||||
callCheckedExcluding (listenerToExclude,
|
||||
DummyBailOutChecker{},
|
||||
callbackFunction,
|
||||
std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
/** Calls a specific listener method for each listener in the list,
|
||||
additionally checking the bail-out checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename BailOutCheckerType, typename... MethodArgs, typename... Args>
|
||||
void callChecked (const BailOutCheckerType& bailOutChecker,
|
||||
void (ListenerClass::*callbackFunction) (MethodArgs...),
|
||||
Args&&... args)
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
bailOutChecker,
|
||||
callbackFunction,
|
||||
std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
/** Calls a specific listener method for each listener in the list, except
|
||||
for the listener specified by listenerToExclude, additionally checking
|
||||
the bail-out checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename BailOutCheckerType, typename... MethodArgs, typename... Args>
|
||||
void callCheckedExcluding (ListenerClass* listenerToExclude,
|
||||
const BailOutCheckerType& bailOutChecker,
|
||||
void (ListenerClass::*callbackFunction) (MethodArgs...),
|
||||
Args&&... args)
|
||||
{
|
||||
callCheckedExcluding (listenerToExclude, bailOutChecker, [&] (ListenerClass& l)
|
||||
{
|
||||
(l.*callbackFunction) (args...);
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** A dummy bail-out checker that always returns false.
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
struct DummyBailOutChecker
|
||||
{
|
||||
constexpr bool shouldBailOut() const noexcept { return false; }
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
using ThisType = ListenerList<ListenerClass, ArrayType>;
|
||||
using ListenerType = ListenerClass;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
using ScopedLockType = typename ArrayType::ScopedLockType;
|
||||
|
||||
inline bool initialised() const noexcept { return state == State::initialised; }
|
||||
|
||||
inline void initialiseIfNeeded() noexcept
|
||||
{
|
||||
if (initialised())
|
||||
return;
|
||||
|
||||
auto expected = State::uninitialised;
|
||||
|
||||
if (state.compare_exchange_strong (expected, State::initialising))
|
||||
{
|
||||
static_assert (std::is_nothrow_constructible_v<ArrayType>,
|
||||
"Any ListenerList ArrayType must have a noexcept default constructor");
|
||||
|
||||
static_assert (std::is_nothrow_constructible_v<SafeIterators>,
|
||||
"Please notify the JUCE team if you encounter this assertion");
|
||||
|
||||
data = std::make_shared<Data>();
|
||||
state = State::initialised;
|
||||
return;
|
||||
}
|
||||
|
||||
while (! initialised())
|
||||
std::this_thread::yield();
|
||||
}
|
||||
|
||||
struct Iterator
|
||||
{
|
||||
int index{};
|
||||
int end{};
|
||||
};
|
||||
|
||||
using SafeIterators = std::vector<Iterator*>;
|
||||
|
||||
enum class State
|
||||
{
|
||||
uninitialised,
|
||||
initialising,
|
||||
initialised
|
||||
};
|
||||
|
||||
struct Data
|
||||
{
|
||||
ArrayType listeners;
|
||||
SafeIterators iterators;
|
||||
|
||||
#if JUCE_ASSERTIONS_ENABLED_OR_LOGGED
|
||||
CriticalSection callCheckedExcludingMutex;
|
||||
#endif
|
||||
};
|
||||
|
||||
std::shared_ptr<Data> data{};
|
||||
std::atomic<State> state { State::uninitialised };
|
||||
|
||||
template <typename Callback, typename BailOutCheckerType>
|
||||
static void callCheckedExcluding (std::shared_ptr<Data> d,
|
||||
ListenerClass* listenerToExclude,
|
||||
const BailOutCheckerType& bailOutChecker,
|
||||
Callback&& callback)
|
||||
{
|
||||
const ScopedLockType lock { d->listeners.getLock() };
|
||||
|
||||
#if JUCE_ASSERTIONS_ENABLED_OR_LOGGED
|
||||
{
|
||||
// Keep a reference to the mutex to protect against the case where this list gets deleted
|
||||
// during a callback.
|
||||
const ScopedTryLock callCheckedExcludingLock (d->callCheckedExcludingMutex);
|
||||
|
||||
// If you hit this assertion it means you're trying to call the listeners from multiple
|
||||
// threads concurrently. If you need to do this either use a LightweightListenerList, for a
|
||||
// lock free option, or a ThreadSafeListenerList if you also need the extra guarantees
|
||||
// provided by ListenerList. See the class descriptions for more details.
|
||||
jassert (callCheckedExcludingLock.isLocked());
|
||||
}
|
||||
#endif
|
||||
|
||||
Iterator it{};
|
||||
it.end = d->listeners.size();
|
||||
|
||||
d->iterators.push_back (&it);
|
||||
|
||||
const ScopeGuard scope { [i = &d->iterators, &it]
|
||||
{
|
||||
i->erase (std::remove (i->begin(), i->end(), &it), i->end());
|
||||
} };
|
||||
|
||||
for (; it.index < it.end; ++it.index)
|
||||
{
|
||||
if (bailOutChecker.shouldBailOut())
|
||||
return;
|
||||
|
||||
auto* listener = d->listeners.getUnchecked (it.index);
|
||||
|
||||
if (listener == listenerToExclude)
|
||||
continue;
|
||||
|
||||
callback (*listener);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE (ListenerList)
|
||||
JUCE_DECLARE_NON_MOVEABLE (ListenerList)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A thread safe version of the ListenerList class.
|
||||
|
||||
@see ListenerList, LightweightListenerList
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename ListenerClass>
|
||||
using ThreadSafeListenerList = ListenerList<ListenerClass, Array<ListenerClass*, CriticalSection>>;
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A lightweight version of the ListenerList that doesn't provide any guarantees when mutating the
|
||||
list from a callback, but allows callbacks to be triggered concurrently without a mutex.
|
||||
|
||||
@see ListenerList, ThreadSafeListenerList
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename ListenerClass>
|
||||
class LightweightListenerList
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty list. */
|
||||
LightweightListenerList() = default;
|
||||
|
||||
/** Destructor. */
|
||||
~LightweightListenerList()
|
||||
{
|
||||
// If you hit this jassert it means you're trying to delete the list while iterating through
|
||||
// the listeners! If you need to handle this situation gracefully use a ListenerList or
|
||||
// ThreadSafeListenerList.
|
||||
jassert (numCallsInProgress == 0);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Adds a listener to the list.
|
||||
A listener can only be added once, so if the listener is already in the list, this method
|
||||
has no effect.
|
||||
|
||||
If you need to add a Listener during a callback, use the ListenerList type.
|
||||
|
||||
@see remove
|
||||
*/
|
||||
void add (ListenerClass* listenerToAdd)
|
||||
{
|
||||
// If you hit this jassert it means you're trying to add a listener while iterating through
|
||||
// the listeners! If you need to handle this situation gracefully use a ListenerList or
|
||||
// ThreadSafeListenerList.
|
||||
jassert (numCallsInProgress == 0);
|
||||
|
||||
if (listenerToAdd != nullptr)
|
||||
listeners.addIfNotAlreadyThere (listenerToAdd);
|
||||
else
|
||||
jassertfalse; // Listeners can't be null pointers!
|
||||
}
|
||||
|
||||
/** Adds a listener to the list.
|
||||
A listener can only be added once, so if the listener is already in the list, this method
|
||||
has no effect.
|
||||
|
||||
If you need to add a Listener during a callback, use the ListenerList type.
|
||||
|
||||
@see remove
|
||||
*/
|
||||
void add (ListenerClass& listenerToAdd) { add (&listenerToAdd); }
|
||||
void add (ListenerClass&&) = delete;
|
||||
|
||||
/** Removes a listener from the list.
|
||||
If the listener wasn't in the list, this has no effect.
|
||||
|
||||
If you need to remove a Listener during a callback, use the ListenerList type.
|
||||
*/
|
||||
void remove (ListenerClass* listenerToRemove)
|
||||
{
|
||||
// If you hit this jassert it means you're trying to remove a listener while iterating
|
||||
// through the listeners! If you need to handle this situation gracefully use a ListenerList
|
||||
// or ThreadSafeListenerList.
|
||||
jassert (numCallsInProgress == 0);
|
||||
|
||||
jassert (listenerToRemove != nullptr); // Listeners can't be null pointers!
|
||||
|
||||
listeners.removeFirstMatchingValue (listenerToRemove);
|
||||
}
|
||||
|
||||
/** Removes a listener from the list.
|
||||
If the listener wasn't in the list, this has no effect.
|
||||
|
||||
If you need to remove a Listener during a callback, use the ListenerList type.
|
||||
*/
|
||||
void remove (ListenerClass& listenerToRemove) { remove (&listenerToRemove); }
|
||||
void remove (ListenerClass&&) = delete;
|
||||
|
||||
/** Adds a listener that will be automatically removed when the Guard is destroyed.
|
||||
|
||||
Be very careful to ensure that the ErasedScopeGuard is destroyed or released before the
|
||||
ListenerList is destroyed, otherwise the ErasedScopeGuard may attempt to dereference a
|
||||
dangling pointer when it is destroyed, which will result in a crash.
|
||||
*/
|
||||
[[nodiscard]] ErasedScopeGuard addScoped (ListenerClass& listenerToAdd)
|
||||
{
|
||||
add (&listenerToAdd);
|
||||
return ErasedScopeGuard { [this, &listenerToAdd] { remove (&listenerToAdd); } };
|
||||
}
|
||||
|
||||
ErasedScopeGuard addScoped (ListenerClass&&) = delete;
|
||||
|
||||
/** Returns the number of registered listeners. */
|
||||
[[nodiscard]] int size() const noexcept { return listeners.size(); }
|
||||
|
||||
/** Returns true if no listeners are registered, false otherwise. */
|
||||
[[nodiscard]] bool isEmpty() const noexcept { return listeners.isEmpty(); }
|
||||
|
||||
/** Clears the list.
|
||||
|
||||
If you need to clear the list during a callback, use the ListenerList type.
|
||||
*/
|
||||
void clear()
|
||||
{
|
||||
// If you hit this jassert it means you're trying to clear the listener list while iterating
|
||||
// through the listeners! If you need to handle this situation gracefully use a ListenerList
|
||||
// or ThreadSafeListenerList.
|
||||
jassert (numCallsInProgress == 0);
|
||||
|
||||
listeners.clear();
|
||||
}
|
||||
|
||||
/** Returns true if the specified listener has been added to the list. */
|
||||
[[nodiscard]] bool contains (ListenerClass* listener) const noexcept
|
||||
{
|
||||
return listeners.contains (listener);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Calls an invokable object for each listener in the list. */
|
||||
template <typename Callback>
|
||||
void call (Callback&& callback) const
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
DummyBailOutChecker{},
|
||||
std::forward<Callback> (callback));
|
||||
}
|
||||
|
||||
/** Calls an invokable object for each listener in the list, except for the listener specified
|
||||
by listenerToExclude.
|
||||
*/
|
||||
template <typename Callback>
|
||||
void callExcluding (ListenerClass* listenerToExclude, Callback&& callback) const
|
||||
{
|
||||
callCheckedExcluding (listenerToExclude,
|
||||
DummyBailOutChecker{},
|
||||
std::forward<Callback> (callback));
|
||||
|
||||
}
|
||||
|
||||
/** Calls an invokable object for each listener in the list, additionally checking the bail-out
|
||||
checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename Callback, typename BailOutCheckerType>
|
||||
void callChecked (const BailOutCheckerType& bailOutChecker, Callback&& callback) const
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
bailOutChecker,
|
||||
std::forward<Callback> (callback));
|
||||
}
|
||||
|
||||
/** Calls an invokable object for each listener in the list, except for the listener specified
|
||||
by listenerToExclude, additionally checking the bail-out checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename Callback, typename BailOutCheckerType>
|
||||
void callCheckedExcluding (ListenerClass* listenerToExclude,
|
||||
const BailOutCheckerType& bailOutChecker,
|
||||
Callback&& callback) const
|
||||
{
|
||||
#if JUCE_ASSERTIONS_ENABLED_OR_LOGGED
|
||||
++numCallsInProgress;
|
||||
const ScopeGuard decrementPerformingCallbackCount { [&] { --numCallsInProgress; }};
|
||||
#endif
|
||||
|
||||
for (auto* listener : listeners)
|
||||
{
|
||||
if (bailOutChecker.shouldBailOut())
|
||||
return;
|
||||
|
||||
if (listener == listenerToExclude)
|
||||
continue;
|
||||
|
||||
callback (*listener);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Calls a specific listener method for each listener in the list. */
|
||||
template <typename... MethodArgs, typename... Args>
|
||||
void call (void (ListenerClass::*callbackFunction) (MethodArgs...), Args&&... args) const
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
DummyBailOutChecker{},
|
||||
callbackFunction,
|
||||
std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
/** Calls a specific listener method for each listener in the list, except for the listener
|
||||
specified by listenerToExclude.
|
||||
*/
|
||||
template <typename... MethodArgs, typename... Args>
|
||||
void callExcluding (ListenerClass* listenerToExclude,
|
||||
void (ListenerClass::*callbackFunction) (MethodArgs...),
|
||||
Args&&... args) const
|
||||
{
|
||||
callCheckedExcluding (listenerToExclude,
|
||||
DummyBailOutChecker{},
|
||||
callbackFunction,
|
||||
std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
/** Calls a specific listener method for each listener in the list, additionally checking the
|
||||
bail-out checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename BailOutCheckerType, typename... MethodArgs, typename... Args>
|
||||
void callChecked (const BailOutCheckerType& bailOutChecker,
|
||||
void (ListenerClass::*callbackFunction) (MethodArgs...),
|
||||
Args&&... args) const
|
||||
{
|
||||
callCheckedExcluding (nullptr,
|
||||
bailOutChecker,
|
||||
callbackFunction,
|
||||
std::forward<Args> (args)...);
|
||||
}
|
||||
|
||||
/** Calls a specific listener method for each listener in the list, except for the listener
|
||||
specified by listenerToExclude, additionally checking the bail-out checker before each call.
|
||||
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
template <typename BailOutCheckerType, typename... MethodArgs, typename... Args>
|
||||
void callCheckedExcluding (ListenerClass* listenerToExclude,
|
||||
const BailOutCheckerType& bailOutChecker,
|
||||
void (ListenerClass::*callbackFunction) (MethodArgs...),
|
||||
Args&&... args) const
|
||||
{
|
||||
callCheckedExcluding (listenerToExclude, bailOutChecker, [&] (ListenerClass& l)
|
||||
{
|
||||
(l.*callbackFunction) (args...);
|
||||
});
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** A dummy bail-out checker that always returns false.
|
||||
See the class description for info about writing a bail-out checker.
|
||||
*/
|
||||
using DummyBailOutChecker = typename ListenerList<ListenerClass>::DummyBailOutChecker;
|
||||
|
||||
//==============================================================================
|
||||
using ThisType = LightweightListenerList<ListenerClass>;
|
||||
using ListenerType = ListenerClass;
|
||||
|
||||
private:
|
||||
#if JUCE_ASSERTIONS_ENABLED_OR_LOGGED
|
||||
mutable std::atomic<int> numCallsInProgress { 0 };
|
||||
#endif
|
||||
|
||||
Array<ListenerClass*> listeners;
|
||||
|
||||
//==============================================================================
|
||||
JUCE_DECLARE_NON_COPYABLE (LightweightListenerList)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,793 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
class ListenerListTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
class TestListener
|
||||
{
|
||||
public:
|
||||
explicit TestListener (std::function<void()> cb) : callback (std::move (cb)) {}
|
||||
|
||||
void doCallback()
|
||||
{
|
||||
++numCalls;
|
||||
callback();
|
||||
}
|
||||
|
||||
int getNumCalls() const { return numCalls; }
|
||||
|
||||
private:
|
||||
int numCalls = 0;
|
||||
std::function<void()> callback;
|
||||
};
|
||||
|
||||
class TestObject
|
||||
{
|
||||
public:
|
||||
void addListener (std::function<void()> cb)
|
||||
{
|
||||
listeners.push_back (std::make_unique<TestListener> (std::move (cb)));
|
||||
listenerList.add (listeners.back().get());
|
||||
}
|
||||
|
||||
void removeListener (int i) { listenerList.remove (listeners[(size_t) i].get()); }
|
||||
|
||||
void callListeners()
|
||||
{
|
||||
++callLevel;
|
||||
listenerList.call ([] (auto& l) { l.doCallback(); });
|
||||
--callLevel;
|
||||
}
|
||||
|
||||
int getNumListeners() const { return (int) listeners.size(); }
|
||||
|
||||
auto& getListener (int i) { return *listeners[(size_t) i]; }
|
||||
|
||||
int getCallLevel() const
|
||||
{
|
||||
return callLevel;
|
||||
}
|
||||
|
||||
bool wereAllNonRemovedListenersCalled (int numCalls) const
|
||||
{
|
||||
return std::all_of (std::begin (listeners),
|
||||
std::end (listeners),
|
||||
[&] (auto& listener)
|
||||
{
|
||||
return (! listenerList.contains (listener.get())) || listener->getNumCalls() == numCalls;
|
||||
});
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::unique_ptr<TestListener>> listeners;
|
||||
ListenerList<TestListener> listenerList;
|
||||
int callLevel = 0;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
ListenerListTests() : UnitTest ("ListenerList", UnitTestCategories::containers) {}
|
||||
|
||||
void runTest() final
|
||||
{
|
||||
// This is a test that the pre-iterator adjustment implementation should pass too
|
||||
beginTest ("All non-removed listeners should be called - removing an already called listener");
|
||||
{
|
||||
TestObject test;
|
||||
|
||||
for (int i = 0; i < 20; ++i)
|
||||
{
|
||||
test.addListener ([i, &test]
|
||||
{
|
||||
if (i == 5)
|
||||
test.removeListener (6);
|
||||
});
|
||||
}
|
||||
|
||||
test.callListeners();
|
||||
expect (test.wereAllNonRemovedListenersCalled (1));
|
||||
}
|
||||
|
||||
// Iterator adjustment is necessary for passing this
|
||||
beginTest ("All non-removed listeners should be called - removing a yet uncalled listener");
|
||||
{
|
||||
TestObject test;
|
||||
|
||||
for (int i = 0; i < 20; ++i)
|
||||
{
|
||||
test.addListener ([i, &test]
|
||||
{
|
||||
if (i == 5)
|
||||
test.removeListener (4);
|
||||
});
|
||||
}
|
||||
|
||||
test.callListeners();
|
||||
expect (test.wereAllNonRemovedListenersCalled (1));
|
||||
}
|
||||
|
||||
// This test case demonstrates why we have to call --it.index instead of it.next()
|
||||
beginTest ("All non-removed listeners should be called - one callback removes multiple listeners");
|
||||
{
|
||||
TestObject test;
|
||||
|
||||
for (int i = 0; i < 20; ++i)
|
||||
{
|
||||
test.addListener ([i, &test]
|
||||
{
|
||||
if (i == 19)
|
||||
{
|
||||
test.removeListener (19);
|
||||
test.removeListener (0);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test.callListeners();
|
||||
expect (test.wereAllNonRemovedListenersCalled (1));
|
||||
}
|
||||
|
||||
beginTest ("All non-removed listeners should be called - removing listeners randomly");
|
||||
{
|
||||
auto random = getRandom();
|
||||
|
||||
for (auto run = 0; run < 10; ++run)
|
||||
{
|
||||
const auto numListeners = random.nextInt ({ 10, 100 });
|
||||
const auto listenersThatRemoveListeners = chooseUnique (random,
|
||||
numListeners,
|
||||
random.nextInt ({ 0, numListeners / 2 }));
|
||||
|
||||
// The listener in position [key] should remove listeners in [value]
|
||||
std::map<int, std::set<int>> removals;
|
||||
|
||||
for (auto i : listenersThatRemoveListeners)
|
||||
{
|
||||
// Random::nextInt ({1, 1}); triggers an assertion
|
||||
removals[i] = chooseUnique (random,
|
||||
numListeners,
|
||||
random.nextInt ({ 1, std::max (2, numListeners / 10) }));
|
||||
}
|
||||
|
||||
TestObject test;
|
||||
|
||||
for (int i = 0; i < numListeners; ++i)
|
||||
{
|
||||
test.addListener ([i, &removals, &test]
|
||||
{
|
||||
const auto iter = removals.find (i);
|
||||
|
||||
if (iter == removals.end())
|
||||
return;
|
||||
|
||||
for (auto j : iter->second)
|
||||
{
|
||||
test.removeListener (j);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test.callListeners();
|
||||
expect (test.wereAllNonRemovedListenersCalled (1));
|
||||
}
|
||||
}
|
||||
|
||||
// Iterator adjustment is not necessary for passing this
|
||||
beginTest ("All non-removed listeners should be called - add listener during iteration");
|
||||
{
|
||||
TestObject test;
|
||||
const auto numStartingListeners = 20;
|
||||
|
||||
for (int i = 0; i < numStartingListeners; ++i)
|
||||
{
|
||||
test.addListener ([i, &test]
|
||||
{
|
||||
if (i == 5 || i == 6)
|
||||
test.addListener ([] {});
|
||||
});
|
||||
}
|
||||
|
||||
test.callListeners();
|
||||
|
||||
// Only the Listeners added before the test can be expected to have been called
|
||||
bool success = true;
|
||||
|
||||
for (int i = 0; i < numStartingListeners; ++i)
|
||||
success = success && test.getListener (i).getNumCalls() == 1;
|
||||
|
||||
// Listeners added during the iteration must not be called in that iteration
|
||||
for (int i = numStartingListeners; i < test.getNumListeners(); ++i)
|
||||
success = success && test.getListener (i).getNumCalls() == 0;
|
||||
|
||||
expect (success);
|
||||
}
|
||||
|
||||
beginTest ("All non-removed listeners should be called - nested ListenerList::call()");
|
||||
{
|
||||
TestObject test;
|
||||
|
||||
for (int i = 0; i < 20; ++i)
|
||||
{
|
||||
test.addListener ([i, &test]
|
||||
{
|
||||
const auto callLevel = test.getCallLevel();
|
||||
|
||||
if (i == 6 && callLevel == 1)
|
||||
{
|
||||
test.callListeners();
|
||||
}
|
||||
|
||||
if (i == 5)
|
||||
{
|
||||
if (callLevel == 1)
|
||||
test.removeListener (4);
|
||||
else if (callLevel == 2)
|
||||
test.removeListener (6);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
test.callListeners();
|
||||
expect (test.wereAllNonRemovedListenersCalled (2));
|
||||
}
|
||||
|
||||
beginTest ("All non-removed listeners should be called - random ListenerList::call()");
|
||||
{
|
||||
const auto numListeners = 20;
|
||||
auto random = getRandom();
|
||||
|
||||
for (int run = 0; run < 10; ++run)
|
||||
{
|
||||
TestObject test;
|
||||
auto numCalls = 0;
|
||||
|
||||
auto listenersToRemove = chooseUnique (random, numListeners, numListeners / 2);
|
||||
|
||||
for (int i = 0; i < numListeners; ++i)
|
||||
{
|
||||
// Capturing numListeners is a warning on MacOS, not capturing it is an error on Windows
|
||||
test.addListener ([&]
|
||||
{
|
||||
const auto callLevel = test.getCallLevel();
|
||||
|
||||
if (callLevel < 4 && random.nextFloat() < 0.05f)
|
||||
{
|
||||
++numCalls;
|
||||
test.callListeners();
|
||||
}
|
||||
|
||||
if (random.nextFloat() < 0.5f)
|
||||
{
|
||||
const auto listenerToRemove = random.nextInt ({ 0, numListeners });
|
||||
|
||||
if (listenersToRemove.erase (listenerToRemove) > 0)
|
||||
test.removeListener (listenerToRemove);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
while (listenersToRemove.size() > 0)
|
||||
{
|
||||
test.callListeners();
|
||||
++numCalls;
|
||||
}
|
||||
|
||||
expect (test.wereAllNonRemovedListenersCalled (numCalls));
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Deleting the listener list from a callback");
|
||||
{
|
||||
struct Listener
|
||||
{
|
||||
std::function<void()> onCallback;
|
||||
void notify() { onCallback(); }
|
||||
};
|
||||
|
||||
auto listeners = std::make_unique<juce::ListenerList<Listener>>();
|
||||
|
||||
const auto callback = [&]
|
||||
{
|
||||
expect (listeners != nullptr);
|
||||
listeners.reset();
|
||||
};
|
||||
|
||||
Listener listener1 { callback };
|
||||
Listener listener2 { callback };
|
||||
|
||||
listeners->add (&listener1);
|
||||
listeners->add (&listener2);
|
||||
|
||||
listeners->call (&Listener::notify);
|
||||
|
||||
expect (listeners == nullptr);
|
||||
}
|
||||
|
||||
beginTest ("Using a BailOutChecker");
|
||||
{
|
||||
struct Listener
|
||||
{
|
||||
std::function<void()> onCallback;
|
||||
void notify() { onCallback(); }
|
||||
};
|
||||
|
||||
ListenerList<Listener> listeners;
|
||||
|
||||
bool listener1Called = false;
|
||||
bool listener2Called = false;
|
||||
bool listener3Called = false;
|
||||
|
||||
Listener listener1 { [&]{ listener1Called = true; } };
|
||||
Listener listener2 { [&]{ listener2Called = true; } };
|
||||
Listener listener3 { [&]{ listener3Called = true; } };
|
||||
|
||||
listeners.add (&listener1);
|
||||
listeners.add (&listener2);
|
||||
listeners.add (&listener3);
|
||||
|
||||
struct BailOutChecker
|
||||
{
|
||||
bool& bailOutBool;
|
||||
bool shouldBailOut() const { return bailOutBool; }
|
||||
};
|
||||
|
||||
BailOutChecker bailOutChecker { listener2Called };
|
||||
listeners.callChecked (bailOutChecker, &Listener::notify);
|
||||
|
||||
expect ( listener1Called);
|
||||
expect ( listener2Called);
|
||||
expect (! listener3Called);
|
||||
}
|
||||
|
||||
beginTest ("Using a critical section");
|
||||
{
|
||||
struct Listener
|
||||
{
|
||||
std::function<void()> onCallback;
|
||||
void notify() { onCallback(); }
|
||||
};
|
||||
|
||||
struct TestCriticalSection
|
||||
{
|
||||
TestCriticalSection() noexcept { isAlive() = true; }
|
||||
~TestCriticalSection() noexcept { isAlive() = false; }
|
||||
|
||||
static void enter() noexcept { numOutOfScopeCalls() += isAlive() ? 0 : 1; }
|
||||
static void exit() noexcept { numOutOfScopeCalls() += isAlive() ? 0 : 1; }
|
||||
|
||||
static bool tryEnter() noexcept
|
||||
{
|
||||
numOutOfScopeCalls() += isAlive() ? 0 : 1;
|
||||
return true;
|
||||
}
|
||||
|
||||
using ScopedLockType = GenericScopedLock<TestCriticalSection>;
|
||||
|
||||
static bool& isAlive() noexcept
|
||||
{
|
||||
static bool inScope = false;
|
||||
return inScope;
|
||||
}
|
||||
|
||||
static int& numOutOfScopeCalls() noexcept
|
||||
{
|
||||
static int numOutOfScopeCalls = 0;
|
||||
return numOutOfScopeCalls;
|
||||
}
|
||||
};
|
||||
|
||||
auto listeners = std::make_unique<juce::ListenerList<Listener, Array<Listener*, TestCriticalSection>>>();
|
||||
|
||||
const auto callback = [&]{ listeners.reset(); };
|
||||
|
||||
Listener listener { callback };
|
||||
|
||||
listeners->add (&listener);
|
||||
listeners->call (&Listener::notify);
|
||||
|
||||
expect (listeners == nullptr);
|
||||
expect (TestCriticalSection::numOutOfScopeCalls() == 0);
|
||||
}
|
||||
|
||||
beginTest ("Adding a listener during a callback when one has already been removed");
|
||||
{
|
||||
struct Listener{};
|
||||
|
||||
ListenerList<Listener> listeners;
|
||||
expect (listeners.size() == 0);
|
||||
|
||||
Listener listener1;
|
||||
Listener listener2;
|
||||
listeners.add (&listener1);
|
||||
listeners.add (&listener2);
|
||||
expect (listeners.size() == 2);
|
||||
|
||||
int numberOfCallbacks = 0;
|
||||
|
||||
listeners.call ([&] (auto& l)
|
||||
{
|
||||
listeners.remove (&l);
|
||||
expect (listeners.size() == 1);
|
||||
|
||||
listeners.add (&l);
|
||||
expect (listeners.size() == 2);
|
||||
|
||||
++numberOfCallbacks;
|
||||
});
|
||||
|
||||
expect (numberOfCallbacks == 2);
|
||||
expect (listeners.size() == 2);
|
||||
}
|
||||
|
||||
beginTest ("Add and remove a nested listener");
|
||||
{
|
||||
struct Listener{};
|
||||
|
||||
ListenerList<Listener> listeners;
|
||||
expect (listeners.size() == 0);
|
||||
|
||||
Listener listener1;
|
||||
Listener listener2;
|
||||
listeners.add (&listener1);
|
||||
listeners.add (&listener2);
|
||||
expect (listeners.size() == 2);
|
||||
|
||||
int numberOfCallbacks = 0;
|
||||
|
||||
listeners.call ([&] (auto)
|
||||
{
|
||||
Listener nestedListener;
|
||||
|
||||
listeners.add (&nestedListener);
|
||||
expect (listeners.size() == 3);
|
||||
|
||||
listeners.remove (&nestedListener);
|
||||
expect (listeners.size() == 2);
|
||||
|
||||
++numberOfCallbacks;
|
||||
});
|
||||
|
||||
expect (numberOfCallbacks == 2);
|
||||
expect (listeners.size() == 2);
|
||||
}
|
||||
|
||||
beginTest ("ThreadSafeListenerList stress test");
|
||||
{
|
||||
struct Listener { void callback(){} };
|
||||
|
||||
ThreadPool threadPool { 10 };
|
||||
ThreadSafeListenerList<Listener> listeners;
|
||||
|
||||
for (int i = 0; i < 1'000; ++i)
|
||||
{
|
||||
threadPool.addJob ([&]
|
||||
{
|
||||
std::vector<std::unique_ptr<Listener>> listenersToAdd;
|
||||
|
||||
for (int j = 0; j < 1'000; ++j)
|
||||
{
|
||||
listenersToAdd.push_back (std::make_unique<Listener>());
|
||||
listeners.add (listenersToAdd.back().get());
|
||||
}
|
||||
|
||||
for (auto& listener : listenersToAdd)
|
||||
listeners.remove (listener.get());
|
||||
});
|
||||
|
||||
threadPool.addJob ([&]
|
||||
{
|
||||
listeners.call (&Listener::callback);
|
||||
});
|
||||
}
|
||||
|
||||
expect (threadPool.removeAllJobs (false, 30'000));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
static std::set<int> chooseUnique (Random& random, int max, int numChosen)
|
||||
{
|
||||
std::set<int> result;
|
||||
|
||||
while ((int) result.size() < numChosen)
|
||||
result.insert (random.nextInt ({ 0, max }));
|
||||
|
||||
return result;
|
||||
}
|
||||
};
|
||||
|
||||
class LightweightListenerListTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
LightweightListenerListTests() : UnitTest ("LightweightListenerList", UnitTestCategories::containers) {}
|
||||
|
||||
void runTest() final
|
||||
{
|
||||
class Listener
|
||||
{
|
||||
public:
|
||||
void triggerCallback() { ++numCallbacksTriggered; }
|
||||
int getNumCallbacksTriggered() const { return numCallbacksTriggered; }
|
||||
|
||||
private:
|
||||
int numCallbacksTriggered = 0;
|
||||
};
|
||||
|
||||
beginTest ("Default list is empty");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
expect (listeners.isEmpty());
|
||||
expect (listeners.size() == 0);
|
||||
}
|
||||
|
||||
beginTest ("Adding a listener");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener;
|
||||
|
||||
expect (listener.getNumCallbacksTriggered() == 0);
|
||||
expect (! listeners.contains (&listener));
|
||||
|
||||
listeners.add (&listener);
|
||||
expect (! listeners.isEmpty());
|
||||
expect (listeners.size() == 1);
|
||||
expect (listeners.contains (&listener));
|
||||
expect (listener.getNumCallbacksTriggered() == 0);
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener.getNumCallbacksTriggered() == 1);
|
||||
expect (! listeners.isEmpty());
|
||||
expect (listeners.size() == 1);
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
|
||||
expect (listener.getNumCallbacksTriggered() == 2);
|
||||
}
|
||||
|
||||
beginTest ("Adding the same listener twice");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener;
|
||||
|
||||
listeners.add (&listener);
|
||||
listeners.add (&listener);
|
||||
|
||||
expect (! listeners.isEmpty());
|
||||
expect (listeners.size() == 1);
|
||||
expect (listeners.contains (&listener));
|
||||
expect (listener.getNumCallbacksTriggered() == 0);
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener.getNumCallbacksTriggered() == 1);
|
||||
}
|
||||
|
||||
beginTest ("Adding multiple listeners");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener1;
|
||||
Listener listener2;
|
||||
Listener listener3;
|
||||
|
||||
expect (! listeners.contains (&listener1));
|
||||
expect (! listeners.contains (&listener2));
|
||||
expect (! listeners.contains (&listener3));
|
||||
|
||||
listeners.add (&listener1);
|
||||
expect ( listeners.contains (&listener1));
|
||||
expect (! listeners.contains (&listener2));
|
||||
expect (! listeners.contains (&listener3));
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 1);
|
||||
expect (listener2.getNumCallbacksTriggered() == 0);
|
||||
expect (listener3.getNumCallbacksTriggered() == 0);
|
||||
|
||||
listeners.add (&listener2);
|
||||
expect (! listeners.isEmpty());
|
||||
expect (listeners.size() == 2);
|
||||
expect ( listeners.contains (&listener1));
|
||||
expect ( listeners.contains (&listener2));
|
||||
expect (! listeners.contains (&listener3));
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 2);
|
||||
expect (listener2.getNumCallbacksTriggered() == 1);
|
||||
expect (listener3.getNumCallbacksTriggered() == 0);
|
||||
|
||||
listeners.add (&listener3);
|
||||
expect (! listeners.isEmpty());
|
||||
expect (listeners.size() == 3);
|
||||
expect (listeners.contains (&listener1));
|
||||
expect (listeners.contains (&listener2));
|
||||
expect (listeners.contains (&listener3));
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 3);
|
||||
expect (listener2.getNumCallbacksTriggered() == 2);
|
||||
expect (listener3.getNumCallbacksTriggered() == 1);
|
||||
}
|
||||
|
||||
beginTest ("Removing a listener");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener1;
|
||||
Listener listener2;
|
||||
Listener listener3;
|
||||
|
||||
listeners.add (&listener1);
|
||||
listeners.add (&listener2);
|
||||
listeners.add (&listener3);
|
||||
|
||||
listeners.remove (&listener2);
|
||||
expect (listeners.size() == 2);
|
||||
expect (! listeners.contains (&listener2));
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 1);
|
||||
expect (listener2.getNumCallbacksTriggered() == 0);
|
||||
expect (listener3.getNumCallbacksTriggered() == 1);
|
||||
|
||||
listeners.remove (&listener1);
|
||||
expect (listeners.size() == 1);
|
||||
expect (! listeners.contains (&listener1));
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 1);
|
||||
expect (listener2.getNumCallbacksTriggered() == 0);
|
||||
expect (listener3.getNumCallbacksTriggered() == 2);
|
||||
|
||||
listeners.remove (&listener3);
|
||||
expect (listeners.size() == 0);
|
||||
expect (! listeners.contains (&listener3));
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 1);
|
||||
expect (listener2.getNumCallbacksTriggered() == 0);
|
||||
expect (listener3.getNumCallbacksTriggered() == 2);
|
||||
}
|
||||
|
||||
beginTest ("Adding a scoped listener");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener;
|
||||
|
||||
{
|
||||
const auto scopeGuard = listeners.addScoped (listener);
|
||||
expect (! listeners.isEmpty());
|
||||
expect (listeners.size() == 1);
|
||||
expect (listeners.contains (&listener));
|
||||
}
|
||||
|
||||
expect (listeners.isEmpty());
|
||||
expect (listeners.size() == 0);
|
||||
expect (! listeners.contains (&listener));
|
||||
}
|
||||
|
||||
beginTest ("Clear the listeners");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener1;
|
||||
Listener listener2;
|
||||
Listener listener3;
|
||||
|
||||
listeners.add (&listener1);
|
||||
listeners.add (&listener2);
|
||||
listeners.add (&listener3);
|
||||
|
||||
listeners.clear();
|
||||
expect (listeners.isEmpty());
|
||||
expect (listeners.size() == 0);
|
||||
|
||||
listeners.call (&Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 0);
|
||||
expect (listener2.getNumCallbacksTriggered() == 0);
|
||||
expect (listener3.getNumCallbacksTriggered() == 0);
|
||||
}
|
||||
|
||||
beginTest ("Call excluding");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener1;
|
||||
Listener listener2;
|
||||
Listener listener3;
|
||||
|
||||
listeners.add (&listener1);
|
||||
listeners.add (&listener2);
|
||||
listeners.add (&listener3);
|
||||
|
||||
listeners.callExcluding (&listener1, &Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 0);
|
||||
expect (listener2.getNumCallbacksTriggered() == 1);
|
||||
expect (listener3.getNumCallbacksTriggered() == 1);
|
||||
|
||||
listeners.callExcluding (&listener2, &Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 1);
|
||||
expect (listener2.getNumCallbacksTriggered() == 1);
|
||||
expect (listener3.getNumCallbacksTriggered() == 2);
|
||||
|
||||
listeners.callExcluding (&listener3, &Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 2);
|
||||
expect (listener2.getNumCallbacksTriggered() == 2);
|
||||
expect (listener3.getNumCallbacksTriggered() == 2);
|
||||
|
||||
}
|
||||
|
||||
beginTest ("Call with bail-out checker");
|
||||
{
|
||||
LightweightListenerList<Listener> listeners;
|
||||
Listener listener1;
|
||||
Listener listener2;
|
||||
Listener listener3;
|
||||
|
||||
listeners.add (&listener1);
|
||||
listeners.add (&listener2);
|
||||
listeners.add (&listener3);
|
||||
|
||||
struct BailOutChecker
|
||||
{
|
||||
bool shouldBailOut() const { return f(); }
|
||||
std::function<bool()> f;
|
||||
};
|
||||
|
||||
const BailOutChecker bailOutChecker { [&] { return listener2.getNumCallbacksTriggered() == 2; } };
|
||||
|
||||
// all the listeners should be called
|
||||
listeners.callChecked (bailOutChecker, &Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 1);
|
||||
expect (listener2.getNumCallbacksTriggered() == 1);
|
||||
expect (listener3.getNumCallbacksTriggered() == 1);
|
||||
|
||||
// only listeners 1 and 2 should be called
|
||||
listeners.callChecked (bailOutChecker, &Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 2);
|
||||
expect (listener2.getNumCallbacksTriggered() == 2);
|
||||
expect (listener3.getNumCallbacksTriggered() == 1);
|
||||
|
||||
// none of the listeners should be called
|
||||
listeners.callChecked (bailOutChecker, &Listener::triggerCallback);
|
||||
expect (listener1.getNumCallbacksTriggered() == 2);
|
||||
expect (listener2.getNumCallbacksTriggered() == 2);
|
||||
expect (listener3.getNumCallbacksTriggered() == 1);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static ListenerListTests listenerListTests;
|
||||
static LightweightListenerListTests lightweightListenerListTests;
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,277 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
bool NamedValue::operator== (const NamedValue& other) const noexcept
|
||||
{
|
||||
const auto tie = [] (auto& x) { return std::tie (x.name, x.value); };
|
||||
return tie (*this) == tie (other);
|
||||
}
|
||||
|
||||
bool NamedValue::operator!= (const NamedValue& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
NamedValueSet::NamedValueSet (std::initializer_list<NamedValue> list)
|
||||
: values (std::move (list))
|
||||
{
|
||||
}
|
||||
|
||||
void NamedValueSet::clear()
|
||||
{
|
||||
values.clear();
|
||||
}
|
||||
|
||||
bool NamedValueSet::operator== (const NamedValueSet& other) const noexcept
|
||||
{
|
||||
auto num = values.size();
|
||||
|
||||
if (num != other.values.size())
|
||||
return false;
|
||||
|
||||
for (int i = 0; i < num; ++i)
|
||||
{
|
||||
// optimise for the case where the keys are in the same order
|
||||
if (values.getReference (i).name == other.values.getReference (i).name)
|
||||
{
|
||||
if (values.getReference (i).value != other.values.getReference (i).value)
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
// if we encounter keys that are in a different order, search remaining items by brute force
|
||||
for (int j = i; j < num; ++j)
|
||||
{
|
||||
if (auto* otherVal = other.getVarPointer (values.getReference (j).name))
|
||||
if (values.getReference (j).value == *otherVal)
|
||||
continue;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NamedValueSet::operator!= (const NamedValueSet& other) const noexcept { return ! operator== (other); }
|
||||
|
||||
int NamedValueSet::size() const noexcept { return values.size(); }
|
||||
bool NamedValueSet::isEmpty() const noexcept { return values.isEmpty(); }
|
||||
|
||||
static const var& getNullVarRef() noexcept
|
||||
{
|
||||
static var nullVar;
|
||||
return nullVar;
|
||||
}
|
||||
|
||||
const var& NamedValueSet::operator[] (const Identifier& name) const noexcept
|
||||
{
|
||||
if (auto* v = getVarPointer (name))
|
||||
return *v;
|
||||
|
||||
return getNullVarRef();
|
||||
}
|
||||
|
||||
var NamedValueSet::getWithDefault (const Identifier& name, const var& defaultReturnValue) const
|
||||
{
|
||||
if (auto* v = getVarPointer (name))
|
||||
return *v;
|
||||
|
||||
return defaultReturnValue;
|
||||
}
|
||||
|
||||
var* NamedValueSet::getVarPointer (const Identifier& name) noexcept
|
||||
{
|
||||
for (auto& i : values)
|
||||
if (i.name == name)
|
||||
return &(i.value);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
const var* NamedValueSet::getVarPointer (const Identifier& name) const noexcept
|
||||
{
|
||||
for (auto& i : values)
|
||||
if (i.name == name)
|
||||
return &(i.value);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
bool NamedValueSet::set (const Identifier& name, var&& newValue)
|
||||
{
|
||||
if (auto* v = getVarPointer (name))
|
||||
{
|
||||
if (v->equalsWithSameType (newValue))
|
||||
return false;
|
||||
|
||||
*v = std::move (newValue);
|
||||
return true;
|
||||
}
|
||||
|
||||
values.add ({ name, std::move (newValue) });
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NamedValueSet::set (const Identifier& name, const var& newValue)
|
||||
{
|
||||
if (auto* v = getVarPointer (name))
|
||||
{
|
||||
if (v->equalsWithSameType (newValue))
|
||||
return false;
|
||||
|
||||
*v = newValue;
|
||||
return true;
|
||||
}
|
||||
|
||||
values.add ({ name, newValue });
|
||||
return true;
|
||||
}
|
||||
|
||||
bool NamedValueSet::contains (const Identifier& name) const noexcept
|
||||
{
|
||||
return getVarPointer (name) != nullptr;
|
||||
}
|
||||
|
||||
int NamedValueSet::indexOf (const Identifier& name) const noexcept
|
||||
{
|
||||
auto numValues = values.size();
|
||||
|
||||
for (int i = 0; i < numValues; ++i)
|
||||
if (values.getReference (i).name == name)
|
||||
return i;
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
bool NamedValueSet::remove (const Identifier& name)
|
||||
{
|
||||
auto numValues = values.size();
|
||||
|
||||
for (int i = 0; i < numValues; ++i)
|
||||
{
|
||||
if (values.getReference (i).name == name)
|
||||
{
|
||||
values.remove (i);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
Identifier NamedValueSet::getName (const int index) const noexcept
|
||||
{
|
||||
if (isPositiveAndBelow (index, values.size()))
|
||||
return values.getReference (index).name;
|
||||
|
||||
jassertfalse;
|
||||
return {};
|
||||
}
|
||||
|
||||
const var& NamedValueSet::getValueAt (const int index) const noexcept
|
||||
{
|
||||
if (isPositiveAndBelow (index, values.size()))
|
||||
return values.getReference (index).value;
|
||||
|
||||
jassertfalse;
|
||||
return getNullVarRef();
|
||||
}
|
||||
|
||||
var* NamedValueSet::getVarPointerAt (int index) noexcept
|
||||
{
|
||||
if (isPositiveAndBelow (index, values.size()))
|
||||
return &(values.getReference (index).value);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
const var* NamedValueSet::getVarPointerAt (int index) const noexcept
|
||||
{
|
||||
if (isPositiveAndBelow (index, values.size()))
|
||||
return &(values.getReference (index).value);
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
void NamedValueSet::setFromXmlAttributes (const XmlElement& xml)
|
||||
{
|
||||
values.clearQuick();
|
||||
|
||||
for (const auto& [name, value] : xml.getAttributeIterator())
|
||||
{
|
||||
if (name.toString().startsWith ("base64:"))
|
||||
{
|
||||
MemoryBlock mb;
|
||||
|
||||
if (mb.fromBase64Encoding (value))
|
||||
{
|
||||
values.add ({ name.toString().substring (7), var (mb) });
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
values.add ({ name, var (value) });
|
||||
}
|
||||
}
|
||||
|
||||
void NamedValueSet::copyToXmlAttributes (XmlElement& xml) const
|
||||
{
|
||||
for (auto& i : values)
|
||||
{
|
||||
if (auto* mb = i.value.getBinaryData())
|
||||
{
|
||||
xml.setAttribute ("base64:" + i.name.toString(), mb->toBase64Encoding());
|
||||
}
|
||||
else
|
||||
{
|
||||
// These types can't be stored as XML!
|
||||
jassert (! i.value.isObject());
|
||||
jassert (! i.value.isMethod());
|
||||
jassert (! i.value.isArray());
|
||||
|
||||
xml.setAttribute (i.name.toString(),
|
||||
i.value.toString());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,187 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
//==============================================================================
|
||||
/** Structure for a named var object, used as an element of a NamedValueSet. */
|
||||
class JUCE_API NamedValue
|
||||
{
|
||||
public:
|
||||
bool operator== (const NamedValue&) const noexcept;
|
||||
bool operator!= (const NamedValue&) const noexcept;
|
||||
|
||||
Identifier name;
|
||||
var value;
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
/** Holds a set of named var objects.
|
||||
|
||||
This can be used as a basic structure to hold a set of var object, which can
|
||||
be retrieved by using their identifier.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API NamedValueSet
|
||||
{
|
||||
public:
|
||||
using NamedValue = juce::NamedValue;
|
||||
|
||||
//==============================================================================
|
||||
/** Creates an empty set. */
|
||||
NamedValueSet() noexcept = default;
|
||||
|
||||
/** Creates a NamedValueSet from a list of names and properties. */
|
||||
NamedValueSet (std::initializer_list<NamedValue>);
|
||||
|
||||
/** Two NamedValueSets are considered equal if they contain all the same key/value
|
||||
pairs, regardless of the order.
|
||||
*/
|
||||
bool operator== (const NamedValueSet&) const noexcept;
|
||||
bool operator!= (const NamedValueSet&) const noexcept;
|
||||
|
||||
const NamedValue* begin() const noexcept { return values.begin(); }
|
||||
const NamedValue* end() const noexcept { return values.end(); }
|
||||
|
||||
Span<NamedValue> asSpan() & { return { values.data(), (size_t) values.size() }; }
|
||||
Span<const NamedValue> asSpan() const& { return { values.data(), (size_t) values.size() }; }
|
||||
|
||||
/* These functions are deleted to help avoid accidentally forming a span over a temporary. */
|
||||
Span<NamedValue> asSpan() && = delete;
|
||||
Span<const NamedValue> asSpan() const&& = delete;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the total number of values that the set contains. */
|
||||
int size() const noexcept;
|
||||
|
||||
/** Returns true if the set is empty. */
|
||||
bool isEmpty() const noexcept;
|
||||
|
||||
/** Returns the value of a named item.
|
||||
If the name isn't found, this will return a void variant.
|
||||
*/
|
||||
const var& operator[] (const Identifier& name) const noexcept;
|
||||
|
||||
/** Tries to return the named value, but if no such value is found, this will
|
||||
instead return the supplied default value.
|
||||
*/
|
||||
var getWithDefault (const Identifier& name, const var& defaultReturnValue) const;
|
||||
|
||||
/** Changes or adds a named value.
|
||||
@returns true if a value was changed or added; false if the
|
||||
value was already set the value passed-in.
|
||||
*/
|
||||
bool set (const Identifier& name, const var& newValue);
|
||||
|
||||
/** Changes or adds a named value.
|
||||
@returns true if a value was changed or added; false if the
|
||||
value was already set the value passed-in.
|
||||
*/
|
||||
bool set (const Identifier& name, var&& newValue);
|
||||
|
||||
/** Returns true if the set contains an item with the specified name. */
|
||||
bool contains (const Identifier& name) const noexcept;
|
||||
|
||||
/** Removes a value from the set.
|
||||
@returns true if a value was removed; false if there was no value
|
||||
with the name that was given.
|
||||
*/
|
||||
bool remove (const Identifier& name);
|
||||
|
||||
/** Returns the name of the value at a given index.
|
||||
The index must be between 0 and size() - 1.
|
||||
*/
|
||||
Identifier getName (int index) const noexcept;
|
||||
|
||||
/** Returns a pointer to the var that holds a named value, or null if there is
|
||||
no value with this name.
|
||||
|
||||
Do not use this method unless you really need access to the internal var object
|
||||
for some reason - for normal reading and writing always prefer operator[]() and set().
|
||||
Also note that the pointer returned may become invalid as soon as any subsequent
|
||||
methods are called on the NamedValueSet.
|
||||
*/
|
||||
var* getVarPointer (const Identifier& name) noexcept;
|
||||
|
||||
/** Returns a pointer to the var that holds a named value, or null if there is
|
||||
no value with this name.
|
||||
|
||||
Do not use this method unless you really need access to the internal var object
|
||||
for some reason - for normal reading and writing always prefer operator[]() and set().
|
||||
Also note that the pointer returned may become invalid as soon as any subsequent
|
||||
methods are called on the NamedValueSet.
|
||||
*/
|
||||
const var* getVarPointer (const Identifier& name) const noexcept;
|
||||
|
||||
/** Returns the value of the item at a given index.
|
||||
The index must be between 0 and size() - 1.
|
||||
*/
|
||||
const var& getValueAt (int index) const noexcept;
|
||||
|
||||
/** Returns the value of the item at a given index.
|
||||
The index must be between 0 and size() - 1, or this will return a nullptr
|
||||
Also note that the pointer returned may become invalid as soon as any subsequent
|
||||
methods are called on the NamedValueSet.
|
||||
*/
|
||||
var* getVarPointerAt (int index) noexcept;
|
||||
|
||||
/** Returns the value of the item at a given index.
|
||||
The index must be between 0 and size() - 1, or this will return a nullptr
|
||||
Also note that the pointer returned may become invalid as soon as any subsequent
|
||||
methods are called on the NamedValueSet.
|
||||
*/
|
||||
const var* getVarPointerAt (int index) const noexcept;
|
||||
|
||||
/** Returns the index of the given name, or -1 if it's not found. */
|
||||
int indexOf (const Identifier& name) const noexcept;
|
||||
|
||||
/** Removes all values. */
|
||||
void clear();
|
||||
|
||||
//==============================================================================
|
||||
/** Sets properties to the values of all of an XML element's attributes. */
|
||||
void setFromXmlAttributes (const XmlElement& xml);
|
||||
|
||||
/** Sets attributes in an XML element corresponding to each of this object's
|
||||
properties.
|
||||
*/
|
||||
void copyToXmlAttributes (XmlElement& xml) const;
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
Array<NamedValue> values;
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,192 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
using Nullopt = std::nullopt_t;
|
||||
constexpr auto nullopt = std::nullopt;
|
||||
|
||||
// Without this, our tests can emit "unreachable code" warnings during
|
||||
// link time code generation.
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4702)
|
||||
|
||||
/** @cond */
|
||||
#define JUCE_OPTIONAL_OPERATORS X(==) X(!=) X(<) X(<=) X(>) X(>=)
|
||||
/** @endcond */
|
||||
|
||||
/**
|
||||
A simple optional type.
|
||||
|
||||
In new code, you should probably prefer using std::optional directly.
|
||||
|
||||
This is intended to stand-in for std::optional while JUCE's minimum
|
||||
supported language standard is lower than C++17. When the minimum language
|
||||
standard moves to C++17, this class will probably be deprecated, in much
|
||||
the same way that juce::ScopedPointer was deprecated in favour of
|
||||
std::unique_ptr after C++11.
|
||||
|
||||
This isn't really intended to be used by JUCE clients. Instead, it's to be
|
||||
used internally in JUCE code, with an API close-enough to std::optional
|
||||
that the types can be swapped with fairly minor disruption at some point in
|
||||
the future, but *without breaking any public APIs*.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Value>
|
||||
class Optional
|
||||
{
|
||||
template <typename> struct IsOptional : std::false_type {};
|
||||
template <typename T> struct IsOptional<Optional<T>> : std::true_type {};
|
||||
|
||||
public:
|
||||
Optional() = default;
|
||||
Optional (const Optional&) = default;
|
||||
Optional (Optional&&) = default;
|
||||
Optional& operator= (const Optional&) = default;
|
||||
Optional& operator= (Optional&&) = default;
|
||||
|
||||
Optional (Nullopt) noexcept {}
|
||||
|
||||
template <typename Head, typename... Tail, std::enable_if_t<! IsOptional<std::decay_t<Head>>::value, int> = 0>
|
||||
Optional (Head&& head, Tail&&... tail)
|
||||
noexcept (std::is_nothrow_constructible_v<std::optional<Value>, Head, Tail...>)
|
||||
: opt (std::forward<Head> (head), std::forward<Tail> (tail)...) {}
|
||||
|
||||
template <typename Other>
|
||||
Optional (const Optional<Other>& other)
|
||||
noexcept (std::is_nothrow_constructible_v<std::optional<Value>, const std::optional<Other>&>)
|
||||
: opt (other.opt) {}
|
||||
|
||||
template <typename Other>
|
||||
Optional (Optional<Other>&& other)
|
||||
noexcept (std::is_nothrow_constructible_v<std::optional<Value>, std::optional<Other>&&>)
|
||||
: opt (std::move (other.opt)) {}
|
||||
|
||||
template <typename Other, std::enable_if_t<! IsOptional<std::decay_t<Other>>::value, int> = 0>
|
||||
Optional& operator= (Other&& other)
|
||||
noexcept (std::is_nothrow_assignable_v<std::optional<Value>, Other>)
|
||||
{
|
||||
opt = std::forward<Other> (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename Other>
|
||||
Optional& operator= (const Optional<Other>& other)
|
||||
noexcept (std::is_nothrow_assignable_v<std::optional<Value>, const std::optional<Other>&>)
|
||||
{
|
||||
opt = other.opt;
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename Other>
|
||||
Optional& operator= (Optional<Other>&& other)
|
||||
noexcept (std::is_nothrow_assignable_v<std::optional<Value>, std::optional<Other>&&>)
|
||||
{
|
||||
opt = std::move (other.opt);
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename... Other>
|
||||
auto& emplace (Other&&... other)
|
||||
{
|
||||
return opt.emplace (std::forward<Other> (other)...);
|
||||
}
|
||||
|
||||
void reset() noexcept
|
||||
{
|
||||
opt.reset();
|
||||
}
|
||||
|
||||
void swap (Optional& other)
|
||||
noexcept (std::is_nothrow_swappable_v<std::optional<Value>>)
|
||||
{
|
||||
opt.swap (other.opt);
|
||||
}
|
||||
|
||||
decltype (auto) operator->() { return opt.operator->(); }
|
||||
decltype (auto) operator->() const { return opt.operator->(); }
|
||||
decltype (auto) operator* () { return opt.operator* (); }
|
||||
decltype (auto) operator* () const { return opt.operator* (); }
|
||||
|
||||
explicit operator bool() const noexcept { return opt.has_value(); }
|
||||
bool hasValue() const noexcept { return opt.has_value(); }
|
||||
|
||||
template <typename U>
|
||||
decltype (auto) orFallback (U&& fallback) const& { return opt.value_or (std::forward<U> (fallback)); }
|
||||
|
||||
template <typename U>
|
||||
decltype (auto) orFallback (U&& fallback) & { return opt.value_or (std::forward<U> (fallback)); }
|
||||
|
||||
#define X(op) \
|
||||
template <typename T, typename U> friend bool operator op (const Optional<T>&, const Optional<U>&); \
|
||||
template <typename T> friend bool operator op (const Optional<T>&, Nullopt); \
|
||||
template <typename T> friend bool operator op (Nullopt, const Optional<T>&); \
|
||||
template <typename T, typename U> friend bool operator op (const Optional<T>&, const U&); \
|
||||
template <typename T, typename U> friend bool operator op (const T&, const Optional<U>&);
|
||||
|
||||
JUCE_OPTIONAL_OPERATORS
|
||||
|
||||
#undef X
|
||||
|
||||
private:
|
||||
template <typename Other>
|
||||
friend class Optional;
|
||||
|
||||
std::optional<Value> opt;
|
||||
};
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
|
||||
template <typename Value>
|
||||
Optional<std::decay_t<Value>> makeOptional (Value&& v)
|
||||
{
|
||||
return std::forward<Value> (v);
|
||||
}
|
||||
|
||||
/** @cond */
|
||||
#define X(op) \
|
||||
template <typename T, typename U> bool operator op (const Optional<T>& lhs, const Optional<U>& rhs) { return lhs.opt op rhs.opt; } \
|
||||
template <typename T> bool operator op (const Optional<T>& lhs, Nullopt rhs) { return lhs.opt op rhs; } \
|
||||
template <typename T> bool operator op (Nullopt lhs, const Optional<T>& rhs) { return lhs op rhs.opt; } \
|
||||
template <typename T, typename U> bool operator op (const Optional<T>& lhs, const U& rhs) { return lhs.opt op rhs; } \
|
||||
template <typename T, typename U> bool operator op (const T& lhs, const Optional<U>& rhs) { return lhs op rhs.opt; }
|
||||
|
||||
JUCE_OPTIONAL_OPERATORS
|
||||
|
||||
#undef X
|
||||
#undef JUCE_OPTIONAL_OPERATORS
|
||||
/** @endcond */
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,640 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
/* Not nested, so that ADL works for the swap function. */
|
||||
struct ThrowOnMoveOrSwap
|
||||
{
|
||||
ThrowOnMoveOrSwap() = default;
|
||||
ThrowOnMoveOrSwap (ThrowOnMoveOrSwap&&) { throw std::bad_alloc{}; }
|
||||
};
|
||||
static void swap (ThrowOnMoveOrSwap&, ThrowOnMoveOrSwap&) { throw std::bad_alloc{}; }
|
||||
|
||||
class OptionalUnitTest final : public UnitTest
|
||||
{
|
||||
public:
|
||||
OptionalUnitTest() : UnitTest ("Optional", UnitTestCategories::containers) {}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("Default-constructed optional is invalid");
|
||||
{
|
||||
Optional<int> o;
|
||||
expect (! o.hasValue());
|
||||
}
|
||||
|
||||
beginTest ("Constructing from Nullopt is invalid");
|
||||
{
|
||||
Optional<int> o (nullopt);
|
||||
expect (! o.hasValue());
|
||||
}
|
||||
|
||||
beginTest ("Optional constructed from value is valid");
|
||||
{
|
||||
Optional<int> o = 5;
|
||||
expect (o.hasValue());
|
||||
expectEquals (*o, 5);
|
||||
}
|
||||
|
||||
using Ptr = std::shared_ptr<int>;
|
||||
const auto makePtr = [] { return std::make_shared<int>(); };
|
||||
|
||||
beginTest ("Constructing from a moved optional calls appropriate member functions");
|
||||
{
|
||||
auto ptr = makePtr();
|
||||
Optional<Ptr> original (ptr);
|
||||
expect (ptr.use_count() == 2);
|
||||
auto other = std::move (original);
|
||||
// A moved-from optional still contains a value!
|
||||
expect (original.hasValue());
|
||||
expect (other.hasValue());
|
||||
expect (ptr.use_count() == 2);
|
||||
}
|
||||
|
||||
beginTest ("Moving an empty optional to a populated one destroys the instance");
|
||||
{
|
||||
auto ptr = makePtr();
|
||||
Optional<Ptr> original (ptr);
|
||||
expect (ptr.use_count() == 2);
|
||||
original = Optional<Ptr>();
|
||||
expect (ptr.use_count() == 1);
|
||||
}
|
||||
|
||||
beginTest ("Copying an empty optional to a populated one destroys the instance");
|
||||
{
|
||||
auto ptr = makePtr();
|
||||
Optional<Ptr> original (ptr);
|
||||
expect (ptr.use_count() == 2);
|
||||
Optional<Ptr> empty;
|
||||
original = empty;
|
||||
expect (ptr.use_count() == 1);
|
||||
}
|
||||
|
||||
beginTest ("Moving a populated optional calls appropriate member functions");
|
||||
{
|
||||
auto a = makePtr();
|
||||
auto b = makePtr();
|
||||
|
||||
Optional<Ptr> aOpt (a);
|
||||
Optional<Ptr> bOpt (b);
|
||||
|
||||
expect (a.use_count() == 2);
|
||||
expect (b.use_count() == 2);
|
||||
|
||||
aOpt = std::move (bOpt);
|
||||
|
||||
expect (aOpt.hasValue());
|
||||
expect (bOpt.hasValue());
|
||||
|
||||
expect (a.use_count() == 1);
|
||||
expect (b.use_count() == 2);
|
||||
}
|
||||
|
||||
beginTest ("Copying a populated optional calls appropriate member functions");
|
||||
{
|
||||
auto a = makePtr();
|
||||
auto b = makePtr();
|
||||
|
||||
Optional<Ptr> aOpt (a);
|
||||
Optional<Ptr> bOpt (b);
|
||||
|
||||
expect (a.use_count() == 2);
|
||||
expect (b.use_count() == 2);
|
||||
|
||||
aOpt = bOpt;
|
||||
|
||||
expect (aOpt.hasValue());
|
||||
expect (bOpt.hasValue());
|
||||
|
||||
expect (a.use_count() == 1);
|
||||
expect (b.use_count() == 3);
|
||||
}
|
||||
|
||||
beginTest ("Moving an empty optional to an empty one does nothing");
|
||||
{
|
||||
Optional<Ptr> original;
|
||||
original = Optional<Ptr>();
|
||||
expect (! original.hasValue());
|
||||
}
|
||||
|
||||
beginTest ("Copying an empty optional to an empty one does nothing");
|
||||
{
|
||||
Optional<Ptr> original;
|
||||
Optional<Ptr> empty;
|
||||
original = empty;
|
||||
expect (! original.hasValue());
|
||||
expect (! empty.hasValue());
|
||||
}
|
||||
|
||||
beginTest ("Moving a populated optional calls appropriate member functions");
|
||||
{
|
||||
auto a = makePtr();
|
||||
|
||||
Optional<Ptr> aOpt (a);
|
||||
Optional<Ptr> empty;
|
||||
|
||||
expect (a.use_count() == 2);
|
||||
|
||||
empty = std::move (aOpt);
|
||||
|
||||
expect (empty.hasValue());
|
||||
expect (aOpt.hasValue());
|
||||
|
||||
expect (a.use_count() == 2);
|
||||
}
|
||||
|
||||
beginTest ("Copying a populated optional calls appropriate member functions");
|
||||
{
|
||||
auto a = makePtr();
|
||||
|
||||
Optional<Ptr> aOpt (a);
|
||||
Optional<Ptr> empty;
|
||||
|
||||
expect (a.use_count() == 2);
|
||||
|
||||
empty = aOpt;
|
||||
|
||||
expect (aOpt.hasValue());
|
||||
expect (empty.hasValue());
|
||||
|
||||
expect (a.use_count() == 3);
|
||||
}
|
||||
|
||||
struct ThrowOnCopy
|
||||
{
|
||||
ThrowOnCopy() = default;
|
||||
|
||||
// Put into an invalid state and throw
|
||||
ThrowOnCopy (const ThrowOnCopy&)
|
||||
{
|
||||
value = -100;
|
||||
throw std::bad_alloc{};
|
||||
}
|
||||
|
||||
// Put into an invalid state and throw
|
||||
ThrowOnCopy& operator= (const ThrowOnCopy&)
|
||||
{
|
||||
value = -100;
|
||||
throw std::bad_alloc{};
|
||||
}
|
||||
|
||||
ThrowOnCopy (ThrowOnCopy&&) noexcept = default;
|
||||
ThrowOnCopy& operator= (ThrowOnCopy&&) noexcept = default;
|
||||
|
||||
~ThrowOnCopy() = default;
|
||||
|
||||
int value = 0;
|
||||
};
|
||||
|
||||
beginTest ("Strong exception safety is maintained when forwarding over empty object");
|
||||
{
|
||||
bool threw = false;
|
||||
Optional<ThrowOnCopy> a;
|
||||
|
||||
try
|
||||
{
|
||||
ThrowOnCopy t;
|
||||
a = t;
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (! a.hasValue()); // If construction failed, this object should still be well-formed but empty
|
||||
}
|
||||
|
||||
beginTest ("Weak exception safety is maintained when forwarding over populated object");
|
||||
{
|
||||
bool threw = false;
|
||||
Optional<ThrowOnCopy> a = ThrowOnCopy();
|
||||
a->value = 5;
|
||||
|
||||
try
|
||||
{
|
||||
ThrowOnCopy t;
|
||||
a = t;
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (a.hasValue());
|
||||
expect (a->value == -100); // If we assign to an extant object, it's up to that object to provide an exception guarantee
|
||||
}
|
||||
|
||||
beginTest ("Strong exception safety is maintained when copying over empty object");
|
||||
{
|
||||
bool threw = false;
|
||||
Optional<ThrowOnCopy> a;
|
||||
|
||||
try
|
||||
{
|
||||
Optional<ThrowOnCopy> t = ThrowOnCopy{};
|
||||
a = t;
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (! a.hasValue());
|
||||
}
|
||||
|
||||
beginTest ("Exception safety of contained type is maintained when copying over populated object");
|
||||
{
|
||||
bool threw = false;
|
||||
Optional<ThrowOnCopy> a = ThrowOnCopy();
|
||||
a->value = 5;
|
||||
|
||||
try
|
||||
{
|
||||
Optional<ThrowOnCopy> t = ThrowOnCopy{};
|
||||
a = t;
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (a.hasValue());
|
||||
expect (a->value == -100);
|
||||
}
|
||||
|
||||
beginTest ("Assigning from nullopt clears the instance");
|
||||
{
|
||||
auto ptr = makePtr();
|
||||
Optional<Ptr> a (ptr);
|
||||
expect (ptr.use_count() == 2);
|
||||
a = nullopt;
|
||||
expect (ptr.use_count() == 1);
|
||||
}
|
||||
|
||||
struct Foo {};
|
||||
struct Bar final : public Foo {};
|
||||
|
||||
beginTest ("Can be constructed from compatible type");
|
||||
{
|
||||
Optional<std::shared_ptr<Foo>> opt { std::make_shared<Bar>() };
|
||||
}
|
||||
|
||||
beginTest ("Can be assigned from compatible type");
|
||||
{
|
||||
Optional<std::shared_ptr<Foo>> opt;
|
||||
opt = std::make_shared<Bar>();
|
||||
}
|
||||
|
||||
beginTest ("Can copy from compatible type");
|
||||
{
|
||||
auto ptr = std::make_shared<Bar>();
|
||||
Optional<std::shared_ptr<Bar>> bar (ptr);
|
||||
Optional<std::shared_ptr<Foo>> foo (bar);
|
||||
expect (ptr.use_count() == 3);
|
||||
}
|
||||
|
||||
beginTest ("Can move from compatible type");
|
||||
{
|
||||
auto ptr = std::make_shared<Bar>();
|
||||
Optional<std::shared_ptr<Foo>> foo (Optional<std::shared_ptr<Bar>> { ptr });
|
||||
expect (ptr.use_count() == 2);
|
||||
}
|
||||
|
||||
beginTest ("Can copy assign from compatible type");
|
||||
{
|
||||
auto ptr = std::make_shared<Bar>();
|
||||
Optional<std::shared_ptr<Bar>> bar (ptr);
|
||||
Optional<std::shared_ptr<Foo>> foo;
|
||||
foo = bar;
|
||||
expect (ptr.use_count() == 3);
|
||||
}
|
||||
|
||||
beginTest ("Can move assign from compatible type");
|
||||
{
|
||||
auto ptr = std::make_shared<Bar>();
|
||||
Optional<std::shared_ptr<Foo>> foo;
|
||||
foo = Optional<std::shared_ptr<Bar>> (ptr);
|
||||
expect (ptr.use_count() == 2);
|
||||
}
|
||||
|
||||
beginTest ("An exception thrown during emplace leaves the optional without a value");
|
||||
{
|
||||
Optional<ThrowOnCopy> opt { ThrowOnCopy{} };
|
||||
bool threw = false;
|
||||
|
||||
try
|
||||
{
|
||||
ThrowOnCopy t;
|
||||
opt.emplace (t);
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (! opt.hasValue());
|
||||
}
|
||||
|
||||
beginTest ("Swap does nothing to two empty optionals");
|
||||
{
|
||||
Optional<Ptr> a, b;
|
||||
expect (! a.hasValue());
|
||||
expect (! b.hasValue());
|
||||
|
||||
a.swap (b);
|
||||
|
||||
expect (! a.hasValue());
|
||||
expect (! b.hasValue());
|
||||
}
|
||||
|
||||
beginTest ("Swap transfers ownership if one optional contains a value");
|
||||
{
|
||||
{
|
||||
Ptr ptr = makePtr();
|
||||
Optional<Ptr> a, b = ptr;
|
||||
expect (! a.hasValue());
|
||||
expect (b.hasValue());
|
||||
expect (ptr.use_count() == 2);
|
||||
|
||||
a.swap (b);
|
||||
|
||||
expect (a.hasValue());
|
||||
expect (! b.hasValue());
|
||||
expect (ptr.use_count() == 2);
|
||||
}
|
||||
|
||||
{
|
||||
auto ptr = makePtr();
|
||||
Optional<Ptr> a = ptr, b;
|
||||
expect (a.hasValue());
|
||||
expect (! b.hasValue());
|
||||
expect (ptr.use_count() == 2);
|
||||
|
||||
a.swap (b);
|
||||
|
||||
expect (! a.hasValue());
|
||||
expect (b.hasValue());
|
||||
expect (ptr.use_count() == 2);
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Swap calls std::swap to swap two populated optionals");
|
||||
{
|
||||
auto x = makePtr(), y = makePtr();
|
||||
Optional<Ptr> a = x, b = y;
|
||||
expect (a.hasValue());
|
||||
expect (b.hasValue());
|
||||
expect (x.use_count() == 2);
|
||||
expect (y.use_count() == 2);
|
||||
expect (*a == x);
|
||||
expect (*b == y);
|
||||
|
||||
a.swap (b);
|
||||
|
||||
expect (a.hasValue());
|
||||
expect (b.hasValue());
|
||||
expect (x.use_count() == 2);
|
||||
expect (y.use_count() == 2);
|
||||
expect (*a == y);
|
||||
expect (*b == x);
|
||||
}
|
||||
|
||||
beginTest ("An exception thrown during a swap leaves both objects in the previous populated state");
|
||||
{
|
||||
{
|
||||
Optional<ThrowOnMoveOrSwap> a, b;
|
||||
a.emplace();
|
||||
|
||||
expect (a.hasValue());
|
||||
expect (! b.hasValue());
|
||||
|
||||
bool threw = false;
|
||||
|
||||
try
|
||||
{
|
||||
a.swap (b);
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (a.hasValue());
|
||||
expect (! b.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
Optional<ThrowOnMoveOrSwap> a, b;
|
||||
b.emplace();
|
||||
|
||||
expect (! a.hasValue());
|
||||
expect (b.hasValue());
|
||||
|
||||
bool threw = false;
|
||||
|
||||
try
|
||||
{
|
||||
a.swap (b);
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (! a.hasValue());
|
||||
expect (b.hasValue());
|
||||
}
|
||||
|
||||
{
|
||||
Optional<ThrowOnMoveOrSwap> a, b;
|
||||
a.emplace();
|
||||
b.emplace();
|
||||
|
||||
expect (a.hasValue());
|
||||
expect (b.hasValue());
|
||||
|
||||
bool threw = false;
|
||||
|
||||
try
|
||||
{
|
||||
a.swap (b);
|
||||
}
|
||||
catch (const std::bad_alloc&)
|
||||
{
|
||||
threw = true;
|
||||
}
|
||||
|
||||
expect (threw);
|
||||
expect (a.hasValue());
|
||||
expect (b.hasValue());
|
||||
}
|
||||
}
|
||||
|
||||
beginTest ("Relational tests");
|
||||
{
|
||||
expect (Optional<int> (1) == Optional<int> (1));
|
||||
expect (Optional<int>() == Optional<int>());
|
||||
expect (! (Optional<int> (1) == Optional<int>()));
|
||||
expect (! (Optional<int>() == Optional<int> (1)));
|
||||
expect (! (Optional<int> (1) == Optional<int> (2)));
|
||||
|
||||
expect (Optional<int> (1) != Optional<int> (2));
|
||||
expect (! (Optional<int>() != Optional<int>()));
|
||||
expect (Optional<int> (1) != Optional<int>());
|
||||
expect (Optional<int>() != Optional<int> (1));
|
||||
expect (! (Optional<int> (1) != Optional<int> (1)));
|
||||
|
||||
expect (Optional<int>() < Optional<int> (1));
|
||||
expect (! (Optional<int> (1) < Optional<int>()));
|
||||
expect (! (Optional<int>() < Optional<int>()));
|
||||
expect (Optional<int> (1) < Optional<int> (2));
|
||||
|
||||
expect (Optional<int>() <= Optional<int> (1));
|
||||
expect (! (Optional<int> (1) <= Optional<int>()));
|
||||
expect (Optional<int>() <= Optional<int>());
|
||||
expect (Optional<int> (1) <= Optional<int> (2));
|
||||
|
||||
expect (! (Optional<int>() > Optional<int> (1)));
|
||||
expect (Optional<int> (1) > Optional<int>());
|
||||
expect (! (Optional<int>() > Optional<int>()));
|
||||
expect (! (Optional<int> (1) > Optional<int> (2)));
|
||||
|
||||
expect (! (Optional<int>() >= Optional<int> (1)));
|
||||
expect (Optional<int> (1) >= Optional<int>());
|
||||
expect (Optional<int>() >= Optional<int>());
|
||||
expect (! (Optional<int> (1) >= Optional<int> (2)));
|
||||
|
||||
expect (Optional<int>() == nullopt);
|
||||
expect (! (Optional<int> (1) == nullopt));
|
||||
expect (nullopt == Optional<int>());
|
||||
expect (! (nullopt == Optional<int> (1)));
|
||||
|
||||
expect (! (Optional<int>() != nullopt));
|
||||
expect (Optional<int> (1) != nullopt);
|
||||
expect (! (nullopt != Optional<int>()));
|
||||
expect (nullopt != Optional<int> (1));
|
||||
|
||||
expect (! (Optional<int>() < nullopt));
|
||||
expect (! (Optional<int> (1) < nullopt));
|
||||
|
||||
expect (! (nullopt < Optional<int>()));
|
||||
expect (nullopt < Optional<int> (1));
|
||||
|
||||
expect (Optional<int>() <= nullopt);
|
||||
expect (! (Optional<int> (1) <= nullopt));
|
||||
|
||||
expect (nullopt <= Optional<int>());
|
||||
expect (nullopt <= Optional<int> (1));
|
||||
|
||||
expect (! (Optional<int>() > nullopt));
|
||||
expect (Optional<int> (1) > nullopt);
|
||||
|
||||
expect (! (nullopt > Optional<int>()));
|
||||
expect (! (nullopt > Optional<int> (1)));
|
||||
|
||||
expect (Optional<int>() >= nullopt);
|
||||
expect (Optional<int> (1) >= nullopt);
|
||||
|
||||
expect (nullopt >= Optional<int>());
|
||||
expect (! (nullopt >= Optional<int> (1)));
|
||||
|
||||
expect (! (Optional<int>() == 5));
|
||||
expect (! (Optional<int> (1) == 5));
|
||||
expect (Optional<int> (1) == 1);
|
||||
expect (! (5 == Optional<int>()));
|
||||
expect (! (5 == Optional<int> (1)));
|
||||
expect (1 == Optional<int> (1));
|
||||
|
||||
expect (Optional<int>() != 5);
|
||||
expect (Optional<int> (1) != 5);
|
||||
expect (! (Optional<int> (1) != 1));
|
||||
expect (5 != Optional<int>());
|
||||
expect (5 != Optional<int> (1));
|
||||
expect (! (1 != Optional<int> (1)));
|
||||
|
||||
expect (Optional<int>() < 5);
|
||||
expect (Optional<int> (1) < 5);
|
||||
expect (! (Optional<int> (1) < 1));
|
||||
expect (! (Optional<int> (1) < 0));
|
||||
|
||||
expect (! (5 < Optional<int>()));
|
||||
expect (! (5 < Optional<int> (1)));
|
||||
expect (! (1 < Optional<int> (1)));
|
||||
expect (0 < Optional<int> (1));
|
||||
|
||||
expect (Optional<int>() <= 5);
|
||||
expect (Optional<int> (1) <= 5);
|
||||
expect (Optional<int> (1) <= 1);
|
||||
expect (! (Optional<int> (1) <= 0));
|
||||
|
||||
expect (! (5 <= Optional<int>()));
|
||||
expect (! (5 <= Optional<int> (1)));
|
||||
expect (1 <= Optional<int> (1));
|
||||
expect (0 <= Optional<int> (1));
|
||||
|
||||
expect (! (Optional<int>() > 5));
|
||||
expect (! (Optional<int> (1) > 5));
|
||||
expect (! (Optional<int> (1) > 1));
|
||||
expect (Optional<int> (1) > 0);
|
||||
|
||||
expect (5 > Optional<int>());
|
||||
expect (5 > Optional<int> (1));
|
||||
expect (! (1 > Optional<int> (1)));
|
||||
expect (! (0 > Optional<int> (1)));
|
||||
|
||||
expect (! (Optional<int>() >= 5));
|
||||
expect (! (Optional<int> (1) >= 5));
|
||||
expect (Optional<int> (1) >= 1);
|
||||
expect (Optional<int> (1) >= 0);
|
||||
|
||||
expect (5 >= Optional<int>());
|
||||
expect (5 >= Optional<int> (1));
|
||||
expect (1 >= Optional<int> (1));
|
||||
expect (! (0 >= Optional<int> (1)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static OptionalUnitTest optionalUnitTest;
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,142 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
static struct OwnedArrayTest : public UnitTest
|
||||
{
|
||||
struct Base
|
||||
{
|
||||
Base() = default;
|
||||
virtual ~Base() = default;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Base)
|
||||
};
|
||||
|
||||
struct Derived final : public Base
|
||||
{
|
||||
Derived() = default;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Derived)
|
||||
};
|
||||
|
||||
struct DestructorObj
|
||||
{
|
||||
DestructorObj (OwnedArrayTest& p,
|
||||
OwnedArray<DestructorObj>& arr)
|
||||
: parent (p), objectArray (arr)
|
||||
{}
|
||||
|
||||
~DestructorObj()
|
||||
{
|
||||
data = 0;
|
||||
|
||||
for (auto* o : objectArray)
|
||||
{
|
||||
parent.expect (o != nullptr);
|
||||
parent.expect (o != this);
|
||||
|
||||
if (o != nullptr)
|
||||
parent.expectEquals (o->data, 956);
|
||||
}
|
||||
}
|
||||
|
||||
OwnedArrayTest& parent;
|
||||
OwnedArray<DestructorObj>& objectArray;
|
||||
int data = 956;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DestructorObj)
|
||||
};
|
||||
|
||||
OwnedArrayTest()
|
||||
: UnitTest ("OwnedArray", UnitTestCategories::containers)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("After converting move construction, ownership is transferred");
|
||||
{
|
||||
OwnedArray<Derived> derived { new Derived{}, new Derived{}, new Derived{} };
|
||||
|
||||
OwnedArray<Base> base { std::move (derived) };
|
||||
|
||||
expectEquals (base.size(), 3);
|
||||
expectEquals (derived.size(), 0);
|
||||
}
|
||||
|
||||
beginTest ("After converting move assignment, ownership is transferred");
|
||||
{
|
||||
OwnedArray<Base> base;
|
||||
|
||||
base = OwnedArray<Derived> { new Derived{}, new Derived{}, new Derived{} };
|
||||
|
||||
expectEquals (base.size(), 3);
|
||||
}
|
||||
|
||||
beginTest ("Iterate in destructor");
|
||||
{
|
||||
{
|
||||
OwnedArray<DestructorObj> arr;
|
||||
|
||||
for (int i = 0; i < 2; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
}
|
||||
|
||||
OwnedArray<DestructorObj> arr;
|
||||
|
||||
for (int i = 0; i < 1025; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
|
||||
while (! arr.isEmpty())
|
||||
arr.remove (0);
|
||||
|
||||
for (int i = 0; i < 1025; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
|
||||
arr.removeRange (1, arr.size() - 3);
|
||||
|
||||
for (int i = 0; i < 1025; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
|
||||
arr.set (500, new DestructorObj (*this, arr));
|
||||
}
|
||||
}
|
||||
} ownedArrayTest;
|
||||
|
||||
#endif
|
||||
|
||||
}
|
||||
@@ -0,0 +1,890 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/** An array designed for holding objects.
|
||||
|
||||
This holds a list of pointers to objects, and will automatically
|
||||
delete the objects when they are removed from the array, or when the
|
||||
array is itself deleted.
|
||||
|
||||
Declare it in the form: OwnedArray<MyObjectClass>
|
||||
|
||||
...and then add new objects, e.g. myOwnedArray.add (new MyObjectClass());
|
||||
|
||||
After adding objects, they are 'owned' by the array and will be deleted when
|
||||
removed or replaced.
|
||||
|
||||
To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
|
||||
TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
|
||||
|
||||
@see Array, ReferenceCountedArray, StringArray, CriticalSection
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class ObjectClass,
|
||||
class TypeOfCriticalSectionToUse = DummyCriticalSection>
|
||||
class OwnedArray
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty array. */
|
||||
OwnedArray() = default;
|
||||
|
||||
/** Deletes the array and also deletes any objects inside it.
|
||||
|
||||
To get rid of the array without deleting its objects, use its
|
||||
clear (false) method before deleting it.
|
||||
*/
|
||||
~OwnedArray()
|
||||
{
|
||||
deleteAllObjects();
|
||||
}
|
||||
|
||||
/** Move constructor. */
|
||||
OwnedArray (OwnedArray&& other) noexcept
|
||||
: values (std::move (other.values))
|
||||
{
|
||||
}
|
||||
|
||||
/** Creates an array from a list of objects. */
|
||||
OwnedArray (const std::initializer_list<ObjectClass*>& items)
|
||||
{
|
||||
addArray (items);
|
||||
}
|
||||
|
||||
/** Move assignment operator. */
|
||||
OwnedArray& operator= (OwnedArray&& other) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
deleteAllObjects();
|
||||
values = std::move (other.values);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Converting move constructor. */
|
||||
template <class OtherObjectClass, class OtherCriticalSection>
|
||||
OwnedArray (OwnedArray<OtherObjectClass, OtherCriticalSection>&& other) noexcept
|
||||
: values (std::move (other.values))
|
||||
{
|
||||
}
|
||||
|
||||
/** Converting move assignment operator. */
|
||||
template <class OtherObjectClass, class OtherCriticalSection>
|
||||
OwnedArray& operator= (OwnedArray<OtherObjectClass, OtherCriticalSection>&& other) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
deleteAllObjects();
|
||||
values = std::move (other.values);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Clears the array, optionally deleting the objects inside it first. */
|
||||
void clear (bool deleteObjects = true)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
clearQuick (deleteObjects);
|
||||
values.setAllocatedSize (0);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Clears the array, optionally deleting the objects inside it first. */
|
||||
void clearQuick (bool deleteObjects)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (deleteObjects)
|
||||
deleteAllObjects();
|
||||
else
|
||||
values.clear();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of items currently in the array.
|
||||
@see operator[]
|
||||
*/
|
||||
inline int size() const noexcept
|
||||
{
|
||||
return values.size();
|
||||
}
|
||||
|
||||
/** Returns true if the array is empty, false otherwise. */
|
||||
inline bool isEmpty() const noexcept
|
||||
{
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/** Returns a pointer to the object at this index in the array.
|
||||
|
||||
If the index is out-of-range, this will return a null pointer, (and
|
||||
it could be null anyway, because it's ok for the array to hold null
|
||||
pointers as well as objects).
|
||||
|
||||
@see getUnchecked
|
||||
*/
|
||||
inline ObjectClass* operator[] (int index) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values.getValueWithDefault (index);
|
||||
}
|
||||
|
||||
/** Returns a pointer to the object at this index in the array, without checking whether the index is in-range.
|
||||
|
||||
This is a faster and less safe version of operator[] which doesn't check the index passed in, so
|
||||
it can be used when you're sure the index is always going to be legal.
|
||||
*/
|
||||
inline ObjectClass* getUnchecked (int index) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values[index];
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first object in the array.
|
||||
|
||||
This will return a null pointer if the array's empty.
|
||||
@see getLast
|
||||
*/
|
||||
inline ObjectClass* getFirst() const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values.getFirst();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the last object in the array.
|
||||
|
||||
This will return a null pointer if the array's empty.
|
||||
@see getFirst
|
||||
*/
|
||||
inline ObjectClass* getLast() const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values.getLast();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the actual array data.
|
||||
This pointer will only be valid until the next time a non-const method
|
||||
is called on the array.
|
||||
*/
|
||||
inline ObjectClass** getRawDataPointer() noexcept
|
||||
{
|
||||
return values.begin();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass** begin() noexcept
|
||||
{
|
||||
return values.begin();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass* const* begin() const noexcept
|
||||
{
|
||||
return values.begin();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the element which follows the last element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass** end() noexcept
|
||||
{
|
||||
return values.end();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the element which follows the last element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass* const* end() const noexcept
|
||||
{
|
||||
return values.end();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with the standard C++ containers.
|
||||
*/
|
||||
inline ObjectClass** data() noexcept
|
||||
{
|
||||
return begin();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with the standard C++ containers.
|
||||
*/
|
||||
inline ObjectClass* const* data() const noexcept
|
||||
{
|
||||
return begin();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Finds the index of an object which might be in the array.
|
||||
|
||||
@param objectToLookFor the object to look for
|
||||
@returns the index at which the object was found, or -1 if it's not found
|
||||
*/
|
||||
int indexOf (const ObjectClass* objectToLookFor) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto* e = values.begin();
|
||||
|
||||
for (; e != values.end(); ++e)
|
||||
if (objectToLookFor == *e)
|
||||
return static_cast<int> (e - values.begin());
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Returns true if the array contains a specified object.
|
||||
|
||||
@param objectToLookFor the object to look for
|
||||
@returns true if the object is in the array
|
||||
*/
|
||||
bool contains (const ObjectClass* objectToLookFor) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto* e = values.begin();
|
||||
|
||||
for (; e != values.end(); ++e)
|
||||
if (objectToLookFor == *e)
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Appends a new object to the end of the array.
|
||||
|
||||
Note that this object will be deleted by the OwnedArray when it is removed,
|
||||
so be careful not to delete it somewhere else.
|
||||
|
||||
Also be careful not to add the same object to the array more than once,
|
||||
as this will obviously cause deletion of dangling pointers.
|
||||
|
||||
@param newObject the new object to add to the array
|
||||
@returns the new object that was added
|
||||
@see set, insert, addSorted
|
||||
*/
|
||||
ObjectClass* add (ObjectClass* newObject)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.add (newObject);
|
||||
return newObject;
|
||||
}
|
||||
|
||||
/** Appends a new object to the end of the array.
|
||||
|
||||
Note that this object will be deleted by the OwnedArray when it is removed,
|
||||
so be careful not to delete it somewhere else.
|
||||
|
||||
Also be careful not to add the same object to the array more than once,
|
||||
as this will obviously cause deletion of dangling pointers.
|
||||
|
||||
@param newObject the new object to add to the array
|
||||
@returns the new object that was added
|
||||
@see set, insert, addSorted
|
||||
*/
|
||||
ObjectClass* add (std::unique_ptr<ObjectClass> newObject)
|
||||
{
|
||||
return add (newObject.release());
|
||||
}
|
||||
|
||||
/** Inserts a new object into the array at the given index.
|
||||
|
||||
Note that this object will be deleted by the OwnedArray when it is removed,
|
||||
so be careful not to delete it somewhere else.
|
||||
|
||||
If the index is less than 0 or greater than the size of the array, the
|
||||
element will be added to the end of the array.
|
||||
Otherwise, it will be inserted into the array, moving all the later elements
|
||||
along to make room.
|
||||
|
||||
Be careful not to add the same object to the array more than once,
|
||||
as this will obviously cause deletion of dangling pointers.
|
||||
|
||||
@param indexToInsertAt the index at which the new element should be inserted
|
||||
@param newObject the new object to add to the array
|
||||
@returns the new object that was added
|
||||
@see add, addSorted, set
|
||||
*/
|
||||
ObjectClass* insert (int indexToInsertAt, ObjectClass* newObject)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.insert (indexToInsertAt, newObject, 1);
|
||||
return newObject;
|
||||
}
|
||||
|
||||
/** Inserts a new object into the array at the given index.
|
||||
|
||||
Note that this object will be deleted by the OwnedArray when it is removed,
|
||||
so be careful not to delete it somewhere else.
|
||||
|
||||
If the index is less than 0 or greater than the size of the array, the
|
||||
element will be added to the end of the array.
|
||||
Otherwise, it will be inserted into the array, moving all the later elements
|
||||
along to make room.
|
||||
|
||||
Be careful not to add the same object to the array more than once,
|
||||
as this will obviously cause deletion of dangling pointers.
|
||||
|
||||
@param indexToInsertAt the index at which the new element should be inserted
|
||||
@param newObject the new object to add to the array
|
||||
@returns the new object that was added
|
||||
@see add, addSorted, set
|
||||
*/
|
||||
ObjectClass* insert (int indexToInsertAt, std::unique_ptr<ObjectClass> newObject)
|
||||
{
|
||||
return insert (indexToInsertAt, newObject.release());
|
||||
}
|
||||
|
||||
/** Inserts an array of values into this array at a given position.
|
||||
|
||||
If the index is less than 0 or greater than the size of the array, the
|
||||
new elements will be added to the end of the array.
|
||||
Otherwise, they will be inserted into the array, moving all the later elements
|
||||
along to make room.
|
||||
|
||||
@param indexToInsertAt the index at which the first new element should be inserted
|
||||
@param newObjects the new values to add to the array
|
||||
@param numberOfElements how many items are in the array
|
||||
@see insert, add, addSorted, set
|
||||
*/
|
||||
void insertArray (int indexToInsertAt,
|
||||
ObjectClass* const* newObjects,
|
||||
int numberOfElements)
|
||||
{
|
||||
if (numberOfElements > 0)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.insertArray (indexToInsertAt, newObjects, numberOfElements);
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces an object in the array with a different one.
|
||||
|
||||
If the index is less than zero, this method does nothing.
|
||||
If the index is beyond the end of the array, the new object is added to the end of the array.
|
||||
|
||||
Be careful not to add the same object to the array more than once,
|
||||
as this will obviously cause deletion of dangling pointers.
|
||||
|
||||
@param indexToChange the index whose value you want to change
|
||||
@param newObject the new value to set for this index.
|
||||
@param deleteOldElement whether to delete the object that's being replaced with the new one
|
||||
@see add, insert, remove
|
||||
*/
|
||||
ObjectClass* set (int indexToChange, ObjectClass* newObject, bool deleteOldElement = true)
|
||||
{
|
||||
if (indexToChange >= 0)
|
||||
{
|
||||
std::unique_ptr<ObjectClass> toDelete;
|
||||
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (indexToChange < values.size())
|
||||
{
|
||||
if (deleteOldElement)
|
||||
{
|
||||
toDelete.reset (values[indexToChange]);
|
||||
|
||||
if (toDelete.get() == newObject)
|
||||
toDelete.release();
|
||||
}
|
||||
|
||||
values[indexToChange] = newObject;
|
||||
}
|
||||
else
|
||||
{
|
||||
values.add (newObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
jassertfalse; // you're trying to set an object at a negative index, which doesn't have
|
||||
// any effect - but since the object is not being added, it may be leaking
|
||||
}
|
||||
|
||||
return newObject;
|
||||
}
|
||||
|
||||
/** Replaces an object in the array with a different one.
|
||||
|
||||
If the index is less than zero, this method does nothing.
|
||||
If the index is beyond the end of the array, the new object is added to the end of the array.
|
||||
|
||||
Be careful not to add the same object to the array more than once,
|
||||
as this will obviously cause deletion of dangling pointers.
|
||||
|
||||
@param indexToChange the index whose value you want to change
|
||||
@param newObject the new value to set for this index.
|
||||
@param deleteOldElement whether to delete the object that's being replaced with the new one
|
||||
@see add, insert, remove
|
||||
*/
|
||||
ObjectClass* set (int indexToChange, std::unique_ptr<ObjectClass> newObject, bool deleteOldElement = true)
|
||||
{
|
||||
return set (indexToChange, newObject.release(), deleteOldElement);
|
||||
}
|
||||
|
||||
/** Adds elements from another array to the end of this array.
|
||||
|
||||
@param arrayToAddFrom the array from which to copy the elements
|
||||
@param startIndex the first element of the other array to start copying from
|
||||
@param numElementsToAdd how many elements to add from the other array. If this
|
||||
value is negative or greater than the number of available elements,
|
||||
all available elements will be copied.
|
||||
@see add
|
||||
*/
|
||||
template <class OtherArrayType>
|
||||
void addArray (const OtherArrayType& arrayToAddFrom,
|
||||
int startIndex = 0,
|
||||
int numElementsToAdd = -1)
|
||||
{
|
||||
const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
|
||||
const ScopedLockType lock2 (getLock());
|
||||
values.addArray (arrayToAddFrom, startIndex, numElementsToAdd);
|
||||
}
|
||||
|
||||
/** Adds elements from another array to the end of this array. */
|
||||
template <typename OtherArrayType>
|
||||
void addArray (const std::initializer_list<OtherArrayType>& items)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.addArray (items);
|
||||
}
|
||||
|
||||
/** Adds copies of the elements in another array to the end of this array.
|
||||
|
||||
The other array must be either an OwnedArray of a compatible type of object, or an Array
|
||||
containing pointers to the same kind of object. The objects involved must provide
|
||||
a copy constructor, and this will be used to create new copies of each element, and
|
||||
add them to this array.
|
||||
|
||||
@param arrayToAddFrom the array from which to copy the elements
|
||||
@param startIndex the first element of the other array to start copying from
|
||||
@param numElementsToAdd how many elements to add from the other array. If this
|
||||
value is negative or greater than the number of available elements,
|
||||
all available elements will be copied.
|
||||
@see add
|
||||
*/
|
||||
template <class OtherArrayType>
|
||||
void addCopiesOf (const OtherArrayType& arrayToAddFrom,
|
||||
int startIndex = 0,
|
||||
int numElementsToAdd = -1)
|
||||
{
|
||||
const typename OtherArrayType::ScopedLockType lock1 (arrayToAddFrom.getLock());
|
||||
const ScopedLockType lock2 (getLock());
|
||||
|
||||
if (startIndex < 0)
|
||||
{
|
||||
jassertfalse;
|
||||
startIndex = 0;
|
||||
}
|
||||
|
||||
if (numElementsToAdd < 0 || startIndex + numElementsToAdd > arrayToAddFrom.size())
|
||||
numElementsToAdd = arrayToAddFrom.size() - startIndex;
|
||||
|
||||
jassert (numElementsToAdd >= 0);
|
||||
values.ensureAllocatedSize (values.size() + numElementsToAdd);
|
||||
|
||||
while (--numElementsToAdd >= 0)
|
||||
values.add (createCopyIfNotNull (arrayToAddFrom.getUnchecked (startIndex++)));
|
||||
}
|
||||
|
||||
/** Inserts a new object into the array assuming that the array is sorted.
|
||||
|
||||
This will use a comparator to find the position at which the new object
|
||||
should go. If the array isn't sorted, the behaviour of this
|
||||
method will be unpredictable.
|
||||
|
||||
@param comparator the comparator to use to compare the elements - see the sort method
|
||||
for details about this object's structure
|
||||
@param newObject the new object to insert to the array
|
||||
@returns the index at which the new object was added
|
||||
@see add, sort, indexOfSorted
|
||||
*/
|
||||
template <class ElementComparator>
|
||||
int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept;
|
||||
|
||||
/** Finds the index of an object in the array, assuming that the array is sorted.
|
||||
|
||||
This will use a comparator to do a binary-chop to find the index of the given
|
||||
element, if it exists. If the array isn't sorted, the behaviour of this
|
||||
method will be unpredictable.
|
||||
|
||||
@param comparator the comparator to use to compare the elements - see the sort()
|
||||
method for details about the form this object should take
|
||||
@param objectToLookFor the object to search for
|
||||
@returns the index of the element, or -1 if it's not found
|
||||
@see addSorted, sort
|
||||
*/
|
||||
template <typename ElementComparator>
|
||||
int indexOfSorted (ElementComparator& comparator, const ObjectClass* objectToLookFor) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Removes an object from the array.
|
||||
|
||||
This will remove the object at a given index (optionally also
|
||||
deleting it) and move back all the subsequent objects to close the gap.
|
||||
If the index passed in is out-of-range, nothing will happen.
|
||||
|
||||
@param indexToRemove the index of the element to remove
|
||||
@param deleteObject whether to delete the object that is removed
|
||||
@see removeObject, removeRange
|
||||
*/
|
||||
void remove (int indexToRemove, bool deleteObject = true)
|
||||
{
|
||||
std::unique_ptr<ObjectClass> toDelete;
|
||||
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (isPositiveAndBelow (indexToRemove, values.size()))
|
||||
{
|
||||
auto** e = values.begin() + indexToRemove;
|
||||
|
||||
if (deleteObject)
|
||||
toDelete.reset (*e);
|
||||
|
||||
values.removeElements (indexToRemove, 1);
|
||||
}
|
||||
}
|
||||
|
||||
if ((values.size() << 1) < values.capacity())
|
||||
minimiseStorageOverheads();
|
||||
}
|
||||
|
||||
/** Removes and returns an object from the array without deleting it.
|
||||
|
||||
This will remove the object at a given index and return it, moving back all
|
||||
the subsequent objects to close the gap. If the index passed in is out-of-range,
|
||||
nothing will happen.
|
||||
|
||||
@param indexToRemove the index of the element to remove
|
||||
@see remove, removeObject, removeRange
|
||||
*/
|
||||
ObjectClass* removeAndReturn (int indexToRemove)
|
||||
{
|
||||
ObjectClass* removedItem = nullptr;
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (isPositiveAndBelow (indexToRemove, values.size()))
|
||||
{
|
||||
removedItem = values[indexToRemove];
|
||||
|
||||
values.removeElements (indexToRemove, 1);
|
||||
|
||||
if ((values.size() << 1) < values.capacity())
|
||||
minimiseStorageOverheads();
|
||||
}
|
||||
|
||||
return removedItem;
|
||||
}
|
||||
|
||||
/** Removes a specified object from the array.
|
||||
|
||||
If the item isn't found, no action is taken.
|
||||
|
||||
@param objectToRemove the object to try to remove
|
||||
@param deleteObject whether to delete the object (if it's found)
|
||||
@see remove, removeRange
|
||||
*/
|
||||
void removeObject (const ObjectClass* objectToRemove, bool deleteObject = true)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
for (int i = 0; i < values.size(); ++i)
|
||||
{
|
||||
if (objectToRemove == values[i])
|
||||
{
|
||||
remove (i, deleteObject);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes a range of objects from the array.
|
||||
|
||||
This will remove a set of objects, starting from the given index,
|
||||
and move any subsequent elements down to close the gap.
|
||||
|
||||
If the range extends beyond the bounds of the array, it will
|
||||
be safely clipped to the size of the array.
|
||||
|
||||
@param startIndex the index of the first object to remove
|
||||
@param numberToRemove how many objects should be removed
|
||||
@param deleteObjects whether to delete the objects that get removed
|
||||
@see remove, removeObject
|
||||
*/
|
||||
void removeRange (int startIndex, int numberToRemove, bool deleteObjects = true)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto endIndex = jlimit (0, values.size(), startIndex + numberToRemove);
|
||||
startIndex = jlimit (0, values.size(), startIndex);
|
||||
numberToRemove = endIndex - startIndex;
|
||||
|
||||
if (numberToRemove > 0)
|
||||
{
|
||||
Array<ObjectClass*> objectsToDelete;
|
||||
|
||||
if (deleteObjects)
|
||||
objectsToDelete.addArray (values.begin() + startIndex, numberToRemove);
|
||||
|
||||
values.removeElements (startIndex, numberToRemove);
|
||||
|
||||
for (auto& o : objectsToDelete)
|
||||
ContainerDeletePolicy<ObjectClass>::destroy (o);
|
||||
|
||||
if ((values.size() << 1) < values.capacity())
|
||||
minimiseStorageOverheads();
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes the last n objects from the array.
|
||||
|
||||
@param howManyToRemove how many objects to remove from the end of the array
|
||||
@param deleteObjects whether to also delete the objects that are removed
|
||||
@see remove, removeObject, removeRange
|
||||
*/
|
||||
void removeLast (int howManyToRemove = 1,
|
||||
bool deleteObjects = true)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (howManyToRemove >= values.size())
|
||||
clear (deleteObjects);
|
||||
else
|
||||
removeRange (values.size() - howManyToRemove, howManyToRemove, deleteObjects);
|
||||
}
|
||||
|
||||
/** Swaps a pair of objects in the array.
|
||||
|
||||
If either of the indexes passed in is out-of-range, nothing will happen,
|
||||
otherwise the two objects at these positions will be exchanged.
|
||||
*/
|
||||
void swap (int index1, int index2) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.swap (index1, index2);
|
||||
}
|
||||
|
||||
/** Moves one of the objects to a different position.
|
||||
|
||||
This will move the object to a specified index, shuffling along
|
||||
any intervening elements as required.
|
||||
|
||||
So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
|
||||
move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
|
||||
|
||||
@param currentIndex the index of the object to be moved. If this isn't a
|
||||
valid index, then nothing will be done
|
||||
@param newIndex the index at which you'd like this object to end up. If this
|
||||
is less than zero, it will be moved to the end of the array
|
||||
*/
|
||||
void move (int currentIndex, int newIndex) noexcept
|
||||
{
|
||||
if (currentIndex != newIndex)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.move (currentIndex, newIndex);
|
||||
}
|
||||
}
|
||||
|
||||
/** This swaps the contents of this array with those of another array.
|
||||
|
||||
If you need to exchange two arrays, this is vastly quicker than using copy-by-value
|
||||
because it just swaps their internal pointers.
|
||||
*/
|
||||
template <class OtherArrayType>
|
||||
void swapWith (OtherArrayType& otherArray) noexcept
|
||||
{
|
||||
const ScopedLockType lock1 (getLock());
|
||||
const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
|
||||
values.swapWith (otherArray.values);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Reduces the amount of storage being used by the array.
|
||||
|
||||
Arrays typically allocate slightly more storage than they need, and after
|
||||
removing elements, they may have quite a lot of unused space allocated.
|
||||
This method will reduce the amount of allocated storage to a minimum.
|
||||
*/
|
||||
void minimiseStorageOverheads() noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.shrinkToNoMoreThan (values.size());
|
||||
}
|
||||
|
||||
/** Increases the array's internal storage to hold a minimum number of elements.
|
||||
|
||||
Calling this before adding a large known number of elements means that
|
||||
the array won't have to keep dynamically resizing itself as the elements
|
||||
are added, and it'll therefore be more efficient.
|
||||
*/
|
||||
void ensureStorageAllocated (int minNumElements) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.ensureAllocatedSize (minNumElements);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Sorts the elements in the array.
|
||||
|
||||
This will use a comparator object to sort the elements into order. The object
|
||||
passed must have a method of the form:
|
||||
@code
|
||||
int compareElements (ElementType* first, ElementType* second);
|
||||
@endcode
|
||||
|
||||
...and this method must return:
|
||||
- a value of < 0 if the first comes before the second
|
||||
- a value of 0 if the two objects are equivalent
|
||||
- a value of > 0 if the second comes before the first
|
||||
|
||||
To improve performance, the compareElements() method can be declared as static or const.
|
||||
|
||||
@param comparator the comparator to use for comparing elements.
|
||||
@param retainOrderOfEquivalentItems if this is true, then items
|
||||
which the comparator says are equivalent will be
|
||||
kept in the order in which they currently appear
|
||||
in the array. This is slower to perform, but may
|
||||
be important in some cases. If it's false, a faster
|
||||
algorithm is used, but equivalent elements may be
|
||||
rearranged.
|
||||
@see sortArray, indexOfSorted
|
||||
*/
|
||||
template <class ElementComparator>
|
||||
void sort (ElementComparator& comparator, bool retainOrderOfEquivalentItems = false) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the CriticalSection that locks this array.
|
||||
To lock, you can call getLock().enter() and getLock().exit(), or preferably use
|
||||
an object of ScopedLockType as an RAII lock for it.
|
||||
*/
|
||||
inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return values; }
|
||||
|
||||
/** Returns the type of scoped lock to use for locking this array */
|
||||
using ScopedLockType = typename TypeOfCriticalSectionToUse::ScopedLockType;
|
||||
|
||||
//==============================================================================
|
||||
/** @cond */
|
||||
[[deprecated ("This method has been replaced by a more flexible templated version and renamed "
|
||||
"to swapWith to be more consistent with the names used in other classes.")]]
|
||||
void swapWithArray (OwnedArray& other) noexcept { swapWith (other); }
|
||||
/** @endcond */
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
ArrayBase <ObjectClass*, TypeOfCriticalSectionToUse> values;
|
||||
|
||||
void deleteAllObjects()
|
||||
{
|
||||
auto i = values.size();
|
||||
|
||||
while (--i >= 0)
|
||||
{
|
||||
auto* e = values[i];
|
||||
values.removeElements (i, 1);
|
||||
ContainerDeletePolicy<ObjectClass>::destroy (e);
|
||||
}
|
||||
}
|
||||
|
||||
template <class OtherObjectClass, class OtherCriticalSection>
|
||||
friend class OwnedArray;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (OwnedArray)
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
template <class ObjectClass, class TypeOfCriticalSectionToUse>
|
||||
template <class ElementComparator>
|
||||
int OwnedArray<ObjectClass, TypeOfCriticalSectionToUse>::addSorted (
|
||||
[[maybe_unused]] ElementComparator& comparator,
|
||||
ObjectClass* newObject) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto index = findInsertIndexInSortedArray (comparator, values.begin(), newObject, 0, values.size());
|
||||
insert (index, newObject);
|
||||
return index;
|
||||
}
|
||||
|
||||
template <class ObjectClass, class TypeOfCriticalSectionToUse>
|
||||
template <typename ElementComparator>
|
||||
int OwnedArray<ObjectClass, TypeOfCriticalSectionToUse>::indexOfSorted (
|
||||
[[maybe_unused]] ElementComparator& comparator,
|
||||
const ObjectClass* objectToLookFor) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
int s = 0, e = values.size();
|
||||
|
||||
while (s < e)
|
||||
{
|
||||
if (comparator.compareElements (objectToLookFor, values[s]) == 0)
|
||||
return s;
|
||||
|
||||
auto halfway = (s + e) / 2;
|
||||
|
||||
if (halfway == s)
|
||||
break;
|
||||
|
||||
if (comparator.compareElements (objectToLookFor, values[halfway]) >= 0)
|
||||
s = halfway;
|
||||
else
|
||||
e = halfway;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
template <class ObjectClass, class TypeOfCriticalSectionToUse>
|
||||
template <typename ElementComparator>
|
||||
void OwnedArray<ObjectClass, TypeOfCriticalSectionToUse>::sort (
|
||||
[[maybe_unused]] ElementComparator& comparator,
|
||||
bool retainOrderOfEquivalentItems) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (size() > 1)
|
||||
sortArray (comparator, values.begin(), 0, size() - 1, retainOrderOfEquivalentItems);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,229 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
PropertySet::PropertySet (bool ignoreCaseOfKeyNames)
|
||||
: properties (ignoreCaseOfKeyNames),
|
||||
fallbackProperties (nullptr),
|
||||
ignoreCaseOfKeys (ignoreCaseOfKeyNames)
|
||||
{
|
||||
}
|
||||
|
||||
PropertySet::PropertySet (const PropertySet& other)
|
||||
: properties (other.properties),
|
||||
fallbackProperties (other.fallbackProperties),
|
||||
ignoreCaseOfKeys (other.ignoreCaseOfKeys)
|
||||
{
|
||||
}
|
||||
|
||||
PropertySet& PropertySet::operator= (const PropertySet& other)
|
||||
{
|
||||
properties = other.properties;
|
||||
fallbackProperties = other.fallbackProperties;
|
||||
ignoreCaseOfKeys = other.ignoreCaseOfKeys;
|
||||
|
||||
propertyChanged();
|
||||
return *this;
|
||||
}
|
||||
|
||||
PropertySet::~PropertySet()
|
||||
{
|
||||
}
|
||||
|
||||
void PropertySet::clear()
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
if (properties.size() > 0)
|
||||
{
|
||||
properties.clear();
|
||||
propertyChanged();
|
||||
}
|
||||
}
|
||||
|
||||
String PropertySet::getValue (StringRef keyName, const String& defaultValue) const noexcept
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
auto index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
|
||||
|
||||
if (index >= 0)
|
||||
return properties.getAllValues() [index];
|
||||
|
||||
return fallbackProperties != nullptr ? fallbackProperties->getValue (keyName, defaultValue)
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
int PropertySet::getIntValue (StringRef keyName, int defaultValue) const noexcept
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
auto index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
|
||||
|
||||
if (index >= 0)
|
||||
return properties.getAllValues() [index].getIntValue();
|
||||
|
||||
return fallbackProperties != nullptr ? fallbackProperties->getIntValue (keyName, defaultValue)
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
double PropertySet::getDoubleValue (StringRef keyName, double defaultValue) const noexcept
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
auto index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
|
||||
|
||||
if (index >= 0)
|
||||
return properties.getAllValues()[index].getDoubleValue();
|
||||
|
||||
return fallbackProperties != nullptr ? fallbackProperties->getDoubleValue (keyName, defaultValue)
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
bool PropertySet::getBoolValue (StringRef keyName, bool defaultValue) const noexcept
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
auto index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
|
||||
|
||||
if (index >= 0)
|
||||
return properties.getAllValues() [index].getIntValue() != 0;
|
||||
|
||||
return fallbackProperties != nullptr ? fallbackProperties->getBoolValue (keyName, defaultValue)
|
||||
: defaultValue;
|
||||
}
|
||||
|
||||
std::unique_ptr<XmlElement> PropertySet::getXmlValue (StringRef keyName) const
|
||||
{
|
||||
return parseXML (getValue (keyName));
|
||||
}
|
||||
|
||||
void PropertySet::setValue (StringRef keyName, const var& v)
|
||||
{
|
||||
jassert (keyName.isNotEmpty()); // shouldn't use an empty key name!
|
||||
|
||||
if (keyName.isNotEmpty())
|
||||
{
|
||||
auto value = v.toString();
|
||||
const ScopedLock sl (lock);
|
||||
auto index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
|
||||
|
||||
if (index < 0 || properties.getAllValues() [index] != value)
|
||||
{
|
||||
properties.set (keyName, value);
|
||||
propertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PropertySet::removeValue (StringRef keyName)
|
||||
{
|
||||
if (keyName.isNotEmpty())
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
auto index = properties.getAllKeys().indexOf (keyName, ignoreCaseOfKeys);
|
||||
|
||||
if (index >= 0)
|
||||
{
|
||||
properties.remove (keyName);
|
||||
propertyChanged();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void PropertySet::setValue (StringRef keyName, const XmlElement* xml)
|
||||
{
|
||||
setValue (keyName, xml == nullptr ? var()
|
||||
: var (xml->toString (XmlElement::TextFormat().singleLine().withoutHeader())));
|
||||
}
|
||||
|
||||
bool PropertySet::containsKey (StringRef keyName) const noexcept
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
return properties.getAllKeys().contains (keyName, ignoreCaseOfKeys);
|
||||
}
|
||||
|
||||
void PropertySet::addAllPropertiesFrom (const PropertySet& source)
|
||||
{
|
||||
const ScopedLock sl (source.getLock());
|
||||
|
||||
for (int i = 0; i < source.properties.size(); ++i)
|
||||
setValue (source.properties.getAllKeys() [i],
|
||||
source.properties.getAllValues() [i]);
|
||||
}
|
||||
|
||||
void PropertySet::setFallbackPropertySet (PropertySet* fallbackProperties_) noexcept
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
fallbackProperties = fallbackProperties_;
|
||||
}
|
||||
|
||||
std::unique_ptr<XmlElement> PropertySet::createXml (const String& nodeName) const
|
||||
{
|
||||
auto xml = std::make_unique<XmlElement> (nodeName);
|
||||
|
||||
const ScopedLock sl (lock);
|
||||
|
||||
for (int i = 0; i < properties.getAllKeys().size(); ++i)
|
||||
{
|
||||
auto e = xml->createNewChildElement ("VALUE");
|
||||
e->setAttribute ("name", properties.getAllKeys()[i]);
|
||||
e->setAttribute ("val", properties.getAllValues()[i]);
|
||||
}
|
||||
|
||||
return xml;
|
||||
}
|
||||
|
||||
void PropertySet::restoreFromXml (const XmlElement& xml)
|
||||
{
|
||||
const ScopedLock sl (lock);
|
||||
clear();
|
||||
|
||||
for (auto* e : xml.getChildWithTagNameIterator ("VALUE"))
|
||||
{
|
||||
if (e->hasAttribute ("name")
|
||||
&& e->hasAttribute ("val"))
|
||||
{
|
||||
properties.set (e->getStringAttribute ("name"),
|
||||
e->getStringAttribute ("val"));
|
||||
}
|
||||
}
|
||||
|
||||
if (properties.size() > 0)
|
||||
propertyChanged();
|
||||
}
|
||||
|
||||
void PropertySet::propertyChanged()
|
||||
{
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,217 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A set of named property values, which can be strings, integers, floating point, etc.
|
||||
|
||||
Effectively, this just wraps a StringPairArray in an interface that makes it easier
|
||||
to load and save types other than strings.
|
||||
|
||||
See the PropertiesFile class for a subclass of this, which automatically broadcasts change
|
||||
messages and saves/loads the list from a file.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API PropertySet
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty PropertySet.
|
||||
@param ignoreCaseOfKeyNames if true, the names of properties are compared in a
|
||||
case-insensitive way
|
||||
*/
|
||||
PropertySet (bool ignoreCaseOfKeyNames = false);
|
||||
|
||||
/** Creates a copy of another PropertySet. */
|
||||
PropertySet (const PropertySet& other);
|
||||
|
||||
/** Copies another PropertySet over this one. */
|
||||
PropertySet& operator= (const PropertySet& other);
|
||||
|
||||
/** Destructor. */
|
||||
virtual ~PropertySet();
|
||||
|
||||
//==============================================================================
|
||||
/** Returns one of the properties as a string.
|
||||
|
||||
If the value isn't found in this set, then this will look for it in a fallback
|
||||
property set (if you've specified one with the setFallbackPropertySet() method),
|
||||
and if it can't find one there, it'll return the default value passed-in.
|
||||
|
||||
@param keyName the name of the property to retrieve
|
||||
@param defaultReturnValue a value to return if the named property doesn't actually exist
|
||||
*/
|
||||
String getValue (StringRef keyName, const String& defaultReturnValue = String()) const noexcept;
|
||||
|
||||
/** Returns one of the properties as an integer.
|
||||
|
||||
If the value isn't found in this set, then this will look for it in a fallback
|
||||
property set (if you've specified one with the setFallbackPropertySet() method),
|
||||
and if it can't find one there, it'll return the default value passed-in.
|
||||
|
||||
@param keyName the name of the property to retrieve
|
||||
@param defaultReturnValue a value to return if the named property doesn't actually exist
|
||||
*/
|
||||
int getIntValue (StringRef keyName, int defaultReturnValue = 0) const noexcept;
|
||||
|
||||
/** Returns one of the properties as an double.
|
||||
|
||||
If the value isn't found in this set, then this will look for it in a fallback
|
||||
property set (if you've specified one with the setFallbackPropertySet() method),
|
||||
and if it can't find one there, it'll return the default value passed-in.
|
||||
|
||||
@param keyName the name of the property to retrieve
|
||||
@param defaultReturnValue a value to return if the named property doesn't actually exist
|
||||
*/
|
||||
double getDoubleValue (StringRef keyName, double defaultReturnValue = 0.0) const noexcept;
|
||||
|
||||
/** Returns one of the properties as an boolean.
|
||||
|
||||
The result will be true if the string found for this key name can be parsed as a non-zero
|
||||
integer.
|
||||
|
||||
If the value isn't found in this set, then this will look for it in a fallback
|
||||
property set (if you've specified one with the setFallbackPropertySet() method),
|
||||
and if it can't find one there, it'll return the default value passed-in.
|
||||
|
||||
@param keyName the name of the property to retrieve
|
||||
@param defaultReturnValue a value to return if the named property doesn't actually exist
|
||||
*/
|
||||
bool getBoolValue (StringRef keyName, bool defaultReturnValue = false) const noexcept;
|
||||
|
||||
/** Returns one of the properties as an XML element.
|
||||
|
||||
The result will a new XMLElement object. It may return nullptr if the key isn't found,
|
||||
or if the entry contains an string that isn't valid XML.
|
||||
|
||||
If the value isn't found in this set, then this will look for it in a fallback
|
||||
property set (if you've specified one with the setFallbackPropertySet() method),
|
||||
and if it can't find one there, it'll return the default value passed-in.
|
||||
|
||||
@param keyName the name of the property to retrieve
|
||||
*/
|
||||
std::unique_ptr<XmlElement> getXmlValue (StringRef keyName) const;
|
||||
|
||||
//==============================================================================
|
||||
/** Sets a named property.
|
||||
|
||||
@param keyName the name of the property to set. (This mustn't be an empty string)
|
||||
@param value the new value to set it to
|
||||
*/
|
||||
void setValue (StringRef keyName, const var& value);
|
||||
|
||||
/** Sets a named property to an XML element.
|
||||
|
||||
@param keyName the name of the property to set. (This mustn't be an empty string)
|
||||
@param xml the new element to set it to. If this is a nullptr, the value will
|
||||
be set to an empty string
|
||||
@see getXmlValue
|
||||
*/
|
||||
void setValue (StringRef keyName, const XmlElement* xml);
|
||||
|
||||
/** This copies all the values from a source PropertySet to this one.
|
||||
This won't remove any existing settings, it just adds any that it finds in the source set.
|
||||
*/
|
||||
void addAllPropertiesFrom (const PropertySet& source);
|
||||
|
||||
//==============================================================================
|
||||
/** Deletes a property.
|
||||
@param keyName the name of the property to delete. (This mustn't be an empty string)
|
||||
*/
|
||||
void removeValue (StringRef keyName);
|
||||
|
||||
/** Returns true if the properties include the given key. */
|
||||
bool containsKey (StringRef keyName) const noexcept;
|
||||
|
||||
/** Removes all values. */
|
||||
void clear();
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the keys/value pair array containing all the properties. */
|
||||
StringPairArray& getAllProperties() noexcept { return properties; }
|
||||
|
||||
/** Returns the lock used when reading or writing to this set */
|
||||
const CriticalSection& getLock() const noexcept { return lock; }
|
||||
|
||||
//==============================================================================
|
||||
/** Returns an XML element which encapsulates all the items in this property set.
|
||||
The string parameter is the tag name that should be used for the node.
|
||||
@see restoreFromXml
|
||||
*/
|
||||
std::unique_ptr<XmlElement> createXml (const String& nodeName) const;
|
||||
|
||||
/** Reloads a set of properties that were previously stored as XML.
|
||||
The node passed in must have been created by the createXml() method.
|
||||
@see createXml
|
||||
*/
|
||||
void restoreFromXml (const XmlElement& xml);
|
||||
|
||||
//==============================================================================
|
||||
/** Sets up a second PropertySet that will be used to look up any values that aren't
|
||||
set in this one.
|
||||
|
||||
If you set this up to be a pointer to a second property set, then whenever one
|
||||
of the getValue() methods fails to find an entry in this set, it will look up that
|
||||
value in the fallback set, and if it finds it, it will return that.
|
||||
|
||||
Make sure that you don't delete the fallback set while it's still being used by
|
||||
another set! To remove the fallback set, just call this method with a null pointer.
|
||||
|
||||
@see getFallbackPropertySet
|
||||
*/
|
||||
void setFallbackPropertySet (PropertySet* fallbackProperties) noexcept;
|
||||
|
||||
/** Returns the fallback property set.
|
||||
@see setFallbackPropertySet
|
||||
*/
|
||||
PropertySet* getFallbackPropertySet() const noexcept { return fallbackProperties; }
|
||||
|
||||
protected:
|
||||
/** Subclasses can override this to be told when one of the properties has been changed. */
|
||||
virtual void propertyChanged();
|
||||
|
||||
private:
|
||||
StringPairArray properties;
|
||||
PropertySet* fallbackProperties;
|
||||
CriticalSection lock;
|
||||
bool ignoreCaseOfKeys;
|
||||
|
||||
JUCE_LEAK_DETECTOR (PropertySet)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,191 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class ReferenceCountedArrayTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
ReferenceCountedArrayTests()
|
||||
: UnitTest ("ReferenceCountedArray", UnitTestCategories::containers)
|
||||
{}
|
||||
|
||||
//==============================================================================
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("Add derived objects");
|
||||
{
|
||||
ReferenceCountedArray<TestDerivedObj> derivedArray;
|
||||
derivedArray.add (static_cast<TestDerivedObj*> (new TestBaseObj()));
|
||||
expectEquals (derivedArray.size(), 1);
|
||||
expectEquals (derivedArray.getObjectPointer (0)->getReferenceCount(), 1);
|
||||
expectEquals (derivedArray[0]->getReferenceCount(), 2);
|
||||
|
||||
for (auto o : derivedArray)
|
||||
expectEquals (o->getReferenceCount(), 1);
|
||||
|
||||
ReferenceCountedArray<TestBaseObj> baseArray;
|
||||
baseArray.addArray (derivedArray);
|
||||
|
||||
for (auto o : baseArray)
|
||||
expectEquals (o->getReferenceCount(), 2);
|
||||
|
||||
derivedArray.clearQuick();
|
||||
baseArray.clearQuick();
|
||||
|
||||
auto* baseObject = new TestBaseObj();
|
||||
TestBaseObj::Ptr baseObjectPtr = baseObject;
|
||||
expectEquals (baseObject->getReferenceCount(), 1);
|
||||
|
||||
auto* derivedObject = new TestDerivedObj();
|
||||
TestDerivedObj::Ptr derivedObjectPtr = derivedObject;
|
||||
expectEquals (derivedObject->getReferenceCount(), 1);
|
||||
|
||||
baseArray.add (baseObject);
|
||||
baseArray.add (derivedObject);
|
||||
|
||||
for (auto o : baseArray)
|
||||
expectEquals (o->getReferenceCount(), 2);
|
||||
|
||||
expectEquals (baseObject->getReferenceCount(), 2);
|
||||
expectEquals (derivedObject->getReferenceCount(), 2);
|
||||
|
||||
derivedArray.add (derivedObject);
|
||||
|
||||
for (auto o : derivedArray)
|
||||
expectEquals (o->getReferenceCount(), 3);
|
||||
|
||||
derivedArray.clearQuick();
|
||||
baseArray.clearQuick();
|
||||
|
||||
expectEquals (baseObject->getReferenceCount(), 1);
|
||||
expectEquals (derivedObject->getReferenceCount(), 1);
|
||||
|
||||
baseArray.add (baseObjectPtr);
|
||||
baseArray.add (derivedObjectPtr.get());
|
||||
|
||||
for (auto o : baseArray)
|
||||
expectEquals (o->getReferenceCount(), 2);
|
||||
|
||||
derivedArray.add (derivedObjectPtr);
|
||||
|
||||
for (auto o : derivedArray)
|
||||
expectEquals (o->getReferenceCount(), 3);
|
||||
}
|
||||
|
||||
beginTest ("Iterate in destructor");
|
||||
{
|
||||
{
|
||||
ReferenceCountedArray<DestructorObj> arr;
|
||||
|
||||
for (int i = 0; i < 2; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
}
|
||||
|
||||
ReferenceCountedArray<DestructorObj> arr;
|
||||
|
||||
for (int i = 0; i < 1025; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
|
||||
while (! arr.isEmpty())
|
||||
arr.remove (0);
|
||||
|
||||
for (int i = 0; i < 1025; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
|
||||
arr.removeRange (1, arr.size() - 3);
|
||||
|
||||
for (int i = 0; i < 1025; ++i)
|
||||
arr.add (new DestructorObj (*this, arr));
|
||||
|
||||
arr.set (500, new DestructorObj (*this, arr));
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
struct TestBaseObj : public ReferenceCountedObject
|
||||
{
|
||||
using Ptr = ReferenceCountedObjectPtr<TestBaseObj>;
|
||||
|
||||
TestBaseObj() = default;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TestBaseObj)
|
||||
};
|
||||
|
||||
struct TestDerivedObj final : public TestBaseObj
|
||||
{
|
||||
using Ptr = ReferenceCountedObjectPtr<TestDerivedObj>;
|
||||
|
||||
TestDerivedObj() = default;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TestDerivedObj)
|
||||
};
|
||||
|
||||
struct DestructorObj final : public ReferenceCountedObject
|
||||
{
|
||||
DestructorObj (ReferenceCountedArrayTests& p,
|
||||
ReferenceCountedArray<DestructorObj>& arr)
|
||||
: parent (p), objectArray (arr)
|
||||
{}
|
||||
|
||||
~DestructorObj()
|
||||
{
|
||||
data = 0;
|
||||
|
||||
for (auto* o : objectArray)
|
||||
{
|
||||
parent.expect (o != nullptr);
|
||||
parent.expect (o != this);
|
||||
|
||||
if (o != nullptr)
|
||||
parent.expectEquals (o->data, 374);
|
||||
}
|
||||
}
|
||||
|
||||
ReferenceCountedArrayTests& parent;
|
||||
ReferenceCountedArray<DestructorObj>& objectArray;
|
||||
int data = 374;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (DestructorObj)
|
||||
};
|
||||
};
|
||||
|
||||
static ReferenceCountedArrayTests referenceCountedArrayTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,925 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Holds a list of objects derived from ReferenceCountedObject, or which implement basic
|
||||
reference-count handling methods.
|
||||
|
||||
The template parameter specifies the class of the object you want to point to - the easiest
|
||||
way to make a class reference-countable is to simply make it inherit from ReferenceCountedObject
|
||||
or SingleThreadedReferenceCountedObject, but if you need to, you can roll your own reference-countable
|
||||
class by implementing a set of methods called incReferenceCount(), decReferenceCount(), and
|
||||
decReferenceCountWithoutDeleting(). See ReferenceCountedObject for examples of how these methods
|
||||
should behave.
|
||||
|
||||
A ReferenceCountedArray holds objects derived from ReferenceCountedObject,
|
||||
and takes care of incrementing and decrementing their ref counts when they
|
||||
are added and removed from the array.
|
||||
|
||||
To make all the array's methods thread-safe, pass in "CriticalSection" as the templated
|
||||
TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
|
||||
|
||||
@see Array, OwnedArray, StringArray
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class ObjectClass, class TypeOfCriticalSectionToUse = DummyCriticalSection>
|
||||
class ReferenceCountedArray
|
||||
{
|
||||
public:
|
||||
using ObjectClassPtr = ReferenceCountedObjectPtr<ObjectClass>;
|
||||
|
||||
//==============================================================================
|
||||
/** Creates an empty array.
|
||||
@see ReferenceCountedObject, Array, OwnedArray
|
||||
*/
|
||||
ReferenceCountedArray() = default;
|
||||
|
||||
/** Creates a copy of another array */
|
||||
ReferenceCountedArray (const ReferenceCountedArray& other) noexcept
|
||||
{
|
||||
const ScopedLockType lock (other.getLock());
|
||||
values.addArray (other.begin(), other.size());
|
||||
|
||||
for (auto* o : *this)
|
||||
if (o != nullptr)
|
||||
o->incReferenceCount();
|
||||
}
|
||||
|
||||
/** Moves from another array */
|
||||
ReferenceCountedArray (ReferenceCountedArray&& other) noexcept
|
||||
: values (std::move (other.values))
|
||||
{
|
||||
}
|
||||
|
||||
/** Creates a copy of another array */
|
||||
template <class OtherObjectClass, class OtherCriticalSection>
|
||||
ReferenceCountedArray (const ReferenceCountedArray<OtherObjectClass, OtherCriticalSection>& other) noexcept
|
||||
{
|
||||
const typename ReferenceCountedArray<OtherObjectClass, OtherCriticalSection>::ScopedLockType lock (other.getLock());
|
||||
values.addArray (other.begin(), other.size());
|
||||
|
||||
for (auto* o : *this)
|
||||
if (o != nullptr)
|
||||
o->incReferenceCount();
|
||||
}
|
||||
|
||||
/** Copies another array into this one.
|
||||
Any existing objects in this array will first be released.
|
||||
*/
|
||||
ReferenceCountedArray& operator= (const ReferenceCountedArray& other) noexcept
|
||||
{
|
||||
releaseAllObjects();
|
||||
auto otherCopy = other;
|
||||
swapWith (otherCopy);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Copies another array into this one.
|
||||
Any existing objects in this array will first be released.
|
||||
*/
|
||||
template <class OtherObjectClass>
|
||||
ReferenceCountedArray& operator= (const ReferenceCountedArray<OtherObjectClass, TypeOfCriticalSectionToUse>& other) noexcept
|
||||
{
|
||||
auto otherCopy = other;
|
||||
swapWith (otherCopy);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Moves from another array */
|
||||
ReferenceCountedArray& operator= (ReferenceCountedArray&& other) noexcept
|
||||
{
|
||||
releaseAllObjects();
|
||||
values = std::move (other.values);
|
||||
return *this;
|
||||
}
|
||||
|
||||
/** Destructor.
|
||||
Any objects in the array will be released, and may be deleted if not referenced from elsewhere.
|
||||
*/
|
||||
~ReferenceCountedArray()
|
||||
{
|
||||
releaseAllObjects();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Removes all objects from the array.
|
||||
Any objects in the array whose reference counts drop to zero will be deleted.
|
||||
*/
|
||||
void clear()
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
clearQuick();
|
||||
values.setAllocatedSize (0);
|
||||
}
|
||||
|
||||
/** Removes all objects from the array without freeing the array's allocated storage.
|
||||
Any objects in the array that whose reference counts drop to zero will be deleted.
|
||||
@see clear
|
||||
*/
|
||||
void clearQuick()
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
releaseAllObjects();
|
||||
}
|
||||
|
||||
/** Returns the current number of objects in the array. */
|
||||
inline int size() const noexcept
|
||||
{
|
||||
return values.size();
|
||||
}
|
||||
|
||||
/** Returns true if the array is empty, false otherwise. */
|
||||
inline bool isEmpty() const noexcept
|
||||
{
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/** Returns a pointer to the object at this index in the array.
|
||||
|
||||
If the index is out-of-range, this will return a null pointer, (and
|
||||
it could be null anyway, because it's ok for the array to hold null
|
||||
pointers as well as objects).
|
||||
|
||||
@see getUnchecked
|
||||
*/
|
||||
inline ObjectClassPtr operator[] (int index) const noexcept
|
||||
{
|
||||
return ObjectClassPtr (getObjectPointer (index));
|
||||
}
|
||||
|
||||
/** Returns a pointer to the object at this index in the array, without checking
|
||||
whether the index is in-range.
|
||||
|
||||
This is a faster and less safe version of operator[] which doesn't check the index passed in, so
|
||||
it can be used when you're sure the index is always going to be legal.
|
||||
*/
|
||||
inline ObjectClassPtr getUnchecked (int index) const noexcept
|
||||
{
|
||||
return ObjectClassPtr (getObjectPointerUnchecked (index));
|
||||
}
|
||||
|
||||
/** Returns a raw pointer to the object at this index in the array.
|
||||
|
||||
If the index is out-of-range, this will return a null pointer, (and
|
||||
it could be null anyway, because it's ok for the array to hold null
|
||||
pointers as well as objects).
|
||||
|
||||
@see getUnchecked
|
||||
*/
|
||||
inline ObjectClass* getObjectPointer (int index) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values.getValueWithDefault (index);
|
||||
}
|
||||
|
||||
/** Returns a raw pointer to the object at this index in the array, without checking
|
||||
whether the index is in-range.
|
||||
*/
|
||||
inline ObjectClass* getObjectPointerUnchecked (int index) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values[index];
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first object in the array.
|
||||
|
||||
This will return a null pointer if the array's empty.
|
||||
@see getLast
|
||||
*/
|
||||
inline ObjectClassPtr getFirst() const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values.getFirst();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the last object in the array.
|
||||
|
||||
This will return a null pointer if the array's empty.
|
||||
@see getFirst
|
||||
*/
|
||||
inline ObjectClassPtr getLast() const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
return values.getLast();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the actual array data.
|
||||
This pointer will only be valid until the next time a non-const method
|
||||
is called on the array.
|
||||
*/
|
||||
inline ObjectClass** getRawDataPointer() const noexcept
|
||||
{
|
||||
return values.begin();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass** begin() noexcept
|
||||
{
|
||||
return values.begin();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass* const* begin() const noexcept
|
||||
{
|
||||
return values.begin();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the element which follows the last element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass** end() noexcept
|
||||
{
|
||||
return values.end();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the element which follows the last element in the array.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline ObjectClass* const* end() const noexcept
|
||||
{
|
||||
return values.end();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with the standard C++ containers.
|
||||
*/
|
||||
inline ObjectClass** data() noexcept
|
||||
{
|
||||
return begin();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the first element in the array.
|
||||
This method is provided for compatibility with the standard C++ containers.
|
||||
*/
|
||||
inline ObjectClass* const* data() const noexcept
|
||||
{
|
||||
return begin();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Finds the index of the first occurrence of an object in the array.
|
||||
|
||||
@param objectToLookFor the object to look for
|
||||
@returns the index at which the object was found, or -1 if it's not found
|
||||
*/
|
||||
int indexOf (const ObjectClass* objectToLookFor) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto* e = values.begin();
|
||||
auto* endPointer = values.end();
|
||||
|
||||
while (e != endPointer)
|
||||
{
|
||||
if (objectToLookFor == *e)
|
||||
return static_cast<int> (e - values.begin());
|
||||
|
||||
++e;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
/** Finds the index of the first occurrence of an object in the array.
|
||||
|
||||
@param objectToLookFor the object to look for
|
||||
@returns the index at which the object was found, or -1 if it's not found
|
||||
*/
|
||||
int indexOf (const ObjectClassPtr& objectToLookFor) const noexcept { return indexOf (objectToLookFor.get()); }
|
||||
|
||||
/** Returns true if the array contains a specified object.
|
||||
|
||||
@param objectToLookFor the object to look for
|
||||
@returns true if the object is in the array
|
||||
*/
|
||||
bool contains (const ObjectClass* objectToLookFor) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto* e = values.begin();
|
||||
auto* endPointer = values.end();
|
||||
|
||||
while (e != endPointer)
|
||||
{
|
||||
if (objectToLookFor == *e)
|
||||
return true;
|
||||
|
||||
++e;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Returns true if the array contains a specified object.
|
||||
|
||||
@param objectToLookFor the object to look for
|
||||
@returns true if the object is in the array
|
||||
*/
|
||||
bool contains (const ObjectClassPtr& objectToLookFor) const noexcept { return contains (objectToLookFor.get()); }
|
||||
|
||||
/** Appends a new object to the end of the array.
|
||||
|
||||
This will increase the new object's reference count.
|
||||
|
||||
@param newObject the new object to add to the array
|
||||
@see set, insert, addIfNotAlreadyThere, addSorted, addArray
|
||||
*/
|
||||
ObjectClass* add (ObjectClass* newObject)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.add (newObject);
|
||||
|
||||
if (newObject != nullptr)
|
||||
newObject->incReferenceCount();
|
||||
|
||||
return newObject;
|
||||
}
|
||||
|
||||
/** Appends a new object to the end of the array.
|
||||
|
||||
This will increase the new object's reference count.
|
||||
|
||||
@param newObject the new object to add to the array
|
||||
@see set, insert, addIfNotAlreadyThere, addSorted, addArray
|
||||
*/
|
||||
ObjectClass* add (const ObjectClassPtr& newObject) { return add (newObject.get()); }
|
||||
|
||||
/** Inserts a new object into the array at the given index.
|
||||
|
||||
If the index is less than 0 or greater than the size of the array, the
|
||||
element will be added to the end of the array.
|
||||
Otherwise, it will be inserted into the array, moving all the later elements
|
||||
along to make room.
|
||||
|
||||
This will increase the new object's reference count.
|
||||
|
||||
@param indexToInsertAt the index at which the new element should be inserted
|
||||
@param newObject the new object to add to the array
|
||||
@see add, addSorted, addIfNotAlreadyThere, set
|
||||
*/
|
||||
ObjectClass* insert (int indexToInsertAt, ObjectClass* newObject)
|
||||
{
|
||||
values.insert (indexToInsertAt, newObject, 1);
|
||||
|
||||
if (newObject != nullptr)
|
||||
newObject->incReferenceCount();
|
||||
|
||||
return newObject;
|
||||
}
|
||||
|
||||
/** Inserts a new object into the array at the given index.
|
||||
|
||||
If the index is less than 0 or greater than the size of the array, the
|
||||
element will be added to the end of the array.
|
||||
Otherwise, it will be inserted into the array, moving all the later elements
|
||||
along to make room.
|
||||
|
||||
This will increase the new object's reference count.
|
||||
|
||||
@param indexToInsertAt the index at which the new element should be inserted
|
||||
@param newObject the new object to add to the array
|
||||
@see add, addSorted, addIfNotAlreadyThere, set
|
||||
*/
|
||||
ObjectClass* insert (int indexToInsertAt, const ObjectClassPtr& newObject) { return insert (indexToInsertAt, newObject.get()); }
|
||||
|
||||
/** Appends a new object at the end of the array as long as the array doesn't
|
||||
already contain it.
|
||||
|
||||
If the array already contains a matching object, nothing will be done.
|
||||
|
||||
@param newObject the new object to add to the array
|
||||
@returns true if the object has been added, false otherwise
|
||||
*/
|
||||
bool addIfNotAlreadyThere (ObjectClass* newObject)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (contains (newObject))
|
||||
return false;
|
||||
|
||||
add (newObject);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Appends a new object at the end of the array as long as the array doesn't
|
||||
already contain it.
|
||||
|
||||
If the array already contains a matching object, nothing will be done.
|
||||
|
||||
@param newObject the new object to add to the array
|
||||
@returns true if the object has been added, false otherwise
|
||||
*/
|
||||
bool addIfNotAlreadyThere (const ObjectClassPtr& newObject) { return addIfNotAlreadyThere (newObject.get()); }
|
||||
|
||||
/** Replaces an object in the array with a different one.
|
||||
|
||||
If the index is less than zero, this method does nothing.
|
||||
If the index is beyond the end of the array, the new object is added to the end of the array.
|
||||
|
||||
The object being added has its reference count increased, and if it's replacing
|
||||
another object, then that one has its reference count decreased, and may be deleted.
|
||||
|
||||
@param indexToChange the index whose value you want to change
|
||||
@param newObject the new value to set for this index.
|
||||
@see add, insert, remove
|
||||
*/
|
||||
void set (int indexToChange, ObjectClass* newObject)
|
||||
{
|
||||
if (indexToChange >= 0)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (newObject != nullptr)
|
||||
newObject->incReferenceCount();
|
||||
|
||||
if (indexToChange < values.size())
|
||||
{
|
||||
auto* e = values[indexToChange];
|
||||
values[indexToChange] = newObject;
|
||||
releaseObject (e);
|
||||
}
|
||||
else
|
||||
{
|
||||
values.add (newObject);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Replaces an object in the array with a different one.
|
||||
|
||||
If the index is less than zero, this method does nothing.
|
||||
If the index is beyond the end of the array, the new object is added to the end of the array.
|
||||
|
||||
The object being added has its reference count increased, and if it's replacing
|
||||
another object, then that one has its reference count decreased, and may be deleted.
|
||||
|
||||
@param indexToChange the index whose value you want to change
|
||||
@param newObject the new value to set for this index.
|
||||
@see add, insert, remove
|
||||
*/
|
||||
void set (int indexToChange, const ObjectClassPtr& newObject) { set (indexToChange, newObject.get()); }
|
||||
|
||||
/** Adds elements from another array to the end of this array.
|
||||
|
||||
@param arrayToAddFrom the array from which to copy the elements
|
||||
@param startIndex the first element of the other array to start copying from
|
||||
@param numElementsToAdd how many elements to add from the other array. If this
|
||||
value is negative or greater than the number of available elements,
|
||||
all available elements will be copied.
|
||||
@see add
|
||||
*/
|
||||
void addArray (const ReferenceCountedArray& arrayToAddFrom,
|
||||
int startIndex = 0,
|
||||
int numElementsToAdd = -1) noexcept
|
||||
{
|
||||
const ScopedLockType lock1 (arrayToAddFrom.getLock());
|
||||
|
||||
{
|
||||
const ScopedLockType lock2 (getLock());
|
||||
|
||||
auto numElementsAdded = values.addArray (arrayToAddFrom.values, startIndex, numElementsToAdd);
|
||||
auto** e = values.end();
|
||||
|
||||
for (int i = 0; i < numElementsAdded; ++i)
|
||||
(*(--e))->incReferenceCount();
|
||||
}
|
||||
}
|
||||
|
||||
/** Inserts a new object into the array assuming that the array is sorted.
|
||||
|
||||
This will use a comparator to find the position at which the new object
|
||||
should go. If the array isn't sorted, the behaviour of this
|
||||
method will be unpredictable.
|
||||
|
||||
@param comparator the comparator object to use to compare the elements - see the
|
||||
sort() method for details about this object's form
|
||||
@param newObject the new object to insert to the array
|
||||
@returns the index at which the new object was added
|
||||
@see add, sort
|
||||
*/
|
||||
template <class ElementComparator>
|
||||
int addSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto index = findInsertIndexInSortedArray (comparator, values.begin(), newObject, 0, values.size());
|
||||
insert (index, newObject);
|
||||
return index;
|
||||
}
|
||||
|
||||
/** Inserts or replaces an object in the array, assuming it is sorted.
|
||||
|
||||
This is similar to addSorted, but if a matching element already exists, then it will be
|
||||
replaced by the new one, rather than the new one being added as well.
|
||||
*/
|
||||
template <class ElementComparator>
|
||||
void addOrReplaceSorted (ElementComparator& comparator, ObjectClass* newObject) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
auto index = findInsertIndexInSortedArray (comparator, values.begin(), newObject, 0, values.size());
|
||||
|
||||
if (index > 0 && comparator.compareElements (newObject, values[index - 1]) == 0)
|
||||
set (index - 1, newObject); // replace an existing object that matches
|
||||
else
|
||||
insert (index, newObject); // no match, so insert the new one
|
||||
}
|
||||
|
||||
/** Finds the index of an object in the array, assuming that the array is sorted.
|
||||
|
||||
This will use a comparator to do a binary-chop to find the index of the given
|
||||
element, if it exists. If the array isn't sorted, the behaviour of this
|
||||
method will be unpredictable.
|
||||
|
||||
@param comparator the comparator to use to compare the elements - see the sort()
|
||||
method for details about the form this object should take
|
||||
@param objectToLookFor the object to search for
|
||||
@returns the index of the element, or -1 if it's not found
|
||||
@see addSorted, sort
|
||||
*/
|
||||
template <class ElementComparator>
|
||||
int indexOfSorted (ElementComparator& comparator, const ObjectClass* objectToLookFor) const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Removes an object from the array.
|
||||
|
||||
This will remove the object at a given index and move back all the
|
||||
subsequent objects to close the gap.
|
||||
|
||||
If the index passed in is out-of-range, nothing will happen.
|
||||
|
||||
The object that is removed will have its reference count decreased,
|
||||
and may be deleted if not referenced from elsewhere.
|
||||
|
||||
@param indexToRemove the index of the element to remove
|
||||
@see removeObject, removeRange
|
||||
*/
|
||||
void remove (int indexToRemove)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (isPositiveAndBelow (indexToRemove, values.size()))
|
||||
{
|
||||
auto* e = *(values.begin() + indexToRemove);
|
||||
values.removeElements (indexToRemove, 1);
|
||||
releaseObject (e);
|
||||
|
||||
if ((values.size() << 1) < values.capacity())
|
||||
minimiseStorageOverheads();
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes and returns an object from the array.
|
||||
|
||||
This will remove the object at a given index and return it, moving back all
|
||||
the subsequent objects to close the gap. If the index passed in is out-of-range,
|
||||
nothing will happen and a null pointer will be returned.
|
||||
|
||||
@param indexToRemove the index of the element to remove
|
||||
@see remove, removeObject, removeRange
|
||||
*/
|
||||
ObjectClassPtr removeAndReturn (int indexToRemove)
|
||||
{
|
||||
ObjectClassPtr removedItem;
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (isPositiveAndBelow (indexToRemove, values.size()))
|
||||
{
|
||||
auto* e = *(values.begin() + indexToRemove);
|
||||
removedItem = e;
|
||||
values.removeElements (indexToRemove, 1);
|
||||
releaseObject (e);
|
||||
|
||||
if ((values.size() << 1) < values.capacity())
|
||||
minimiseStorageOverheads();
|
||||
}
|
||||
|
||||
return removedItem;
|
||||
}
|
||||
|
||||
/** Removes the first occurrence of a specified object from the array.
|
||||
|
||||
If the item isn't found, no action is taken. If it is found, it is
|
||||
removed and has its reference count decreased.
|
||||
|
||||
@param objectToRemove the object to try to remove
|
||||
@see remove, removeRange
|
||||
*/
|
||||
void removeObject (ObjectClass* objectToRemove)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
remove (indexOf (objectToRemove));
|
||||
}
|
||||
|
||||
/** Removes the first occurrence of a specified object from the array.
|
||||
|
||||
If the item isn't found, no action is taken. If it is found, it is
|
||||
removed and has its reference count decreased.
|
||||
|
||||
@param objectToRemove the object to try to remove
|
||||
@see remove, removeRange
|
||||
*/
|
||||
void removeObject (const ObjectClassPtr& objectToRemove) { removeObject (objectToRemove.get()); }
|
||||
|
||||
/** Removes a range of objects from the array.
|
||||
|
||||
This will remove a set of objects, starting from the given index,
|
||||
and move any subsequent elements down to close the gap.
|
||||
|
||||
If the range extends beyond the bounds of the array, it will
|
||||
be safely clipped to the size of the array.
|
||||
|
||||
The objects that are removed will have their reference counts decreased,
|
||||
and may be deleted if not referenced from elsewhere.
|
||||
|
||||
@param startIndex the index of the first object to remove
|
||||
@param numberToRemove how many objects should be removed
|
||||
@see remove, removeObject
|
||||
*/
|
||||
void removeRange (int startIndex,
|
||||
int numberToRemove)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
startIndex = jlimit (0, values.size(), startIndex);
|
||||
auto endIndex = jlimit (0, values.size(), startIndex + numberToRemove);
|
||||
numberToRemove = endIndex - startIndex;
|
||||
|
||||
if (numberToRemove > 0)
|
||||
{
|
||||
Array<ObjectClass*> objectsToRemove;
|
||||
objectsToRemove.addArray (values.begin() + startIndex, numberToRemove);
|
||||
|
||||
values.removeElements (startIndex, numberToRemove);
|
||||
|
||||
for (auto& o : objectsToRemove)
|
||||
releaseObject (o);
|
||||
|
||||
if ((values.size() << 1) < values.capacity())
|
||||
minimiseStorageOverheads();
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes the last n objects from the array.
|
||||
|
||||
The objects that are removed will have their reference counts decreased,
|
||||
and may be deleted if not referenced from elsewhere.
|
||||
|
||||
@param howManyToRemove how many objects to remove from the end of the array
|
||||
@see remove, removeObject, removeRange
|
||||
*/
|
||||
void removeLast (int howManyToRemove = 1)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (howManyToRemove > values.size())
|
||||
howManyToRemove = values.size();
|
||||
|
||||
while (--howManyToRemove >= 0)
|
||||
remove (values.size() - 1);
|
||||
}
|
||||
|
||||
/** Swaps a pair of objects in the array.
|
||||
|
||||
If either of the indexes passed in is out-of-range, nothing will happen,
|
||||
otherwise the two objects at these positions will be exchanged.
|
||||
*/
|
||||
void swap (int index1, int index2) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
if (isPositiveAndBelow (index1, values.size())
|
||||
&& isPositiveAndBelow (index2, values.size()))
|
||||
{
|
||||
std::swap (values[index1], values[index2]);
|
||||
}
|
||||
}
|
||||
|
||||
/** Moves one of the objects to a different position.
|
||||
|
||||
This will move the object to a specified index, shuffling along
|
||||
any intervening elements as required.
|
||||
|
||||
So for example, if you have the array { 0, 1, 2, 3, 4, 5 } then calling
|
||||
move (2, 4) would result in { 0, 1, 3, 4, 2, 5 }.
|
||||
|
||||
@param currentIndex the index of the object to be moved. If this isn't a
|
||||
valid index, then nothing will be done
|
||||
@param newIndex the index at which you'd like this object to end up. If this
|
||||
is less than zero, it will be moved to the end of the array
|
||||
*/
|
||||
void move (int currentIndex, int newIndex) noexcept
|
||||
{
|
||||
if (currentIndex != newIndex)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.move (currentIndex, newIndex);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** This swaps the contents of this array with those of another array.
|
||||
|
||||
If you need to exchange two arrays, this is vastly quicker than using copy-by-value
|
||||
because it just swaps their internal pointers.
|
||||
*/
|
||||
template <class OtherArrayType>
|
||||
void swapWith (OtherArrayType& otherArray) noexcept
|
||||
{
|
||||
const ScopedLockType lock1 (getLock());
|
||||
const typename OtherArrayType::ScopedLockType lock2 (otherArray.getLock());
|
||||
values.swapWith (otherArray.values);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Compares this array to another one.
|
||||
|
||||
@returns true only if the other array contains the same objects in the same order
|
||||
*/
|
||||
bool operator== (const ReferenceCountedArray& other) const noexcept
|
||||
{
|
||||
const ScopedLockType lock2 (other.getLock());
|
||||
const ScopedLockType lock1 (getLock());
|
||||
return values == other.values;
|
||||
}
|
||||
|
||||
/** Compares this array to another one.
|
||||
|
||||
@see operator==
|
||||
*/
|
||||
bool operator!= (const ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Sorts the elements in the array.
|
||||
|
||||
This will use a comparator object to sort the elements into order. The object
|
||||
passed must have a method of the form:
|
||||
@code
|
||||
int compareElements (ElementType first, ElementType second);
|
||||
@endcode
|
||||
|
||||
...and this method must return:
|
||||
- a value of < 0 if the first comes before the second
|
||||
- a value of 0 if the two objects are equivalent
|
||||
- a value of > 0 if the second comes before the first
|
||||
|
||||
To improve performance, the compareElements() method can be declared as static or const.
|
||||
|
||||
@param comparator the comparator to use for comparing elements.
|
||||
@param retainOrderOfEquivalentItems if this is true, then items
|
||||
which the comparator says are equivalent will be
|
||||
kept in the order in which they currently appear
|
||||
in the array. This is slower to perform, but may
|
||||
be important in some cases. If it's false, a faster
|
||||
algorithm is used, but equivalent elements may be
|
||||
rearranged.
|
||||
|
||||
@see sortArray
|
||||
*/
|
||||
template <class ElementComparator>
|
||||
void sort (ElementComparator& comparator, bool retainOrderOfEquivalentItems = false) noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Reduces the amount of storage being used by the array.
|
||||
|
||||
Arrays typically allocate slightly more storage than they need, and after
|
||||
removing elements, they may have quite a lot of unused space allocated.
|
||||
This method will reduce the amount of allocated storage to a minimum.
|
||||
*/
|
||||
void minimiseStorageOverheads() noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.shrinkToNoMoreThan (values.size());
|
||||
}
|
||||
|
||||
/** Increases the array's internal storage to hold a minimum number of elements.
|
||||
|
||||
Calling this before adding a large known number of elements means that
|
||||
the array won't have to keep dynamically resizing itself as the elements
|
||||
are added, and it'll therefore be more efficient.
|
||||
*/
|
||||
void ensureStorageAllocated (const int minNumElements)
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
values.ensureAllocatedSize (minNumElements);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the CriticalSection that locks this array.
|
||||
To lock, you can call getLock().enter() and getLock().exit(), or preferably use
|
||||
an object of ScopedLockType as an RAII lock for it.
|
||||
*/
|
||||
inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return values; }
|
||||
|
||||
/** Returns the type of scoped lock to use for locking this array */
|
||||
using ScopedLockType = typename TypeOfCriticalSectionToUse::ScopedLockType;
|
||||
|
||||
//==============================================================================
|
||||
/** @cond */
|
||||
[[deprecated ("This method has been replaced by a more flexible templated version and renamed "
|
||||
"to swapWith to be more consistent with the names used in other classes.")]]
|
||||
void swapWithArray (ReferenceCountedArray& other) noexcept { swapWith (other); }
|
||||
/** @endcond */
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
ArrayBase<ObjectClass*, TypeOfCriticalSectionToUse> values;
|
||||
|
||||
void releaseAllObjects()
|
||||
{
|
||||
auto i = values.size();
|
||||
|
||||
while (--i >= 0)
|
||||
{
|
||||
auto* e = values[i];
|
||||
values.removeElements (i, 1);
|
||||
releaseObject (e);
|
||||
}
|
||||
}
|
||||
|
||||
static void releaseObject (ObjectClass* o)
|
||||
{
|
||||
if (o != nullptr && o->decReferenceCountWithoutDeleting())
|
||||
ContainerDeletePolicy<ObjectClass>::destroy (o);
|
||||
}
|
||||
};
|
||||
|
||||
//==============================================================================
|
||||
template <class ObjectClass, class TypeOfCriticalSectionToUse>
|
||||
template <class ElementComparator>
|
||||
int ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>::indexOfSorted (
|
||||
[[maybe_unused]] ElementComparator& comparator,
|
||||
const ObjectClass* objectToLookFor) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
int s = 0, e = values.size();
|
||||
|
||||
while (s < e)
|
||||
{
|
||||
if (comparator.compareElements (objectToLookFor, values[s]) == 0)
|
||||
return s;
|
||||
|
||||
auto halfway = (s + e) / 2;
|
||||
|
||||
if (halfway == s)
|
||||
break;
|
||||
|
||||
if (comparator.compareElements (objectToLookFor, values[halfway]) >= 0)
|
||||
s = halfway;
|
||||
else
|
||||
e = halfway;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
|
||||
template <class ObjectClass, class TypeOfCriticalSectionToUse>
|
||||
template <class ElementComparator>
|
||||
void ReferenceCountedArray<ObjectClass, TypeOfCriticalSectionToUse>::sort (
|
||||
[[maybe_unused]] ElementComparator& comparator,
|
||||
bool retainOrderOfEquivalentItems) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
sortArray (comparator, values.begin(), 0, values.size() - 1, retainOrderOfEquivalentItems);
|
||||
}
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,105 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Helper class providing an RAII-based mechanism for temporarily setting and
|
||||
then re-setting a value.
|
||||
|
||||
E.g. @code
|
||||
int x = 1;
|
||||
|
||||
{
|
||||
ScopedValueSetter setter (x, 2);
|
||||
|
||||
// x is now 2
|
||||
}
|
||||
|
||||
// x is now 1 again
|
||||
|
||||
{
|
||||
ScopedValueSetter setter (x, 3, 4);
|
||||
|
||||
// x is now 3
|
||||
}
|
||||
|
||||
// x is now 4
|
||||
@endcode
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename ValueType>
|
||||
class [[nodiscard]] ScopedValueSetter
|
||||
{
|
||||
public:
|
||||
/** Creates a ScopedValueSetter that will immediately change the specified value to the
|
||||
given new value, and will then reset it to its original value when this object is deleted.
|
||||
*/
|
||||
ScopedValueSetter (ValueType& valueToSet,
|
||||
ValueType newValue)
|
||||
: value (valueToSet),
|
||||
originalValue (valueToSet)
|
||||
{
|
||||
valueToSet = newValue;
|
||||
}
|
||||
|
||||
/** Creates a ScopedValueSetter that will immediately change the specified value to the
|
||||
given new value, and will then reset it to be valueWhenDeleted when this object is deleted.
|
||||
*/
|
||||
ScopedValueSetter (ValueType& valueToSet,
|
||||
ValueType newValue,
|
||||
ValueType valueWhenDeleted)
|
||||
: value (valueToSet),
|
||||
originalValue (valueWhenDeleted)
|
||||
{
|
||||
valueToSet = newValue;
|
||||
}
|
||||
|
||||
~ScopedValueSetter()
|
||||
{
|
||||
value = originalValue;
|
||||
}
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
ValueType& value;
|
||||
const ValueType originalValue;
|
||||
|
||||
JUCE_DECLARE_NON_COPYABLE (ScopedValueSetter)
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,138 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Encapsulates the logic for a single-threaded FIFO.
|
||||
|
||||
This might be useful for building buffers which can be written and read in
|
||||
blocks of different sizes. For example, in an audio effect we might wish to
|
||||
run some processing on fixed-size blocks of audio input, but the host may
|
||||
provide input blocks of varying sizes. In this situation, we might want to
|
||||
store the previous input in a buffer, and extract a fixed-size block
|
||||
whenever there are enough samples available. The SingleThreadedAbstractFifo
|
||||
implements logic suitable for this use-case.
|
||||
|
||||
This class is quite similar to AbstractFifo, in that it only keeps track of
|
||||
the current read/write locations. The user is responsible for providing the
|
||||
actual buffer that will be read/written.
|
||||
|
||||
The intended usage of this class is as follows:
|
||||
- Create some backing storage in a vector, AudioBuffer etc.
|
||||
- Construct a SingleThreadedAbstractFifo to manage the buffer, passing the
|
||||
number of items in the buffer.
|
||||
- Each time new input is ready, call write(), passing the number of items
|
||||
you wish to write into the buffer. This function returns a pair of ranges
|
||||
describing which indices in the backing storage should be written.
|
||||
- Call getNumReadable() to find out how many items are ready to read from
|
||||
the buffer.
|
||||
- If there are enough items ready to read, call read(), passing the number
|
||||
of items you require. This function returns a pair of ranges describing
|
||||
which indices in the backing storage may be read.
|
||||
|
||||
Unlike AbstractFifo, the SingleThreadedAbstractFifo is intended for use
|
||||
from a single thread. It is not safe to call any non-const member function
|
||||
of SingleThreadedAbstractFifo concurrently with any other member function.
|
||||
|
||||
@see AbstractFifo
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class SingleThreadedAbstractFifo
|
||||
{
|
||||
public:
|
||||
/** Creates a SingleThreadedAbstractFifo with no size. */
|
||||
SingleThreadedAbstractFifo() = default;
|
||||
|
||||
/** Creates a SingleThreadedAbstractFifo that can manage a buffer of the specified size. */
|
||||
explicit SingleThreadedAbstractFifo (int sizeIn)
|
||||
: size (sizeIn)
|
||||
{
|
||||
// This class only works properly when the size is a power of two.
|
||||
// Use nextPowerOfTwo() to find a good size, and ensure that your
|
||||
// backing storage is the same size.
|
||||
jassert (isPowerOfTwo (sizeIn));
|
||||
}
|
||||
|
||||
/** Returns the number of unused elements present in the buffer. */
|
||||
int getRemainingSpace() const { return size - numReadable; }
|
||||
|
||||
/** Returns the number of pending elements present in the buffer. */
|
||||
int getNumReadable() const { return numReadable; }
|
||||
|
||||
/** Returns the size of the managed buffer. */
|
||||
int getSize() const { return size; }
|
||||
|
||||
/** Returns two blocks in the buffer where new items may be written.
|
||||
|
||||
Note that if the buffer is running low on free space, the sum of the lengths of
|
||||
the returned ranges may be less than num!
|
||||
*/
|
||||
std::array<Range<int>, 2> write (int num)
|
||||
{
|
||||
const auto startPos = (readPos + numReadable) & (size - 1);
|
||||
const auto maxToWrite = jmin (getRemainingSpace(), num);
|
||||
const auto firstBlockSize = jmin (maxToWrite, size - startPos);
|
||||
|
||||
numReadable += maxToWrite;
|
||||
|
||||
return { { { startPos, startPos + firstBlockSize }, { 0, maxToWrite - firstBlockSize } } };
|
||||
}
|
||||
|
||||
/** Returns two blocks in the buffer from which new items may be read.
|
||||
|
||||
Note that if the buffer doesn't have the requested number of items available,
|
||||
the sum of the lengths of the returned ranges may be less than num!
|
||||
*/
|
||||
std::array<Range<int>, 2> read (int num)
|
||||
{
|
||||
const auto startPos = readPos;
|
||||
const auto maxToRead = jmin (numReadable, num);
|
||||
const auto firstBlockSize = jmin (maxToRead, size - startPos);
|
||||
|
||||
readPos = (startPos + maxToRead) & (size - 1);
|
||||
numReadable -= maxToRead;
|
||||
|
||||
return { { { startPos, startPos + firstBlockSize }, { 0, maxToRead - firstBlockSize } } };
|
||||
}
|
||||
|
||||
private:
|
||||
int size = 0, readPos = 0, numReadable = 0;
|
||||
};
|
||||
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,501 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4512)
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Holds a set of unique primitive objects, such as ints or doubles.
|
||||
|
||||
A set can only hold one item with a given value, so if for example it's a
|
||||
set of integers, attempting to add the same integer twice will do nothing
|
||||
the second time.
|
||||
|
||||
Internally, the list of items is kept sorted (which means that whatever
|
||||
kind of primitive type is used must support the ==, <, >, <= and >= operators
|
||||
to determine the order), and searching the set for known values is very fast
|
||||
because it uses a binary-chop method.
|
||||
|
||||
Note that if you're using a class or struct as the element type, it must be
|
||||
capable of being copied or moved with a straightforward memcpy, rather than
|
||||
needing construction and destruction code.
|
||||
|
||||
To make all the set's methods thread-safe, pass in "CriticalSection" as the templated
|
||||
TypeOfCriticalSectionToUse parameter, instead of the default DummyCriticalSection.
|
||||
|
||||
@see Array, OwnedArray, ReferenceCountedArray, StringArray, CriticalSection
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class ElementType, class TypeOfCriticalSectionToUse = DummyCriticalSection>
|
||||
class SortedSet
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** Creates an empty set. */
|
||||
SortedSet() = default;
|
||||
|
||||
/** Creates a copy of another set. */
|
||||
SortedSet (const SortedSet&) = default;
|
||||
|
||||
/** Creates a copy of another set. */
|
||||
SortedSet (SortedSet&&) noexcept = default;
|
||||
|
||||
/** Makes a copy of another set. */
|
||||
SortedSet& operator= (const SortedSet&) = default;
|
||||
|
||||
/** Makes a copy of another set. */
|
||||
SortedSet& operator= (SortedSet&&) noexcept = default;
|
||||
|
||||
/** Destructor. */
|
||||
~SortedSet() = default;
|
||||
|
||||
//==============================================================================
|
||||
/** Compares this set to another one.
|
||||
Two sets are considered equal if they both contain the same set of elements.
|
||||
@param other the other set to compare with
|
||||
*/
|
||||
bool operator== (const SortedSet<ElementType>& other) const noexcept
|
||||
{
|
||||
return data == other.data;
|
||||
}
|
||||
|
||||
/** Compares this set to another one.
|
||||
Two sets are considered equal if they both contain the same set of elements.
|
||||
@param other the other set to compare with
|
||||
*/
|
||||
bool operator!= (const SortedSet<ElementType>& other) const noexcept
|
||||
{
|
||||
return ! operator== (other);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Removes all elements from the set.
|
||||
|
||||
This will remove all the elements, and free any storage that the set is
|
||||
using. To clear it without freeing the storage, use the clearQuick()
|
||||
method instead.
|
||||
|
||||
@see clearQuick
|
||||
*/
|
||||
void clear() noexcept
|
||||
{
|
||||
data.clear();
|
||||
}
|
||||
|
||||
/** Removes all elements from the set without freeing the array's allocated storage.
|
||||
@see clear
|
||||
*/
|
||||
void clearQuick() noexcept
|
||||
{
|
||||
data.clearQuick();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the current number of elements in the set. */
|
||||
inline int size() const noexcept
|
||||
{
|
||||
return data.size();
|
||||
}
|
||||
|
||||
/** Returns true if the set is empty, false otherwise. */
|
||||
inline bool isEmpty() const noexcept
|
||||
{
|
||||
return size() == 0;
|
||||
}
|
||||
|
||||
/** Returns one of the elements in the set.
|
||||
|
||||
If the index passed in is beyond the range of valid elements, this
|
||||
will return zero.
|
||||
|
||||
If you're certain that the index will always be a valid element, you
|
||||
can call getUnchecked() instead, which is faster.
|
||||
|
||||
@param index the index of the element being requested (0 is the first element in the set)
|
||||
@see getUnchecked, getFirst, getLast
|
||||
*/
|
||||
inline ElementType operator[] (const int index) const noexcept
|
||||
{
|
||||
return data [index];
|
||||
}
|
||||
|
||||
/** Returns one of the elements in the set, without checking the index passed in.
|
||||
Unlike the operator[] method, this will try to return an element without
|
||||
checking that the index is within the bounds of the set, so should only
|
||||
be used when you're confident that it will always be a valid index.
|
||||
|
||||
@param index the index of the element being requested (0 is the first element in the set)
|
||||
@see operator[], getFirst, getLast
|
||||
*/
|
||||
inline ElementType getUnchecked (const int index) const noexcept
|
||||
{
|
||||
return data.getUnchecked (index);
|
||||
}
|
||||
|
||||
/** Returns a direct reference to one of the elements in the set, without checking the index passed in.
|
||||
|
||||
This is like getUnchecked, but returns a direct reference to the element, so that
|
||||
you can alter it directly. Obviously this can be dangerous, so only use it when
|
||||
absolutely necessary.
|
||||
|
||||
@param index the index of the element being requested (0 is the first element in the array)
|
||||
*/
|
||||
inline ElementType& getReference (const int index) noexcept
|
||||
{
|
||||
return data.getReference (index);
|
||||
}
|
||||
|
||||
/** Returns a direct reference to one of the elements in the set, without checking the index passed in.
|
||||
|
||||
@param index the index of the element being requested (0 is the first element in the array)
|
||||
*/
|
||||
inline const ElementType& getReference (const int index) const noexcept
|
||||
{
|
||||
return data.getReference (index);
|
||||
}
|
||||
|
||||
/** Returns the first element in the set, or 0 if the set is empty.
|
||||
@see operator[], getUnchecked, getLast
|
||||
*/
|
||||
inline ElementType getFirst() const noexcept
|
||||
{
|
||||
return data.getFirst();
|
||||
}
|
||||
|
||||
/** Returns the last element in the set, or 0 if the set is empty.
|
||||
@see operator[], getUnchecked, getFirst
|
||||
*/
|
||||
inline ElementType getLast() const noexcept
|
||||
{
|
||||
return data.getLast();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a pointer to the first element in the set.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline const ElementType* begin() const noexcept
|
||||
{
|
||||
return data.begin();
|
||||
}
|
||||
|
||||
/** Returns a pointer to the element which follows the last element in the set.
|
||||
This method is provided for compatibility with standard C++ iteration mechanisms.
|
||||
*/
|
||||
inline const ElementType* end() const noexcept
|
||||
{
|
||||
return data.end();
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Finds the index of the first element which matches the value passed in.
|
||||
|
||||
This will search the set for the given object, and return the index
|
||||
of its first occurrence. If the object isn't found, the method will return -1.
|
||||
|
||||
@param elementToLookFor the value or object to look for
|
||||
@returns the index of the object, or -1 if it's not found
|
||||
*/
|
||||
int indexOf (const ElementType& elementToLookFor) const noexcept
|
||||
{
|
||||
const ScopedLockType lock (data.getLock());
|
||||
|
||||
int s = 0;
|
||||
int e = data.size();
|
||||
|
||||
for (;;)
|
||||
{
|
||||
if (s >= e)
|
||||
return -1;
|
||||
|
||||
if (elementToLookFor == data.getReference (s))
|
||||
return s;
|
||||
|
||||
auto halfway = (s + e) / 2;
|
||||
|
||||
if (halfway == s)
|
||||
return -1;
|
||||
|
||||
if (elementToLookFor < data.getReference (halfway))
|
||||
e = halfway;
|
||||
else
|
||||
s = halfway;
|
||||
}
|
||||
}
|
||||
|
||||
/** Returns true if the set contains at least one occurrence of an object.
|
||||
|
||||
@param elementToLookFor the value or object to look for
|
||||
@returns true if the item is found
|
||||
*/
|
||||
bool contains (const ElementType& elementToLookFor) const noexcept
|
||||
{
|
||||
return indexOf (elementToLookFor) >= 0;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Adds a new element to the set, (as long as it's not already in there).
|
||||
|
||||
Note that if a matching element already exists, the new value will be assigned
|
||||
to the existing one using operator=, so that if there are any differences between
|
||||
the objects which were not recognised by the object's operator==, then the
|
||||
set will always contain a copy of the most recently added one.
|
||||
|
||||
@param newElement the new object to add to the set
|
||||
@returns true if the value was added, or false if it already existed
|
||||
@see set, insert, addIfNotAlreadyThere, addSorted, addSet, addArray
|
||||
*/
|
||||
bool add (const ElementType& newElement) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
int s = 0;
|
||||
int e = data.size();
|
||||
|
||||
while (s < e)
|
||||
{
|
||||
auto& elem = data.getReference (s);
|
||||
|
||||
if (newElement == elem)
|
||||
{
|
||||
elem = newElement; // force an update in case operator== permits differences
|
||||
return false;
|
||||
}
|
||||
|
||||
auto halfway = (s + e) / 2;
|
||||
bool isBeforeHalfway = (newElement < data.getReference (halfway));
|
||||
|
||||
if (halfway == s)
|
||||
{
|
||||
if (! isBeforeHalfway)
|
||||
++s;
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
if (isBeforeHalfway)
|
||||
e = halfway;
|
||||
else
|
||||
s = halfway;
|
||||
}
|
||||
|
||||
data.insert (s, newElement);
|
||||
return true;
|
||||
}
|
||||
|
||||
/** Adds elements from an array to this set.
|
||||
|
||||
@param elementsToAdd the array of elements to add
|
||||
@param numElementsToAdd how many elements are in this other array
|
||||
@see add
|
||||
*/
|
||||
void addArray (const ElementType* elementsToAdd,
|
||||
int numElementsToAdd) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
|
||||
while (--numElementsToAdd >= 0)
|
||||
add (*elementsToAdd++);
|
||||
}
|
||||
|
||||
/** Adds elements from another set to this one.
|
||||
|
||||
@param setToAddFrom the set from which to copy the elements
|
||||
@param startIndex the first element of the other set to start copying from
|
||||
@param numElementsToAdd how many elements to add from the other set. If this
|
||||
value is negative or greater than the number of available elements,
|
||||
all available elements will be copied.
|
||||
@see add
|
||||
*/
|
||||
template <class OtherSetType>
|
||||
void addSet (const OtherSetType& setToAddFrom,
|
||||
int startIndex = 0,
|
||||
int numElementsToAdd = -1) noexcept
|
||||
{
|
||||
const typename OtherSetType::ScopedLockType lock1 (setToAddFrom.getLock());
|
||||
const ScopedLockType lock2 (getLock());
|
||||
jassert (this != &setToAddFrom);
|
||||
|
||||
if (this != &setToAddFrom)
|
||||
{
|
||||
if (startIndex < 0)
|
||||
{
|
||||
jassertfalse;
|
||||
startIndex = 0;
|
||||
}
|
||||
|
||||
if (numElementsToAdd < 0 || startIndex + numElementsToAdd > setToAddFrom.size())
|
||||
numElementsToAdd = setToAddFrom.size() - startIndex;
|
||||
|
||||
if (numElementsToAdd > 0)
|
||||
addArray (&setToAddFrom.data.getReference (startIndex), numElementsToAdd);
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Removes an element from the set.
|
||||
|
||||
This will remove the element at a given index.
|
||||
If the index passed in is out-of-range, nothing will happen.
|
||||
|
||||
@param indexToRemove the index of the element to remove
|
||||
@returns the element that has been removed
|
||||
@see removeValue, removeRange
|
||||
*/
|
||||
ElementType remove (const int indexToRemove) noexcept
|
||||
{
|
||||
return data.removeAndReturn (indexToRemove);
|
||||
}
|
||||
|
||||
/** Removes an item from the set.
|
||||
|
||||
This will remove the given element from the set, if it's there.
|
||||
|
||||
@param valueToRemove the object to try to remove
|
||||
@see remove, removeRange
|
||||
*/
|
||||
void removeValue (const ElementType& valueToRemove) noexcept
|
||||
{
|
||||
const ScopedLockType lock (getLock());
|
||||
data.remove (indexOf (valueToRemove));
|
||||
}
|
||||
|
||||
/** Removes any elements which are also in another set.
|
||||
|
||||
@param otherSet the other set in which to look for elements to remove
|
||||
@see removeValuesNotIn, remove, removeValue, removeRange
|
||||
*/
|
||||
template <class OtherSetType>
|
||||
void removeValuesIn (const OtherSetType& otherSet) noexcept
|
||||
{
|
||||
const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
|
||||
const ScopedLockType lock2 (getLock());
|
||||
|
||||
if (this == &otherSet)
|
||||
{
|
||||
clear();
|
||||
}
|
||||
else if (! otherSet.isEmpty())
|
||||
{
|
||||
for (int i = data.size(); --i >= 0;)
|
||||
if (otherSet.contains (data.getReference (i)))
|
||||
remove (i);
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes any elements which are not found in another set.
|
||||
|
||||
Only elements which occur in this other set will be retained.
|
||||
|
||||
@param otherSet the set in which to look for elements NOT to remove
|
||||
@see removeValuesIn, remove, removeValue, removeRange
|
||||
*/
|
||||
template <class OtherSetType>
|
||||
void removeValuesNotIn (const OtherSetType& otherSet) noexcept
|
||||
{
|
||||
const typename OtherSetType::ScopedLockType lock1 (otherSet.getLock());
|
||||
const ScopedLockType lock2 (getLock());
|
||||
|
||||
if (this != &otherSet)
|
||||
{
|
||||
if (otherSet.isEmpty())
|
||||
{
|
||||
clear();
|
||||
}
|
||||
else
|
||||
{
|
||||
for (int i = data.size(); --i >= 0;)
|
||||
if (! otherSet.contains (data.getReference (i)))
|
||||
remove (i);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** This swaps the contents of this array with those of another array.
|
||||
|
||||
If you need to exchange two arrays, this is vastly quicker than using copy-by-value
|
||||
because it just swaps their internal pointers.
|
||||
*/
|
||||
template <class OtherSetType>
|
||||
void swapWith (OtherSetType& otherSet) noexcept
|
||||
{
|
||||
data.swapWith (otherSet.data);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Reduces the amount of storage being used by the set.
|
||||
|
||||
Sets typically allocate slightly more storage than they need, and after
|
||||
removing elements, they may have quite a lot of unused space allocated.
|
||||
This method will reduce the amount of allocated storage to a minimum.
|
||||
*/
|
||||
void minimiseStorageOverheads() noexcept
|
||||
{
|
||||
data.minimiseStorageOverheads();
|
||||
}
|
||||
|
||||
/** Increases the set's internal storage to hold a minimum number of elements.
|
||||
|
||||
Calling this before adding a large known number of elements means that
|
||||
the set won't have to keep dynamically resizing itself as the elements
|
||||
are added, and it'll therefore be more efficient.
|
||||
*/
|
||||
void ensureStorageAllocated (const int minNumElements)
|
||||
{
|
||||
data.ensureStorageAllocated (minNumElements);
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the CriticalSection that locks this array.
|
||||
To lock, you can call getLock().enter() and getLock().exit(), or preferably use
|
||||
an object of ScopedLockType as an RAII lock for it.
|
||||
*/
|
||||
inline const TypeOfCriticalSectionToUse& getLock() const noexcept { return data.getLock(); }
|
||||
|
||||
/** Returns the type of scoped lock to use for locking this array */
|
||||
using ScopedLockType = typename TypeOfCriticalSectionToUse::ScopedLockType;
|
||||
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
Array<ElementType, TypeOfCriticalSectionToUse> data;
|
||||
};
|
||||
|
||||
JUCE_END_IGNORE_WARNINGS_MSVC
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
inline constexpr auto dynamicExtent = std::numeric_limits<size_t>::max();
|
||||
|
||||
template <typename Value, size_t Extent>
|
||||
class Span;
|
||||
|
||||
namespace detail
|
||||
{
|
||||
//==============================================================================
|
||||
template <typename, typename = void>
|
||||
constexpr auto hasToAddress = false;
|
||||
|
||||
template <typename T>
|
||||
constexpr auto hasToAddress<T, Void<decltype (std::pointer_traits<T>::to_address (std::declval<T>()))>> = true;
|
||||
|
||||
template <typename, typename = void>
|
||||
constexpr auto hasDataAndSize = false;
|
||||
|
||||
template <typename T>
|
||||
constexpr auto hasDataAndSize<T,
|
||||
Void<decltype (std::data (std::declval<T>())),
|
||||
decltype (std::size (std::declval<T>()))>> = true;
|
||||
|
||||
template <typename From, typename To>
|
||||
constexpr auto isSpanConvertible = std::is_convertible_v<From (*)[], To (*)[]>;
|
||||
|
||||
template <typename T>
|
||||
constexpr auto isSpanType = false;
|
||||
|
||||
template <typename Value, size_t Extent>
|
||||
constexpr auto isSpanType<Span<Value, Extent>> = true;
|
||||
|
||||
template <typename Range, typename Value, typename = void>
|
||||
constexpr auto isSpanCompatibleRange = false;
|
||||
|
||||
template <typename Range, typename Value>
|
||||
constexpr auto isSpanCompatibleRange<Range,
|
||||
Value,
|
||||
Void<std::enable_if_t<hasDataAndSize<Range>
|
||||
&& ! isSpanType<std::remove_cv_t<std::remove_reference_t<Range>>>>>>
|
||||
= isSpanConvertible<std::remove_pointer_t<decltype (std::data (std::declval<Range&>()))>, Value>;
|
||||
|
||||
template <size_t Extent>
|
||||
struct NumBase
|
||||
{
|
||||
constexpr NumBase() = default;
|
||||
|
||||
constexpr explicit NumBase (size_t) {}
|
||||
|
||||
constexpr size_t size() const { return Extent; }
|
||||
};
|
||||
|
||||
template <>
|
||||
struct NumBase<dynamicExtent>
|
||||
{
|
||||
constexpr NumBase() = default;
|
||||
|
||||
constexpr explicit NumBase (size_t arg)
|
||||
: num (arg) {}
|
||||
|
||||
constexpr size_t size() const { return num; }
|
||||
|
||||
size_t num{};
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
constexpr T* toAddress (T* p)
|
||||
{
|
||||
return p;
|
||||
}
|
||||
|
||||
template <typename It>
|
||||
constexpr auto toAddress (const It& it)
|
||||
{
|
||||
if constexpr (detail::hasToAddress<It>)
|
||||
return std::pointer_traits<It>::to_address (it);
|
||||
else
|
||||
return toAddress (it.operator->());
|
||||
}
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A non-owning view over contiguous objects stored in an Array or vector
|
||||
or other similar container.
|
||||
|
||||
This is a bit like std::span from C++20, but with a more limited interface.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <typename Value, size_t Extent = dynamicExtent>
|
||||
class Span : private detail::NumBase<Extent> // for empty-base optimisation
|
||||
{
|
||||
using Base = detail::NumBase<Extent>;
|
||||
|
||||
public:
|
||||
static constexpr auto extent = Extent;
|
||||
|
||||
template <size_t e = extent, std::enable_if_t<e == 0 || e == dynamicExtent, int> = 0>
|
||||
constexpr Span() {}
|
||||
|
||||
template <typename It>
|
||||
constexpr Span (It it, size_t end)
|
||||
: Base (end), ptr (detail::toAddress (it)) {}
|
||||
|
||||
template <typename Range, std::enable_if_t<detail::isSpanCompatibleRange<Range, Value>, int> = 0>
|
||||
constexpr Span (Range&& range)
|
||||
: Base (static_cast<size_t> (std::size (range))),
|
||||
ptr (std::data (range)) {}
|
||||
|
||||
template <typename OtherValue,
|
||||
size_t OtherExtent,
|
||||
std::enable_if_t<(Extent == dynamicExtent || Extent == OtherExtent)
|
||||
&& detail::isSpanConvertible<OtherValue, Value>, int> = 0>
|
||||
constexpr Span (const Span<OtherValue, OtherExtent>& other) noexcept
|
||||
: Base (other.size()), ptr (other.data()) {}
|
||||
|
||||
constexpr Span (const Span&) = default;
|
||||
|
||||
constexpr Span& operator= (const Span&) = default;
|
||||
|
||||
constexpr Span (Span&&) noexcept = default;
|
||||
|
||||
constexpr Span& operator= (Span&&) noexcept = default;
|
||||
|
||||
using Base::size;
|
||||
constexpr size_t getSizeInBytes() const { return size() * sizeof (Value); }
|
||||
|
||||
constexpr Value* begin() const { return ptr; }
|
||||
constexpr Value* end() const { return ptr + size(); }
|
||||
|
||||
constexpr auto& front() const { return ptr[0]; }
|
||||
constexpr auto& back() const { return ptr[size() - 1]; }
|
||||
|
||||
constexpr auto& operator[] (size_t index) const { return ptr[index]; }
|
||||
constexpr Value* data() const { return ptr; }
|
||||
|
||||
constexpr bool empty() const { return size() == 0; }
|
||||
|
||||
private:
|
||||
Value* ptr = nullptr;
|
||||
};
|
||||
|
||||
template <typename T, typename End>
|
||||
Span (T, End) -> Span<std::remove_pointer_t<decltype (detail::toAddress (std::declval<T>()))>>;
|
||||
|
||||
template <typename T, size_t N>
|
||||
Span (T (&) [N]) -> Span<T, N>;
|
||||
|
||||
template <typename T, size_t N>
|
||||
Span (std::array<T, N>&) -> Span<T, N>;
|
||||
|
||||
template <typename T, size_t N>
|
||||
Span (const std::array<T, N>&) -> Span<const T, N>;
|
||||
|
||||
template <typename Range>
|
||||
Span (Range&& r) -> Span<std::remove_pointer_t<decltype (std::data (r))>>;
|
||||
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,218 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
#if JUCE_UNIT_TESTS
|
||||
|
||||
class SparseSetTests final : public UnitTest
|
||||
{
|
||||
public:
|
||||
SparseSetTests()
|
||||
: UnitTest ("SparseSet class", UnitTestCategories::containers)
|
||||
{}
|
||||
|
||||
void runTest() override
|
||||
{
|
||||
beginTest ("basic operations");
|
||||
{
|
||||
SparseSet<int> set;
|
||||
|
||||
expect (set.isEmpty());
|
||||
expectEquals (set.size(), 0);
|
||||
expectEquals (set.getNumRanges(), 0);
|
||||
expect (set.getTotalRange().isEmpty());
|
||||
|
||||
set.addRange ({0, 10});
|
||||
expect (! set.isEmpty());
|
||||
expectEquals (set.size(), 10);
|
||||
expectEquals (set.getNumRanges(), 1);
|
||||
expect (! set.getTotalRange().isEmpty());
|
||||
expect (set.getRange (0) == Range<int> (0, 10));
|
||||
|
||||
expectEquals (set[0], 0);
|
||||
expectEquals (set[5], 5);
|
||||
expectEquals (set[9], 9);
|
||||
// Index out of range yields a default value for a type
|
||||
expectEquals (set[10], 0);
|
||||
expect (set.contains (0));
|
||||
expect (set.contains (9));
|
||||
expect (! set.contains (10));
|
||||
}
|
||||
|
||||
beginTest ("adding ranges");
|
||||
{
|
||||
SparseSet<int> set;
|
||||
|
||||
// Adding same range twice should yield just a single range
|
||||
set.addRange ({0, 10});
|
||||
set.addRange ({0, 10});
|
||||
expectEquals (set.getNumRanges(), 1);
|
||||
expect (set.getRange (0) == Range<int> (0, 10));
|
||||
|
||||
// Adding already included range does not increase num ranges
|
||||
set.addRange ({0, 2});
|
||||
expectEquals (set.getNumRanges(), 1);
|
||||
set.addRange ({8, 10});
|
||||
expectEquals (set.getNumRanges(), 1);
|
||||
set.addRange ({2, 5});
|
||||
expectEquals (set.getNumRanges(), 1);
|
||||
|
||||
// Adding non adjacent range includes total number of ranges
|
||||
set.addRange ({-10, -5});
|
||||
expectEquals (set.getNumRanges(), 2);
|
||||
expect (set.getRange (0) == Range<int> (-10, -5));
|
||||
expect (set.getRange (1) == Range<int> (0, 10));
|
||||
expect (set.getTotalRange() == Range<int> (-10, 10));
|
||||
|
||||
set.addRange ({15, 20});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
expect (set.getRange (0) == Range<int> (-10, -5));
|
||||
expect (set.getRange (1) == Range<int> (0, 10));
|
||||
expect (set.getRange (2) == Range<int> (15, 20));
|
||||
expect (set.getTotalRange() == Range<int> (-10, 20));
|
||||
|
||||
// Adding adjacent ranges merges them.
|
||||
set.addRange ({-5, -3});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
expect (set.getRange (0) == Range<int> (-10, -3));
|
||||
expect (set.getRange (1) == Range<int> (0, 10));
|
||||
expect (set.getRange (2) == Range<int> (15, 20));
|
||||
expect (set.getTotalRange() == Range<int> (-10, 20));
|
||||
|
||||
set.addRange ({20, 25});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
expect (set.getRange (0) == Range<int> (-10, -3));
|
||||
expect (set.getRange (1) == Range<int> (0, 10));
|
||||
expect (set.getRange (2) == Range<int> (15, 25));
|
||||
expect (set.getTotalRange() == Range<int> (-10, 25));
|
||||
|
||||
// Adding range containing other ranges merges them
|
||||
set.addRange ({-50, 50});
|
||||
expectEquals (set.getNumRanges(), 1);
|
||||
expect (set.getRange (0) == Range<int> (-50, 50));
|
||||
expect (set.getTotalRange() == Range<int> (-50, 50));
|
||||
}
|
||||
|
||||
beginTest ("removing ranges");
|
||||
{
|
||||
SparseSet<int> set;
|
||||
|
||||
set.addRange ({-20, -10});
|
||||
set.addRange ({0, 10});
|
||||
set.addRange ({20, 30});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
|
||||
// Removing ranges not included in the set has no effect
|
||||
set.removeRange ({-5, 5});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
|
||||
// Removing partially overlapping range
|
||||
set.removeRange ({-15, 5});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
expect (set.getRange (0) == Range<int> (-20, -15));
|
||||
expect (set.getRange (1) == Range<int> (5, 10));
|
||||
expect (set.getRange (2) == Range<int> (20, 30));
|
||||
|
||||
// Removing subrange of existing range
|
||||
set.removeRange ({20, 22});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
expect (set.getRange (2) == Range<int> (22, 30));
|
||||
|
||||
set.removeRange ({28, 30});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
expect (set.getRange (2) == Range<int> (22, 28));
|
||||
|
||||
set.removeRange ({24, 26});
|
||||
expectEquals (set.getNumRanges(), 4);
|
||||
expect (set.getRange (0) == Range<int> (-20, -15));
|
||||
expect (set.getRange (1) == Range<int> (5, 10));
|
||||
expect (set.getRange (2) == Range<int> (22, 24));
|
||||
expect (set.getRange (3) == Range<int> (26, 28));
|
||||
}
|
||||
|
||||
beginTest ("XORing ranges");
|
||||
{
|
||||
SparseSet<int> set;
|
||||
set.addRange ({0, 10});
|
||||
|
||||
set.invertRange ({0, 10});
|
||||
expectEquals (set.getNumRanges(), 0);
|
||||
set.invertRange ({0, 10});
|
||||
expectEquals (set.getNumRanges(), 1);
|
||||
|
||||
set.invertRange ({4, 6});
|
||||
expectEquals (set.getNumRanges(), 2);
|
||||
expect (set.getRange (0) == Range<int> (0, 4));
|
||||
expect (set.getRange (1) == Range<int> (6, 10));
|
||||
|
||||
set.invertRange ({-2, 2});
|
||||
expectEquals (set.getNumRanges(), 3);
|
||||
expect (set.getRange (0) == Range<int> (-2, 0));
|
||||
expect (set.getRange (1) == Range<int> (2, 4));
|
||||
expect (set.getRange (2) == Range<int> (6, 10));
|
||||
}
|
||||
|
||||
beginTest ("range contains & overlaps checks");
|
||||
{
|
||||
SparseSet<int> set;
|
||||
set.addRange ({0, 10});
|
||||
|
||||
expect (set.containsRange (Range<int> (0, 2)));
|
||||
expect (set.containsRange (Range<int> (8, 10)));
|
||||
expect (set.containsRange (Range<int> (0, 10)));
|
||||
|
||||
expect (! set.containsRange (Range<int> (-2, 0)));
|
||||
expect (! set.containsRange (Range<int> (-2, 10)));
|
||||
expect (! set.containsRange (Range<int> (10, 12)));
|
||||
expect (! set.containsRange (Range<int> (0, 12)));
|
||||
|
||||
expect (set.overlapsRange (Range<int> (0, 2)));
|
||||
expect (set.overlapsRange (Range<int> (8, 10)));
|
||||
expect (set.overlapsRange (Range<int> (0, 10)));
|
||||
|
||||
expect (! set.overlapsRange (Range<int> (-2, 0)));
|
||||
expect ( set.overlapsRange (Range<int> (-2, 10)));
|
||||
expect (! set.overlapsRange (Range<int> (10, 12)));
|
||||
expect ( set.overlapsRange (Range<int> (0, 12)));
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
static SparseSetTests sparseSetTests;
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace juce
|
||||
@@ -0,0 +1,280 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
Holds a set of primitive values, storing them as a set of ranges.
|
||||
|
||||
This container acts like an array, but can efficiently hold large contiguous
|
||||
ranges of values. It's quite a specialised class, mostly useful for things
|
||||
like keeping the set of selected rows in a listbox.
|
||||
|
||||
The type used as a template parameter must be an integer type, such as int, short,
|
||||
int64, etc.
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
template <class Type>
|
||||
class SparseSet
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
SparseSet() = default;
|
||||
|
||||
SparseSet (const SparseSet&) = default;
|
||||
SparseSet& operator= (const SparseSet&) = default;
|
||||
|
||||
SparseSet (SparseSet&& other) noexcept : ranges (std::move (other.ranges)) {}
|
||||
SparseSet& operator= (SparseSet&& other) noexcept { ranges = std::move (other.ranges); return *this; }
|
||||
|
||||
//==============================================================================
|
||||
/** Clears the set. */
|
||||
void clear() { ranges.clear(); }
|
||||
|
||||
/** Checks whether the set is empty.
|
||||
This is much quicker than using (size() == 0).
|
||||
*/
|
||||
bool isEmpty() const noexcept { return ranges.isEmpty(); }
|
||||
|
||||
/** Returns the number of values in the set.
|
||||
|
||||
Because of the way the data is stored, this method can take longer if there
|
||||
are a lot of items in the set. Use isEmpty() for a quick test of whether there
|
||||
are any items.
|
||||
*/
|
||||
Type size() const noexcept
|
||||
{
|
||||
Type total = {};
|
||||
|
||||
for (auto& r : ranges)
|
||||
total += r.getLength();
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
/** Returns one of the values in the set.
|
||||
|
||||
@param index the index of the value to retrieve, in the range 0 to (size() - 1).
|
||||
@returns the value at this index, or 0 if it's out-of-range
|
||||
*/
|
||||
Type operator[] (Type index) const noexcept
|
||||
{
|
||||
Type total = {};
|
||||
|
||||
for (auto& r : ranges)
|
||||
{
|
||||
auto end = total + r.getLength();
|
||||
|
||||
if (index < end)
|
||||
return r.getStart() + (index - total);
|
||||
|
||||
total = end;
|
||||
}
|
||||
|
||||
return {};
|
||||
}
|
||||
|
||||
/** Checks whether a particular value is in the set. */
|
||||
bool contains (Type valueToLookFor) const noexcept
|
||||
{
|
||||
for (auto& r : ranges)
|
||||
{
|
||||
if (r.getStart() > valueToLookFor)
|
||||
break;
|
||||
|
||||
if (r.getEnd() > valueToLookFor)
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Returns the number of contiguous blocks of values.
|
||||
@see getRange
|
||||
*/
|
||||
int getNumRanges() const noexcept { return ranges.size(); }
|
||||
|
||||
/** Returns one of the contiguous ranges of values stored.
|
||||
@param rangeIndex the index of the range to look up, between 0
|
||||
and (getNumRanges() - 1)
|
||||
@see getTotalRange
|
||||
*/
|
||||
Range<Type> getRange (int rangeIndex) const noexcept { return ranges[rangeIndex]; }
|
||||
|
||||
/** Returns the range between the lowest and highest values in the set.
|
||||
@see getRange
|
||||
*/
|
||||
Range<Type> getTotalRange() const noexcept
|
||||
{
|
||||
if (ranges.isEmpty())
|
||||
return {};
|
||||
|
||||
return { ranges.getFirst().getStart(),
|
||||
ranges.getLast().getEnd() };
|
||||
}
|
||||
|
||||
//==============================================================================
|
||||
/** Adds a range of contiguous values to the set.
|
||||
e.g. addRange (Range \<int\> (10, 14)) will add (10, 11, 12, 13) to the set.
|
||||
*/
|
||||
void addRange (Range<Type> range)
|
||||
{
|
||||
if (! range.isEmpty())
|
||||
{
|
||||
removeRange (range);
|
||||
ranges.add (range);
|
||||
std::sort (ranges.begin(), ranges.end(),
|
||||
[] (Range<Type> a, Range<Type> b) { return a.getStart() < b.getStart(); });
|
||||
simplify();
|
||||
}
|
||||
}
|
||||
|
||||
/** Removes a range of values from the set.
|
||||
e.g. removeRange (Range\<int\> (10, 14)) will remove (10, 11, 12, 13) from the set.
|
||||
*/
|
||||
void removeRange (Range<Type> rangeToRemove)
|
||||
{
|
||||
if (getTotalRange().intersects (rangeToRemove) && ! rangeToRemove.isEmpty())
|
||||
{
|
||||
for (int i = ranges.size(); --i >= 0;)
|
||||
{
|
||||
auto& r = ranges.getReference (i);
|
||||
|
||||
if (r.getEnd() <= rangeToRemove.getStart())
|
||||
break;
|
||||
|
||||
if (r.getStart() >= rangeToRemove.getEnd())
|
||||
continue;
|
||||
|
||||
if (rangeToRemove.contains (r))
|
||||
{
|
||||
ranges.remove (i);
|
||||
}
|
||||
else if (r.contains (rangeToRemove))
|
||||
{
|
||||
auto r1 = r.withEnd (rangeToRemove.getStart());
|
||||
auto r2 = r.withStart (rangeToRemove.getEnd());
|
||||
|
||||
// this should be covered in if (rangeToRemove.contains (r))
|
||||
jassert (! r1.isEmpty() || ! r2.isEmpty());
|
||||
|
||||
r = r1;
|
||||
|
||||
if (r.isEmpty())
|
||||
r = r2;
|
||||
|
||||
if (! r1.isEmpty() && ! r2.isEmpty())
|
||||
ranges.insert (i + 1, r2);
|
||||
}
|
||||
else if (rangeToRemove.getEnd() > r.getEnd())
|
||||
{
|
||||
r.setEnd (rangeToRemove.getStart());
|
||||
}
|
||||
else
|
||||
{
|
||||
r.setStart (rangeToRemove.getEnd());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** Does an XOR of the values in a given range. */
|
||||
void invertRange (Range<Type> range)
|
||||
{
|
||||
SparseSet newItems;
|
||||
newItems.addRange (range);
|
||||
|
||||
for (auto& r : ranges)
|
||||
newItems.removeRange (r);
|
||||
|
||||
removeRange (range);
|
||||
|
||||
for (auto& r : newItems.ranges)
|
||||
addRange (r);
|
||||
}
|
||||
|
||||
/** Checks whether any part of a given range overlaps any part of this set. */
|
||||
bool overlapsRange (Range<Type> range) const noexcept
|
||||
{
|
||||
if (! range.isEmpty())
|
||||
for (auto& r : ranges)
|
||||
if (r.intersects (range))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Checks whether the whole of a given range is contained within this one. */
|
||||
bool containsRange (Range<Type> range) const noexcept
|
||||
{
|
||||
if (! range.isEmpty())
|
||||
for (auto& r : ranges)
|
||||
if (r.contains (range))
|
||||
return true;
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Returns the set as a list of ranges, which you may want to iterate over. */
|
||||
const Array<Range<Type>>& getRanges() const noexcept { return ranges; }
|
||||
|
||||
//==============================================================================
|
||||
bool operator== (const SparseSet& other) const noexcept { return ranges == other.ranges; }
|
||||
bool operator!= (const SparseSet& other) const noexcept { return ranges != other.ranges; }
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
Array<Range<Type>> ranges;
|
||||
|
||||
void simplify()
|
||||
{
|
||||
for (int i = ranges.size(); --i > 0;)
|
||||
{
|
||||
auto& r1 = ranges.getReference (i - 1);
|
||||
auto& r2 = ranges.getReference (i);
|
||||
|
||||
if (r1.getEnd() == r2.getStart())
|
||||
{
|
||||
r1.setEnd (r2.getEnd());
|
||||
ranges.remove (i);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace juce
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,386 @@
|
||||
/*
|
||||
==============================================================================
|
||||
|
||||
This file is part of the JUCE framework.
|
||||
Copyright (c) Raw Material Software Limited
|
||||
|
||||
JUCE is an open source framework subject to commercial or open source
|
||||
licensing.
|
||||
|
||||
By downloading, installing, or using the JUCE framework, or combining the
|
||||
JUCE framework with any other source code, object code, content or any other
|
||||
copyrightable work, you agree to the terms of the JUCE End User Licence
|
||||
Agreement, and all incorporated terms including the JUCE Privacy Policy and
|
||||
the JUCE Website Terms of Service, as applicable, which will bind you. If you
|
||||
do not agree to the terms of these agreements, we will not license the JUCE
|
||||
framework to you, and you must discontinue the installation or download
|
||||
process and cease use of the JUCE framework.
|
||||
|
||||
JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/
|
||||
JUCE Privacy Policy: https://juce.com/juce-privacy-policy
|
||||
JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/
|
||||
|
||||
Or:
|
||||
|
||||
You may also use this code under the terms of the AGPLv3:
|
||||
https://www.gnu.org/licenses/agpl-3.0.en.html
|
||||
|
||||
THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL
|
||||
WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF
|
||||
MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED.
|
||||
|
||||
==============================================================================
|
||||
*/
|
||||
|
||||
namespace juce
|
||||
{
|
||||
|
||||
//==============================================================================
|
||||
/**
|
||||
A variant class, that can be used to hold a range of primitive values.
|
||||
|
||||
A var object can hold a range of simple primitive values, strings, or
|
||||
any kind of ReferenceCountedObject. The var class is intended to act like
|
||||
the kind of values used in dynamic scripting languages.
|
||||
|
||||
You can save/load var objects either in a small, proprietary binary format
|
||||
using writeToStream()/readFromStream(), or as JSON by using the JSON class.
|
||||
|
||||
@see JSON, DynamicObject
|
||||
|
||||
@tags{Core}
|
||||
*/
|
||||
class JUCE_API var
|
||||
{
|
||||
public:
|
||||
//==============================================================================
|
||||
/** This structure is passed to a NativeFunction callback, and contains invocation
|
||||
details about the function's arguments and context.
|
||||
*/
|
||||
struct JUCE_API NativeFunctionArgs
|
||||
{
|
||||
NativeFunctionArgs (const var& thisObject, const var* args, int numArgs) noexcept;
|
||||
|
||||
const var& thisObject;
|
||||
const var* arguments;
|
||||
int numArguments;
|
||||
};
|
||||
|
||||
using NativeFunction = std::function<var (const NativeFunctionArgs&)>;
|
||||
|
||||
//==============================================================================
|
||||
/** Creates a void variant. */
|
||||
var() noexcept;
|
||||
|
||||
/** Destructor. */
|
||||
~var() noexcept;
|
||||
|
||||
var (const var& valueToCopy);
|
||||
var (int value) noexcept;
|
||||
var (int64 value) noexcept;
|
||||
var (bool value) noexcept;
|
||||
var (double value) noexcept;
|
||||
var (const char* value);
|
||||
var (const wchar_t* value);
|
||||
var (const String& value);
|
||||
var (const Array<var>& value);
|
||||
var (const StringArray& value);
|
||||
var (ReferenceCountedObject* object);
|
||||
var (NativeFunction method) noexcept;
|
||||
var (const void* binaryData, size_t dataSize);
|
||||
var (const MemoryBlock& binaryData);
|
||||
|
||||
var& operator= (const var& valueToCopy);
|
||||
var& operator= (int value);
|
||||
var& operator= (int64 value);
|
||||
var& operator= (bool value);
|
||||
var& operator= (double value);
|
||||
var& operator= (const char* value);
|
||||
var& operator= (const wchar_t* value);
|
||||
var& operator= (const String& value);
|
||||
var& operator= (const MemoryBlock& value);
|
||||
var& operator= (const Array<var>& value);
|
||||
var& operator= (ReferenceCountedObject* object);
|
||||
var& operator= (NativeFunction method);
|
||||
|
||||
var (var&&) noexcept;
|
||||
var (String&&);
|
||||
var (MemoryBlock&&);
|
||||
var (Array<var>&&);
|
||||
var& operator= (var&&) noexcept;
|
||||
var& operator= (String&&);
|
||||
|
||||
void swapWith (var& other) noexcept;
|
||||
|
||||
/** Returns a var object that can be used where you need the javascript "undefined" value. */
|
||||
static var undefined() noexcept;
|
||||
|
||||
//==============================================================================
|
||||
operator int() const noexcept;
|
||||
operator int64() const noexcept;
|
||||
operator bool() const noexcept;
|
||||
operator float() const noexcept;
|
||||
operator double() const noexcept;
|
||||
operator String() const;
|
||||
String toString() const;
|
||||
|
||||
/** If this variant holds an array, this provides access to it.
|
||||
NOTE: Beware when you use this - the array pointer is only valid for the lifetime
|
||||
of the variant that returned it, so be very careful not to call this method on temporary
|
||||
var objects that are the return-value of a function, and which may go out of scope before
|
||||
you use the array!
|
||||
*/
|
||||
Array<var>* getArray() const noexcept;
|
||||
|
||||
/** If this variant holds a memory block, this provides access to it.
|
||||
NOTE: Beware when you use this - the MemoryBlock pointer is only valid for the lifetime
|
||||
of the variant that returned it, so be very careful not to call this method on temporary
|
||||
var objects that are the return-value of a function, and which may go out of scope before
|
||||
you use the MemoryBlock!
|
||||
*/
|
||||
MemoryBlock* getBinaryData() const noexcept;
|
||||
|
||||
ReferenceCountedObject* getObject() const noexcept;
|
||||
DynamicObject* getDynamicObject() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
bool isVoid() const noexcept;
|
||||
bool isUndefined() const noexcept;
|
||||
bool isInt() const noexcept;
|
||||
bool isInt64() const noexcept;
|
||||
bool isBool() const noexcept;
|
||||
bool isDouble() const noexcept;
|
||||
bool isString() const noexcept;
|
||||
bool isObject() const noexcept;
|
||||
bool isArray() const noexcept;
|
||||
bool isBinaryData() const noexcept;
|
||||
bool isMethod() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns a span over the elements of the contained array, or an empty span if
|
||||
the variant currently contains a non-array type.
|
||||
*/
|
||||
Span<var> getArrayElements() &;
|
||||
|
||||
/** Returns a span over the elements of the contained array, or an empty span if
|
||||
the variant currently contains a non-array type.
|
||||
*/
|
||||
Span<const var> getArrayElements() const &;
|
||||
|
||||
/** Returns a span over the properties of the contained object, or an empty span if
|
||||
the variant currently contains a non-object type.
|
||||
*/
|
||||
Span<NamedValue> getObjectElements() &;
|
||||
|
||||
/** Returns a span over the properties of the contained object, or an empty span if
|
||||
the variant currently contains a non-object type.
|
||||
*/
|
||||
Span<const NamedValue> getObjectElements() const &;
|
||||
|
||||
/* These functions are deleted to help avoid accidentally forming a span over a temporary. */
|
||||
Span<var> getArrayElements() && = delete;
|
||||
Span<const var> getArrayElements() const && = delete;
|
||||
Span<NamedValue> getObjectElements() && = delete;
|
||||
Span<const NamedValue> getObjectElements() const && = delete;
|
||||
|
||||
//==============================================================================
|
||||
/** Returns true if this var has the same value as the one supplied.
|
||||
Note that this ignores the type, so a string var "123" and an integer var with the
|
||||
value 123 are considered to be equal.
|
||||
|
||||
Note that equality checking depends on the "wrapped" type of the object on which
|
||||
equals() is called. That means the following code will convert the right-hand-side
|
||||
argument to a string and compare the string values, because the object on the
|
||||
left-hand-side was initialised from a string:
|
||||
@code var ("123").equals (var (123)) @endcode
|
||||
However, the following code will convert the right-hand-side argument to a double
|
||||
and compare the values as doubles, because the object on the left-hand-side was
|
||||
initialised from a double:
|
||||
@code var (45.6).equals ("45.6000") @endcode
|
||||
|
||||
@see equalsWithSameType
|
||||
*/
|
||||
bool equals (const var& other) const noexcept;
|
||||
|
||||
/** Returns true if this var has the same value and type as the one supplied.
|
||||
This differs from equals() because e.g. "123" and 123 will be considered different.
|
||||
@see equals
|
||||
*/
|
||||
bool equalsWithSameType (const var& other) const noexcept;
|
||||
|
||||
/** Returns true if this var has the same type as the one supplied. */
|
||||
bool hasSameTypeAs (const var& other) const noexcept;
|
||||
|
||||
/** Returns a deep copy of this object.
|
||||
For simple types this just returns a copy, but if the object contains any arrays
|
||||
or DynamicObjects, they will be cloned (recursively).
|
||||
*/
|
||||
var clone() const noexcept;
|
||||
|
||||
//==============================================================================
|
||||
/** If the var is an array, this returns the number of elements.
|
||||
If the var isn't actually an array, this will return 0.
|
||||
*/
|
||||
int size() const;
|
||||
|
||||
/** If the var is an array, this can be used to return one of its elements.
|
||||
To call this method, you must make sure that the var is actually an array, and
|
||||
that the index is a valid number. If these conditions aren't met, behaviour is
|
||||
undefined.
|
||||
For more control over the array's contents, you can call getArray() and manipulate
|
||||
it directly as an Array\<var\>.
|
||||
*/
|
||||
const var& operator[] (int arrayIndex) const;
|
||||
|
||||
/** If the var is an array, this can be used to return one of its elements.
|
||||
To call this method, you must make sure that the var is actually an array, and
|
||||
that the index is a valid number. If these conditions aren't met, behaviour is
|
||||
undefined.
|
||||
For more control over the array's contents, you can call getArray() and manipulate
|
||||
it directly as an Array\<var\>.
|
||||
*/
|
||||
var& operator[] (int arrayIndex);
|
||||
|
||||
/** Appends an element to the var, converting it to an array if it isn't already one.
|
||||
If the var isn't an array, it will be converted to one, and if its value was non-void,
|
||||
this value will be kept as the first element of the new array. The parameter value
|
||||
will then be appended to it.
|
||||
For more control over the array's contents, you can call getArray() and manipulate
|
||||
it directly as an Array\<var\>.
|
||||
*/
|
||||
void append (const var& valueToAppend);
|
||||
|
||||
/** Inserts an element to the var, converting it to an array if it isn't already one.
|
||||
If the var isn't an array, it will be converted to one, and if its value was non-void,
|
||||
this value will be kept as the first element of the new array. The parameter value
|
||||
will then be inserted into it.
|
||||
For more control over the array's contents, you can call getArray() and manipulate
|
||||
it directly as an Array\<var\>.
|
||||
*/
|
||||
void insert (int index, const var& value);
|
||||
|
||||
/** If the var is an array, this removes one of its elements.
|
||||
If the index is out-of-range or the var isn't an array, nothing will be done.
|
||||
For more control over the array's contents, you can call getArray() and manipulate
|
||||
it directly as an Array\<var\>.
|
||||
*/
|
||||
void remove (int index);
|
||||
|
||||
/** Treating the var as an array, this resizes it to contain the specified number of elements.
|
||||
If the var isn't an array, it will be converted to one, and if its value was non-void,
|
||||
this value will be kept as the first element of the new array before resizing.
|
||||
For more control over the array's contents, you can call getArray() and manipulate
|
||||
it directly as an Array\<var\>.
|
||||
*/
|
||||
void resize (int numArrayElementsWanted);
|
||||
|
||||
/** If the var is an array, this searches it for the first occurrence of the specified value,
|
||||
and returns its index.
|
||||
If the var isn't an array, or if the value isn't found, this returns -1.
|
||||
*/
|
||||
int indexOf (const var& value) const;
|
||||
|
||||
//==============================================================================
|
||||
/** If this variant is an object, this returns one of its properties. */
|
||||
const var& operator[] (const Identifier& propertyName) const;
|
||||
/** If this variant is an object, this returns one of its properties. */
|
||||
const var& operator[] (const char* propertyName) const;
|
||||
/** If this variant is an object, this returns one of its properties, or a default
|
||||
fallback value if the property is not set. */
|
||||
var getProperty (const Identifier& propertyName, const var& defaultReturnValue) const;
|
||||
/** Returns true if this variant is an object and if it has the given property. */
|
||||
bool hasProperty (const Identifier& propertyName) const noexcept;
|
||||
|
||||
/** Invokes a named method call with no arguments. */
|
||||
var call (const Identifier& method) const;
|
||||
/** Invokes a named method call with one argument. */
|
||||
var call (const Identifier& method, const var& arg1) const;
|
||||
/** Invokes a named method call with 2 arguments. */
|
||||
var call (const Identifier& method, const var& arg1, const var& arg2) const;
|
||||
/** Invokes a named method call with 3 arguments. */
|
||||
var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3);
|
||||
/** Invokes a named method call with 4 arguments. */
|
||||
var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4) const;
|
||||
/** Invokes a named method call with 5 arguments. */
|
||||
var call (const Identifier& method, const var& arg1, const var& arg2, const var& arg3, const var& arg4, const var& arg5) const;
|
||||
/** Invokes a named method call with a list of arguments. */
|
||||
var invoke (const Identifier& method, const var* arguments, int numArguments) const;
|
||||
/** If this object is a method, this returns the function pointer. */
|
||||
NativeFunction getNativeFunction() const;
|
||||
|
||||
//==============================================================================
|
||||
/** Writes a binary representation of this value to a stream.
|
||||
The data can be read back later using readFromStream().
|
||||
@see JSON
|
||||
*/
|
||||
void writeToStream (OutputStream& output) const;
|
||||
|
||||
/** Reads back a stored binary representation of a value.
|
||||
The data in the stream must have been written using writeToStream(), or this
|
||||
will have unpredictable results. Arrays nested more than 256 levels deep are
|
||||
read as void values.
|
||||
@see JSON
|
||||
*/
|
||||
static var readFromStream (InputStream& input);
|
||||
|
||||
//==============================================================================
|
||||
#if JUCE_ALLOW_STATIC_NULL_VARIABLES
|
||||
/** @cond */
|
||||
[[deprecated ("This was a static empty var object, but is now deprecated as it's too easy to accidentally "
|
||||
"use it indirectly during a static constructor leading to hard-to-find order-of-initialisation "
|
||||
"problems. Use var() or {} instead. For returning an empty var from a function by reference, "
|
||||
"use a function-local static var and return that.")]]
|
||||
static const var null;
|
||||
/** @endcond */
|
||||
#endif
|
||||
|
||||
private:
|
||||
//==============================================================================
|
||||
struct VariantType;
|
||||
struct Instance;
|
||||
|
||||
union ValueUnion
|
||||
{
|
||||
int intValue;
|
||||
int64 int64Value;
|
||||
bool boolValue;
|
||||
double doubleValue;
|
||||
char stringValue[sizeof (String)];
|
||||
ReferenceCountedObject* objectValue;
|
||||
MemoryBlock* binaryValue;
|
||||
NativeFunction* methodValue;
|
||||
};
|
||||
|
||||
friend bool canCompare (const var&, const var&);
|
||||
|
||||
const VariantType* type;
|
||||
ValueUnion value{};
|
||||
|
||||
Array<var>* convertToArray();
|
||||
var (const VariantType&) noexcept;
|
||||
|
||||
// This is needed to prevent the wrong constructor/operator being called
|
||||
var (const ReferenceCountedObject*) = delete;
|
||||
var& operator= (const ReferenceCountedObject*) = delete;
|
||||
var (const void*) = delete;
|
||||
var& operator= (const void*) = delete;
|
||||
};
|
||||
|
||||
/** Compares the values of two var objects, using the var::equals() comparison. */
|
||||
JUCE_API bool operator== (const var&, const var&);
|
||||
/** Compares the values of two var objects, using the var::equals() comparison. */
|
||||
JUCE_API bool operator!= (const var&, const var&);
|
||||
/** Compares the values of two var objects, using the var::equals() comparison. */
|
||||
JUCE_API bool operator< (const var&, const var&);
|
||||
/** Compares the values of two var objects, using the var::equals() comparison. */
|
||||
JUCE_API bool operator<= (const var&, const var&);
|
||||
/** Compares the values of two var objects, using the var::equals() comparison. */
|
||||
JUCE_API bool operator> (const var&, const var&);
|
||||
/** Compares the values of two var objects, using the var::equals() comparison. */
|
||||
JUCE_API bool operator>= (const var&, const var&);
|
||||
|
||||
JUCE_API bool operator== (const var&, const String&);
|
||||
JUCE_API bool operator!= (const var&, const String&);
|
||||
JUCE_API bool operator== (const var&, const char*);
|
||||
JUCE_API bool operator!= (const var&, const char*);
|
||||
} // namespace juce
|
||||
Reference in New Issue
Block a user