Sturk 1.0.2
Publish-subscribe C implementation.
Loading...
Searching...
No Matches
Message broker

This is an example usage of the message broker.

Defining API for messages

Defining the size of the message

static size_t size(void)
{
return sizeof(char[8]);
}

Defining the message constructor

static void init(StLoad* load, va_list vlist)
{
const char* format = va_arg(vlist, char*);
vsnprintf(load, 8, format, vlist);
}
char StLoad
Opaque data type that represents the message load.
Definition broker.h:80

Defining the message destructor

static void deinit(StLoad* load)
{
(void)load;
}

Defining a vtable

const struct StLoadVt SAMPLE_LOAD_API[] = {
{.size = size, .ctor = init, .dtor = deinit}};
Vtable for message construction.
Definition broker.h:87
size_t(* size)(void)
Callback for obtaining the size of the load.
Definition broker.h:98

Complete API

static size_t size(void)
{
return sizeof(char[8]);
}
static void init(StLoad* load, va_list vlist)
{
const char* format = va_arg(vlist, char*);
vsnprintf(load, 8, format, vlist);
}
static void deinit(StLoad* load)
{
(void)load;
}
const struct StLoadVt SAMPLE_LOAD_API[] = {
{.size = size, .ctor = init, .dtor = deinit}};

Publish and subscribe

Initializing a broker

StBroker* broker = broker_create(SAMPLE_LOAD_API);
struct StBroker StBroker
The message broker.
Definition broker.h:135
#define broker_create
Definition broker.h:50
Note

‍[!NOTE] The API passed here is the previously defined vtable.

Creating a subscriber

struct StSubscriber StSubscriber
The subscriber.
Definition broker.h:142
#define subscriber_create
Definition broker.h:62

Subscribing to a topic

subscribe(sber, "test");
#define subscribe
Definition broker.h:47

Publishing to a topic

publish(broker_search(broker, "test"), "%X", 0xF00D);
#define broker_search
Definition broker.h:56
#define publish
Definition broker.h:44
Note

‍[!NOTE] The behaviour of the publish procedure is controlled with the message constructor.

Receiving a message

load = subscriber_await(sber);
#define subscriber_await
Definition broker.h:68

Complete example

TEST(subscriber, should_receive_enqueued_message)
{
StBroker* broker = broker_create(SAMPLE_LOAD_API);
StLoad* load = NULL;
subscribe(sber, "test");
publish(broker_search(broker, "test"), "%X", 0xF00D);
TEST_ASSERT_NULL(channel_gettopic(load_getchan(load)));
load = subscriber_await(sber);
TEST_ASSERT_EQUAL_STRING("F00D", load);
TEST_ASSERT_NULL("test", channel_gettopic(load_getchan(load)));
broker_destroy(broker);
}
#define load_getchan
Definition broker.h:77
#define channel_gettopic
Definition broker.h:59
#define broker_destroy
Definition broker.h:53