Ejemplo n.º 1
0
        void run()
        {
            int n = 0;
            Random r;

            while (! threadShouldExit())
            {
                int num = r.nextInt (2000) + 1;

                int start1, size1, start2, size2;
                fifo.prepareToWrite (num, start1, size1, start2, size2);

                bassert (size1 >= 0 && size2 >= 0);
                bassert (size1 == 0 || (start1 >= 0 && start1 < fifo.getTotalSize()));
                bassert (size2 == 0 || (start2 >= 0 && start2 < fifo.getTotalSize()));

                for (int i = 0; i < size1; ++i)
                    buffer [start1 + i] = n++;

                for (int i = 0; i < size2; ++i)
                    buffer [start2 + i] = n++;

                fifo.finishedWrite (size1 + size2);
            }
        }
Ejemplo n.º 2
0
void RangeSet::checkInternalConsistency () const noexcept
{
#if BEAST_DEBUG
    if (mRanges.size () > 1)
    {
        const_iterator const last = std::prev (mRanges.end ());

        for (const_iterator cur = mRanges.begin (); cur != last; ++cur)
        {
            const_iterator const next = std::next (cur);

            bassert (cur->first <= cur->second);

            bassert (next->first <= next->second);

            bassert (cur->second + 1 < next->first);
        }
    }
    else if (mRanges.size () == 1)
    {
        const_iterator const iter = mRanges.begin ();

        bassert (iter->first <= iter->second);
    }

#endif
}
Ejemplo n.º 3
0
// Called every time io_service::run() returns and a thread will exit.
//
void IoServicePool::onThreadExit()
{
    // service must be stopping for threads to exit.
    bassert (isStopping());

    // must have at least count 1
    bassert (m_threadsRunning.load() > 0);

    if (--m_threadsRunning == 0)
    {
        // last thread just exited
        stopped ();
    }
}
    // Given the old list and the new list for a source, this
    // computes which validators were added or removed, and
    // updates some statistics.
    //
    static void compareLists (Validator::List const& oldList,
                              Validator::List const& newList,
                              CompareCallback& callback)
    {
        // Validator::List is always sorted so walk both arrays and
        // do an element-wise comparison to perform set calculations.
        //
        int i = 0;
        int j = 0;
        while (i < oldList.size () || j < newList.size ())
        {
            if (i < oldList.size () && j < newList.size ())
            {
                int const compare = Validator::Compare::compareElements (
                    oldList [i], newList [j]);

                if (compare < 0)
                {
                    callback.onValidatorRemoved (*oldList [i]);
                    ++i;
                }
                else if (compare > 0)
                {
                    callback.onValidatorAdded (*newList [j]);
                    ++j;
                }
                else
                {
                    bassert (oldList [i] == newList [j]);

                    callback.onValidatorUnchanged (*newList [j]);
                    ++i;
                    ++j;
                }
            }
            else if (i < oldList.size ())
            {
                callback.onValidatorRemoved (*oldList [i]);
                ++i;
            }
            else
            {
                bassert (j < newList.size ());

                callback.onValidatorAdded (*newList [j]);
                ++j;
            }
        }
    }
MemoryBlock::MemoryBlock (const void* const dataToInitialiseFrom, const size_t sizeInBytes)
    : size (sizeInBytes)
{
    bassert (((ssize_t) sizeInBytes) >= 0);

    if (size > 0)
    {
        bassert (dataToInitialiseFrom != nullptr); // non-zero size, but a zero pointer passed-in?

        data.malloc (size);

        if (dataToInitialiseFrom != nullptr)
            memcpy (data, dataToInitialiseFrom, size);
    }
}
Ejemplo n.º 6
0
    void addJob (JobType type, std::string const& name,
        boost::function <void (Job&)> const& jobFunc)
    {
        bassert (type != jtINVALID);

        // FIXME: Workaround incorrect client shutdown ordering
        // do not add jobs to a queue with no threads
        bassert (type == jtCLIENT || m_workers.getNumberOfThreads () > 0);

        {
            // If this goes off it means that a child didn't follow 
            // the Stoppable API rules. A job may only be added if:
            //
            //  - The JobQueue has NOT stopped 
            //          AND
            //      * We are currently processing jobs
            //          OR
            //      * We have have pending jobs
            //          OR
            //      * Not all children are stopped
            //  
            ScopedLock lock (m_mutex);
            bassert (! isStopped() && (
                m_processCount>0 ||
                ! m_jobSet.empty () ||
                ! areChildrenStopped()));
        }

        // Don't even add it to the queue if we're stopping
        // and the job type is marked for skipOnStop.
        //
        if (isStopping() && skipOnStop (type))
        {
            m_journal.debug <<
                "Skipping addJob ('" << name << "')";
            return;
        }

        {
            ScopedLock lock (m_mutex);

            std::pair< std::set <Job>::iterator, bool > it =
                m_jobSet.insert (Job (
                    type, name, ++m_lastJob, m_loads[type], jobFunc, m_cancelCallback));

            queueJob (*it.first, lock);
        }
    }
Ejemplo n.º 7
0
ScopedPointer <UnitTest::Suite>& UnitTest::run (
    UnitTests* const runner)
{
    bassert (runner != nullptr);
    m_runner = runner;
    m_random = m_runner->m_random;

    m_suite = new Suite (m_className, m_packageName);

    initialise();

#if 0
    try
    {
        runTest();
    }
    catch (...)
    {
        failException ();
    }
#else
    runTest ();
#endif

    shutdown();

    finishCase ();

    m_suite->secondsElapsed = RelativeTime (
        Time::getCurrentTime () - m_suite->whenStarted).inSeconds ();

    return m_suite;
}
Ejemplo n.º 8
0
Random& UnitTest::random()
{
    // This method's only valid while the test is being run!
    bassert (m_runner != nullptr);

    return m_random;
}
Ejemplo n.º 9
0
void UnitTest::pass ()
{
    // If this goes off it means you forgot to call beginTestCase()!
    bassert (m_case != nullptr);

    m_case->items.add (Item (true));
}
Ejemplo n.º 10
0
//==============================================================================
bool TemporaryFile::overwriteTargetFileWithTemporary() const
{
    // This method only works if you created this object with the constructor
    // that takes a target file!
    bassert (targetFile != File::nonexistent ());

    if (temporaryFile.exists())
    {
        // Have a few attempts at overwriting the file before giving up..
        for (int i = 5; --i >= 0;)
        {
            if (temporaryFile.moveFileTo (targetFile))
                return true;

            Thread::sleep (100);
        }
    }
    else
    {
        // There's no temporary file to use. If your write failed, you should
        // probably check, and not bother calling this method.
        bassertfalse;
    }

    return false;
}
Ejemplo n.º 11
0
DirectoryIterator::DirectoryIterator (const File& directory, bool recursive,
                                      const String& pattern, const int type)
    : wildCards (parseWildcards (pattern)),
      fileFinder (directory, (recursive || wildCards.size() > 1) ? "*" : pattern),
      wildCard (pattern),
      path (File::addTrailingSeparator (directory.getFullPathName())),
      index (-1),
      totalNumFiles (-1),
      whatToLookFor (type),
      isRecursive (recursive),
      hasBeenAdvanced (false)
{
    // you have to specify the type of files you're looking for!
    bassert ((type & (File::findFiles | File::findDirectories)) != 0);
    bassert (type > 0 && type <= 7);
}
Ejemplo n.º 12
0
 ~Manager ()
 {
     signalThreadShouldExit ();
     notify ();
     waitForThreadToExit ();
     bassert (m_items.empty ());
 }
Ejemplo n.º 13
0
char* MemoryOutputStream::prepareToWrite (size_t numBytes)
{
    bassert ((std::ptrdiff_t) numBytes >= 0);
    size_t storageNeeded = position + numBytes;

    char* data;

    if (blockToUse != nullptr)
    {
        if (storageNeeded >= blockToUse->getSize())
            blockToUse->ensureSize ((storageNeeded + std::min (storageNeeded / 2, (size_t) (1024 * 1024)) + 32) & ~31u);

        data = static_cast <char*> (blockToUse->getData());
    }
    else
    {
        if (storageNeeded > availableSize)
            return nullptr;

        data = static_cast <char*> (externalData);
    }

    char* const writePointer = data + position;
    position += numBytes;
    size = std::max (size, position);
    return writePointer;
}
Ejemplo n.º 14
0
Journal::Stream::Stream (Sink& sink, Severity level, bool active)
    : m_sink (&sink)
    , m_level (level)
    , m_disabled (! active)
{
    bassert (level != kDisabled);
}
Ejemplo n.º 15
0
void JNIClassBase::initialise (JNIEnv* env)
{
    classRef = (jclass) env->NewGlobalRef (env->FindClass (classPath));
    bassert (classRef != 0);

    initialiseFields (env);
}
Ejemplo n.º 16
0
// Return the largest number not in the set that is less than the given number
//
std::uint32_t RangeSet::prevMissing (std::uint32_t v) const
{
    std::uint32_t result = absent;

    if (v != 0)
    {
        checkInternalConsistency ();

        // Handle the case where the loop reaches the terminating condition
        //
        result = v - 1;

        for (const_reverse_iterator cur = mRanges.rbegin (); cur != mRanges.rend (); ++cur)
        {
            // See if v-1 is in the range
            if (contains (*cur, result))
            {
                result = cur->first - 1;
                break;
            }
        }
    }

    bassert (result == absent || !hasValue (result));

    return result;
}
Ejemplo n.º 17
0
void PropertyStream::Source::add (Source& source)
{
    SharedState::Access state (m_state);
    SharedState::Access childState (source.m_state);
    bassert (childState->parent == nullptr);
    state->children.push_back (childState->item);
    childState->parent = this;
}
Ejemplo n.º 18
0
void Workers::pauseAllThreadsAndWait ()
{
    setNumberOfThreads (0);

    m_allPaused.wait ();

    bassert (numberOfCurrentlyRunningTasks () == 0);
}
    ~Manager ()
    {
        m_shouldStop = true;

        m_thread.interrupt ();

        bassert (m_items.empty ());
    }
void DeadlineTimer::setRecurringExpiration (double secondsUntilDeadline)
{
    bassert (secondsUntilDeadline > 0);

    Time const when = Time::getCurrentTime () + RelativeTime (secondsUntilDeadline);

    m_manager->activate (this, secondsUntilDeadline, when);
}
Ejemplo n.º 21
0
void DeadlineTimer::setRecurringExpiration (double secondsUntilDeadline)
{
    bassert (secondsUntilDeadline != 0);

    RelativeTime const when (
        RelativeTime::fromStartup() + secondsUntilDeadline);

    Manager::instance().activate (*this, secondsUntilDeadline, when);
}
void MemoryBlock::replaceWith (const void* const srcData, const size_t numBytes)
{
    if (numBytes > 0)
    {
        bassert (srcData != nullptr); // this must not be null!
        setSize (numBytes);
        memcpy (data, srcData, numBytes);
    }
}
Ejemplo n.º 23
0
var var::invokeMethod (DynamicObject* const target, const var* const arguments, const int numArguments) const
{
    bassert (target != nullptr);

    if (isMethod())
        return (target->*(value.methodValue)) (arguments, numArguments);

    return var::null;
}
Ejemplo n.º 24
0
bool MemoryOutputStream::write (const void* const buffer, size_t howMany)
{
    bassert (buffer != nullptr && ((ssize_t) howMany) >= 0);

    if (howMany > 0)
        memcpy (prepareToWrite (howMany), buffer, howMany);

    return true;
}
Ejemplo n.º 25
0
void PropertyStream::Source::remove (
    SharedState::Access& state, SharedState::Access& childState)
{
    bassert (childState->parent == this);
    state->children.erase (
        state->children.iterator_to (
            childState->item));
    childState->parent = nullptr;
}
Ejemplo n.º 26
0
void AbstractFifo::finishedWrite (int numWritten) noexcept
{
    bassert (numWritten >= 0 && numWritten < bufferSize);
    int newEnd = validEnd.value + numWritten;
    if (newEnd >= bufferSize)
        newEnd -= bufferSize;

    validEnd = newEnd;
}
Ejemplo n.º 27
0
void session::rollback()
{
    bassert(m_bInTransaction);
    m_bInTransaction = false;
    Error error = hard_exec("ROLLBACK");

    if (error)
        throw error;
}
void MemoryBlock::append (const void* const srcData, const size_t numBytes)
{
    if (numBytes > 0)
    {
        bassert (srcData != nullptr); // this must not be null!
        const size_t oldSize = size;
        setSize (size + numBytes);
        memcpy (data + oldSize, srcData, numBytes);
    }
}
Ejemplo n.º 29
0
void LoadEvent::stop ()
{
    bassert (m_isRunning);

    m_timeStopped = beast::RelativeTime::fromStartup();
    m_secondsRunning += (m_timeStopped - m_timeStarted).inSeconds();

    m_isRunning = false;
    m_loadMonitor.addLoadSample (*this);
}
MemoryBlock::MemoryBlock (const MemoryBlock& other)
    : size (other.size)
{
    if (size > 0)
    {
        bassert (other.data != nullptr);
        data.malloc (size);
        memcpy (data, other.data, size);
    }
}