Files
libicsneo/include/icsneo/communication/message/callback/messagecallback.h
T
Paul Hollinsky c32d027b2d MessageCallback: Tolerate being created with nullptr filter
Communication does this in waitForMessageSync if a filter
is not passed in.

This fixes a crash in icsneoWaitForRxMessagesWithTimeOut
for the legacy API.

For good measure, creation with an empty std::function will
immediately throw an std::bad_function_call back at the
caller, rather than letting that happen on the callback thread.

I'm also making the members const here so they are provably
always non-null (and not empty, for the function).
2022-02-21 22:55:49 -05:00

50 lines
1.4 KiB
C++

#ifndef __MESSAGECALLBACK_H_
#define __MESSAGECALLBACK_H_
#ifdef __cplusplus
#include "icsneo/communication/message/message.h"
#include "icsneo/communication/message/filter/messagefilter.h"
#include <memory>
#include <functional>
namespace icsneo {
class MessageCallback {
public:
typedef std::function< void( std::shared_ptr<Message> ) > fn_messageCallback;
MessageCallback(fn_messageCallback cb, std::shared_ptr<MessageFilter> f)
: callback(cb), filter(f ? f : std::make_shared<MessageFilter>()) {
if(!cb)
throw std::bad_function_call();
}
MessageCallback(fn_messageCallback cb, MessageFilter f = MessageFilter())
: MessageCallback(cb, std::make_shared<MessageFilter>(f)) {}
// Allow the filter to be placed first if the user wants (maybe in the case of a lambda)
MessageCallback(std::shared_ptr<MessageFilter> f, fn_messageCallback cb)
: MessageCallback(cb, f) {}
MessageCallback(MessageFilter f, fn_messageCallback cb)
: MessageCallback(cb, std::make_shared<MessageFilter>(f)) {}
virtual bool callIfMatch(const std::shared_ptr<Message>& message) const {
bool ret = filter->match(message);
if(ret)
callback(message);
return ret;
}
const MessageFilter& getFilter() const { return *filter; }
const fn_messageCallback& getCallback() const { return callback; }
protected:
const fn_messageCallback callback;
const std::shared_ptr<MessageFilter> filter;
};
}
#endif // __cplusplus
#endif