Add beast_vflib compatibility module and stand alone unit test app

This commit is contained in:
Patrick Dehne
2013-10-22 23:19:52 +02:00
committed by Vinnie Falco
parent 1f97a239dc
commit 55dd5b5547
19 changed files with 1146 additions and 202 deletions

View File

@@ -21,8 +21,6 @@
*/
//==============================================================================
#include "../network/URL.h"
void MACAddress::findAllAddresses (Array<MACAddress>& result)
{
ifaddrs* addrs = nullptr;
@@ -97,202 +95,3 @@ bool Process::openEmailWithAttachments (const String& targetEmailAddress,
}
#endif
}
//==============================================================================
class URLConnectionState
: public Thread
, LeakChecked <URLConnectionState>
, public Uncopyable
{
public:
URLConnectionState (NSURLRequest* req)
: Thread ("http connection"),
contentLength (-1),
delegate (nil),
request ([req retain]),
connection (nil),
data ([[NSMutableData data] retain]),
headers (nil),
initialised (false),
hasFailed (false),
hasFinished (false)
{
static DelegateClass cls;
delegate = [cls.createInstance() init];
DelegateClass::setState (delegate, this);
}
~URLConnectionState()
{
stop();
[connection release];
[data release];
[request release];
[headers release];
[delegate release];
}
bool start (URL::OpenStreamProgressCallback* callback, void* context)
{
startThread();
while (isThreadRunning() && ! initialised)
{
if (callback != nullptr)
callback (context, -1, (int) [[request HTTPBody] length]);
Thread::sleep (1);
}
return connection != nil && ! hasFailed;
}
void stop()
{
[connection cancel];
stopThread (10000);
}
int read (char* dest, int numBytes)
{
int numDone = 0;
while (numBytes > 0)
{
const int available = bmin (numBytes, (int) [data length]);
if (available > 0)
{
const ScopedLock sl (dataLock);
[data getBytes: dest length: (NSUInteger) available];
[data replaceBytesInRange: NSMakeRange (0, (NSUInteger) available) withBytes: nil length: 0];
numDone += available;
numBytes -= available;
dest += available;
}
else
{
if (hasFailed || hasFinished)
break;
Thread::sleep (1);
}
}
return numDone;
}
void didReceiveResponse (NSURLResponse* response)
{
{
const ScopedLock sl (dataLock);
[data setLength: 0];
}
initialised = true;
contentLength = [response expectedContentLength];
[headers release];
headers = nil;
if ([response isKindOfClass: [NSHTTPURLResponse class]])
headers = [[((NSHTTPURLResponse*) response) allHeaderFields] retain];
}
void didFailWithError (NSError* error)
{
DBG (nsStringToBeast ([error description])); (void) error;
hasFailed = true;
initialised = true;
signalThreadShouldExit();
}
void didReceiveData (NSData* newData)
{
const ScopedLock sl (dataLock);
[data appendData: newData];
initialised = true;
}
void didSendBodyData (int /*totalBytesWritten*/, int /*totalBytesExpected*/)
{
}
void finishedLoading()
{
hasFinished = true;
initialised = true;
signalThreadShouldExit();
}
void run() override
{
connection = [[NSURLConnection alloc] initWithRequest: request
delegate: delegate];
while (! threadShouldExit())
{
BEAST_AUTORELEASEPOOL
{
[[NSRunLoop currentRunLoop] runUntilDate: [NSDate dateWithTimeIntervalSinceNow: 0.01]];
}
}
}
int64 contentLength;
CriticalSection dataLock;
NSObject* delegate;
NSURLRequest* request;
NSURLConnection* connection;
NSMutableData* data;
NSDictionary* headers;
bool initialised, hasFailed, hasFinished;
private:
//==============================================================================
struct DelegateClass : public ObjCClass <NSObject>
{
DelegateClass() : ObjCClass <NSObject> ("BEASTAppDelegate_")
{
addIvar <URLConnectionState*> ("state");
addMethod (@selector (connection:didReceiveResponse:), didReceiveResponse, "v@:@@");
addMethod (@selector (connection:didFailWithError:), didFailWithError, "v@:@@");
addMethod (@selector (connection:didReceiveData:), didReceiveData, "v@:@@");
addMethod (@selector (connection:didSendBodyData:totalBytesWritten:totalBytesExpectedToWrite:totalBytesExpectedToWrite:),
connectionDidSendBodyData, "v@:@iii");
addMethod (@selector (connectionDidFinishLoading:), connectionDidFinishLoading, "v@:@");
registerClass();
}
static void setState (id self, URLConnectionState* state) { object_setInstanceVariable (self, "state", state); }
static URLConnectionState* getState (id self) { return getIvar<URLConnectionState*> (self, "state"); }
private:
static void didReceiveResponse (id self, SEL, NSURLConnection*, NSURLResponse* response)
{
getState (self)->didReceiveResponse (response);
}
static void didFailWithError (id self, SEL, NSURLConnection*, NSError* error)
{
getState (self)->didFailWithError (error);
}
static void didReceiveData (id self, SEL, NSURLConnection*, NSData* newData)
{
getState (self)->didReceiveData (newData);
}
static void connectionDidSendBodyData (id self, SEL, NSURLConnection*, NSInteger, NSInteger totalBytesWritten, NSInteger totalBytesExpected)
{
getState (self)->didSendBodyData (totalBytesWritten, totalBytesExpected);
}
static void connectionDidFinishLoading (id self, SEL, NSURLConnection*)
{
getState (self)->finishedLoading();
}
};
};

View File

@@ -0,0 +1,22 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include "beast_vflib.h"
#include "threads/ThreadWithServiceQueue.cpp"

View File

@@ -0,0 +1,27 @@
//------------------------------------------------------------------------------
/*
This file is part of BeastUtils: https://github.com/pdehne/BeastUtils
Copyright 2013, Patrick Dehne <patrick@sonicweb.de>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_VFLIB_H_INCLUDED
#define BEAST_VFLIB_H_INCLUDED
#include "functor/BindHelper.h"
#include "threads/BindableServiceQueue.h"
#include "threads/ThreadWithServiceQueue.h"
#endif

View File

@@ -0,0 +1,78 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_VFLIB_BINDHELPER_H_INCLUDED
#define BEAST_VFLIB_BINDHELPER_H_INCLUDED
namespace beast {
/** Calls bind() for you.
The UnaryFunction will be called with this signature:
@code
template <typename Functor>
void operator() (Functor const& f);
@endcode
Where Functor is the result of the bind.
*/
template <class UnaryFunction>
class BindHelper
{
private:
// Gets called with the bind
UnaryFunction m_f;
public:
template <typename Arg>
explicit BindHelper (Arg& arg)
: m_f (arg)
{ }
template <typename Arg>
explicit BindHelper (Arg const& arg)
: m_f (arg)
{ }
template <typename F>
void operator() (F const& f) const
{ m_f (f); }
template <typename F, class P1>
void operator() (F const& f, P1 const& p1) const
{ m_f (bind (f, p1)); }
template <typename F, class P1, class P2>
void operator() (F const& f, P1 const& p1, P2 const& p2) const
{ m_f (bind (f, p1, p2)); }
template <typename F, class P1, class P2, class P3>
void operator() (F const& f, P1 const& p1, P2 const& p2, P3 const& p3) const
{ m_f (bind (f, p1, p2, p3)); }
template <typename F, class P1, class P2, class P3, class P4>
void operator() (F const& f, P1 const& p1, P2 const& p2, P3 const& p3, P4 const& p4) const
{ m_f (bind (f, p1, p2, p3, p4)); }
template <typename F, class P1, class P2, class P3, class P4, class P5>
void operator() (F const& f, P1 const& p1, P2 const& p2, P3 const& p3, P4 const& p4, P5 const& p5) const
{ m_f (bind (f, p1, p2, p3, p4, p5)); }
};
}
#endif

View File

@@ -0,0 +1,71 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_VFLIB_BINDABLESERVICEQUEUETYPE_H_INCLUDED
#define BEAST_VFLIB_BINDABLESERVICEQUEUETYPE_H_INCLUDED
#include "beast/Threads.h"
#include "../functor/BindHelper.h"
namespace beast {
template <class Allocator = std::allocator <char> >
class BindableServiceQueueType
: public ServiceQueueType <Allocator>
{
public:
explicit BindableServiceQueueType (int expectedConcurrency = 1,
Allocator alloc = Allocator())
: ServiceQueueType<Allocator>(expectedConcurrency, alloc)
, queue(*this)
, call(*this)
{
}
struct BindHelperPost
{
BindableServiceQueueType<Allocator>& m_queue;
explicit BindHelperPost (BindableServiceQueueType<Allocator>& queue)
: m_queue (queue)
{ }
template <typename F>
void operator() (F const& f) const
{ m_queue.post ( F (f) ); }
};
struct BindHelperDispatch
{
BindableServiceQueueType<Allocator>& m_queue;
explicit BindHelperDispatch (BindableServiceQueueType<Allocator>& queue)
: m_queue (queue)
{ }
template <typename F>
void operator() (F const& f) const
{ m_queue.dispatch ( F (f) ); }
};
BindHelper <BindHelperPost> const queue;
BindHelper <BindHelperDispatch> const call;
};
typedef BindableServiceQueueType <std::allocator <char> > BindableServiceQueue;
}
#endif

View File

@@ -0,0 +1,246 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#include "ThreadWithServiceQueue.h"
namespace beast {
ThreadWithServiceQueue::ThreadWithServiceQueue (const String& name)
: Thread (name)
, m_entryPoints(nullptr)
, m_calledStart(false)
, m_calledStop(false)
, m_interrupted(false)
{
}
ThreadWithServiceQueue::~ThreadWithServiceQueue()
{
stop(true);
}
void ThreadWithServiceQueue::start (EntryPoints* const entryPoints)
{
{
CriticalSection::ScopedLockType lock (m_mutex);
// start() MUST be called.
bassert (!m_calledStart);
m_calledStart = true;
}
m_entryPoints = entryPoints;
startThread();
}
void ThreadWithServiceQueue::stop (bool const wait)
{
{
CriticalSection::ScopedLockType lock (m_mutex);
// start() MUST be called.
bassert (m_calledStart);
if (!m_calledStop)
{
m_calledStop = true;
{
CriticalSection::ScopedUnlockType unlock (m_mutex);
call (&Thread::signalThreadShouldExit, this);
// something could slip in here
// m_queue.close();
}
}
}
if (wait)
waitForThreadToExit();
}
void ThreadWithServiceQueue::interrupt ()
{
call (&ThreadWithServiceQueue::doInterrupt, this);
}
bool ThreadWithServiceQueue::interruptionPoint ()
{
return m_interrupted;
}
void ThreadWithServiceQueue::run ()
{
m_entryPoints->threadInit();
while (! this->threadShouldExit())
{
run_one();
bool isInterrupted = m_entryPoints->threadIdle();
isInterrupted |= interruptionPoint();
if(isInterrupted)
{
// We put this call into the service queue to make
// sure we get through to threadIdle without
// waiting
call (&ThreadWithServiceQueue::doWakeUp, this);
}
}
m_entryPoints->threadExit();
}
void ThreadWithServiceQueue::doInterrupt ()
{
m_interrupted = true;
}
void ThreadWithServiceQueue::doWakeUp ()
{
m_interrupted = false;
}
//------------------------------------------------------------------------------
namespace detail
{
//------------------------------------------------------------------------------
class BindableServiceQueueTests
: public UnitTest
{
public:
struct BindableServiceQueueRunner
: public ThreadWithServiceQueue::EntryPoints
{
ThreadWithServiceQueue m_worker;
int cCallCount, c1CallCount, idleInterruptedCount;
BindableServiceQueueRunner()
: m_worker("BindableServiceQueueRunner")
, cCallCount(0)
, c1CallCount(0)
, idleInterruptedCount(0)
{
}
void start()
{
m_worker.start(this);
}
void stop()
{
m_worker.stop(true);
}
void interrupt()
{
m_worker.interrupt();
}
void c()
{
m_worker.queue(&BindableServiceQueueRunner::cImpl, this);
}
void cImpl()
{
cCallCount++;
}
void c1(int p1)
{
m_worker.queue(&BindableServiceQueueRunner::c1Impl, this, p1);
}
void c1Impl(int p1)
{
c1CallCount++;
}
bool threadIdle ()
{
bool interrupted = m_worker.interruptionPoint ();
if(interrupted)
idleInterruptedCount++;
return interrupted;
}
};
static int const calls = 10000;
void performCalls()
{
Random r;
r.setSeedRandomly();
BindableServiceQueueRunner runner;
beginTestCase("Calls and interruptions");
runner.start();
for(std::size_t i=0; i<calls; i++)
{
int wait = r.nextLargeNumber(10).toInteger();
if(wait % 2)
runner.c();
else
runner.c1Impl(wait);
}
for(std::size_t i=0; i<calls; i++)
runner.interrupt();
runner.stop();
// We can only reason that the idle method must have been interrupted
// at least once
expect ((runner.cCallCount + runner.c1CallCount) == calls);
expect (runner.idleInterruptedCount > 0);
}
void runTest()
{
performCalls ();
}
BindableServiceQueueTests () : UnitTest ("BindableServiceQueue", "beast")
{
}
};
static BindableServiceQueueTests bindableServiceQueueTests;
}
}

View File

@@ -0,0 +1,91 @@
//------------------------------------------------------------------------------
/*
This file is part of Beast: https://github.com/vinniefalco/Beast
Copyright 2013, Vinnie Falco <vinnie.falco@gmail.com>
Permission to use, copy, modify, and/or distribute this software for any
purpose with or without fee is hereby granted, provided that the above
copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
ANY SPECIAL , DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
*/
//==============================================================================
#ifndef BEAST_VFLIB_THREADWITHSERVICEQUEUE_H_INCLUDED
#define BEAST_VFLIB_THREADWITHSERVICEQUEUE_H_INCLUDED
#include "BindableServiceQueue.h"
namespace beast {
/** TODO: Queued calls no longer interrupt the idle method at the moment
use an explicit call to interrupt() if you want to also interrupt the
idle method when queuing calls
*/
class ThreadWithServiceQueue
: public BindableServiceQueue
, public Thread
{
public:
/** Entry points for a ThreadWithCallQueue.
*/
class EntryPoints
{
public:
virtual ~EntryPoints () { }
virtual void threadInit () { }
virtual void threadExit () { }
virtual bool threadIdle ()
{
bool interrupted = false;
return interrupted;
}
};
explicit ThreadWithServiceQueue (const String& name);
~ThreadWithServiceQueue();
void start (EntryPoints* const entryPoints);
void stop (bool const wait);
// Should be called periodically by the idle function.
// There are two possible results:
//
// #1 Returns false. The idle function may continue or return.
// #2 Returns true. The idle function should return as soon as possible.
//
// May only be called on the service queue thead
bool interruptionPoint ();
/* Interrupts the idle function.
*/
void interrupt ();
private:
void run ();
void doInterrupt ();
void doWakeUp ();
private:
EntryPoints* m_entryPoints;
bool m_calledStart;
bool m_calledStop;
bool m_interrupted;
CriticalSection m_mutex;
};
}
#endif