Skip to content

Commit

Permalink
Add message clone
Browse files Browse the repository at this point in the history
  • Loading branch information
jaracil committed Oct 25, 2019
1 parent a02ec34 commit 9cc21b8
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
38 changes: 38 additions & 0 deletions src/pubsub.c
Original file line number Diff line number Diff line change
Expand Up @@ -194,6 +194,44 @@ ps_msg_t *ps_new_msg(const char *topic, uint32_t flags, ...) {
return msg;
}

ps_msg_t *ps_dup_msg(ps_msg_t const *msg_orig) {

ps_msg_t *msg = malloc(sizeof(ps_msg_t));
memcpy(msg, msg_orig, sizeof(ps_msg_t));
msg->_ref = 1;
if (msg_orig->topic != NULL) {
msg->topic = strdup(msg_orig->topic);
}
if (msg_orig->rtopic != NULL) {
msg->rtopic = strdup(msg_orig->rtopic);
}

if (IS_STR(msg_orig)) {
if (msg_orig->str_val != NULL) {
msg->str_val = strdup(msg_orig->str_val);
}
} else if (IS_BUF(msg_orig)) {
msg->buf_val.ptr = malloc(msg_orig->buf_val.sz);
memcpy(msg->buf_val.ptr, msg_orig->buf_val.ptr, msg_orig->buf_val.sz);
} else if (IS_ERR(msg_orig)) {
if (msg_orig->err_val.desc != NULL) {
msg->err_val.desc = strdup(msg_orig->err_val.desc);
}
}
__sync_add_and_fetch(&stat_live_msg, 1);
return msg;
}

void ps_msg_set_topic(ps_msg_t *msg, const char *topic) {
if (msg->topic != NULL) {
free(msg->topic); // Free previous topic
msg->topic = NULL;
}
if (topic != NULL) {
msg->topic = strdup(topic);
}
}

void ps_msg_set_rtopic(ps_msg_t *msg, const char *rtopic) {
if (msg->rtopic != NULL) {
free(msg->rtopic); // Free previous rtopic
Expand Down
16 changes: 16 additions & 0 deletions src/pubsub.h
Original file line number Diff line number Diff line change
Expand Up @@ -108,6 +108,14 @@ void ps_init(void);
*/
ps_msg_t *ps_new_msg(const char *topic, uint32_t flags, ...);

/**
* @brief ps_dup_msg duplicates message
*
* @param msg_orig message to duplicate
* @return ps_msg_t
*/
ps_msg_t *ps_dup_msg(ps_msg_t const *msg_orig);

/**
* @brief ps_ref_msg increments the message reference counter
*
Expand All @@ -123,6 +131,14 @@ ps_msg_t *ps_ref_msg(ps_msg_t *msg);
*/
void ps_unref_msg(ps_msg_t *msg);

/**
* @brief ps_msg_set_topic sets message topic
*
* @param msg message to set the topic
* @param topic string with the topic
*/
void ps_msg_set_topic(ps_msg_t *msg, const char *topic);

/**
* @brief ps_msg_set_rtopic sets a response topic for the message
*
Expand Down

0 comments on commit 9cc21b8

Please sign in to comment.