From 0e2e1c40f4b22d940886de6e8555eeef9c076808 Mon Sep 17 00:00:00 2001 From: Garrett D'Amore Date: Sat, 21 Jan 2017 12:05:35 -0800 Subject: Implement nng_send and nng_recv convenience routines. --- src/nng.c | 72 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 72 insertions(+) (limited to 'src/nng.c') diff --git a/src/nng.c b/src/nng.c index 587900bd..a8b145f9 100644 --- a/src/nng.c +++ b/src/nng.c @@ -18,6 +18,8 @@ // Pretty much every function calls the nni_platform_init to check against // fork related activity. +#include + int nng_open(nng_socket *sidp, uint16_t proto) { @@ -95,6 +97,43 @@ nng_peer(nng_socket sid) } +int +nng_recv(nng_socket sid, void *buf, size_t *szp, int flags) +{ + nng_msg *msg; + int rv; + + // Note that while it would be nice to make this a zero copy operation, + // its not normally possible if a size was specified. + if ((rv = nng_recvmsg(sid, &msg, flags & ~(NNG_FLAG_ALLOC))) != 0) { + return (rv); + } + if (!(flags & NNG_FLAG_ALLOC)) { + memcpy(buf, nng_msg_body(msg), + *szp > nng_msg_len(msg) ? nng_msg_len(msg) : *szp); + *szp = nng_msg_len(msg); + } else { + // We'd really like to avoid a separate data copy, but since + // we have allocated messages with headroom, we can't really + // make free() work on the base pointer. We'd have to have + // some other API for this. Folks that want zero copy had + // better use nng_recvmsg() instead. + void *nbuf; + + if ((nbuf = nni_alloc(nng_msg_len(msg))) == NULL) { + nng_msg_free(msg); + return (NNG_ENOMEM); + } + + *(void **) buf = nbuf; + memcpy(nbuf, nni_msg_body(msg), nni_msg_len(msg)); + *szp = nng_msg_len(msg); + } + nni_msg_free(msg); + return (0); +} + + int nng_recvmsg(nng_socket sid, nng_msg **msgp, int flags) { @@ -120,6 +159,39 @@ nng_recvmsg(nng_socket sid, nng_msg **msgp, int flags) } +int +nng_send(nng_socket sid, void *buf, size_t len, int flags) +{ + nng_msg *msg; + int rv; + + if ((rv = nng_msg_alloc(&msg, len)) != 0) { + return (rv); + } + memcpy(nng_msg_body(msg), buf, len); + if ((rv = nng_sendmsg(sid, msg, flags)) != 0) { + nng_msg_free(msg); + } else if (flags & NNG_FLAG_ALLOC) { + nni_free(buf, len); + } + return (rv); +} + + +void * +nng_alloc(size_t sz) +{ + return (nni_alloc(sz)); +} + + +void +nng_free(void *buf, size_t sz) +{ + nni_free(buf, sz); +} + + int nng_sendmsg(nng_socket sid, nng_msg *msg, int flags) { -- cgit v1.2.3-70-g09d2