From fd06aba05381055ab56e1ec81d56055b66462f0b Mon Sep 17 00:00:00 2001 From: Garrett D'Amore Date: Thu, 26 Apr 2018 15:36:13 -0700 Subject: fixes #375 integer types are error prone This change converts the various integer types like nng_socket in the public API to opaque structures that are passed by value. Basically we just wrap the integer ID. This "hack" give us strong type checks by the compiler (yay!), at the expense of not being able to directly use these as numbers (so comparisions for example don't work, and neither does initialization to zero using the normal method. Comparison of disassembly output shows that at least with the optimizer enabled there is no difference in the compiler output between using a structure or an integral value. --- src/nng.h | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) (limited to 'src/nng.h') diff --git a/src/nng.h b/src/nng.h index 52fc95a1..92c2f396 100644 --- a/src/nng.h +++ b/src/nng.h @@ -59,11 +59,33 @@ extern "C" { #define NNG_MAXADDRLEN (128) // Types common to nng. -typedef uint32_t nng_socket; -typedef uint32_t nng_ctx; -typedef uint32_t nng_dialer; -typedef uint32_t nng_listener; -typedef uint32_t nng_pipe; + +// Identifiers are wrapped in a structure to improve compiler validation +// of incorrect passing. This gives us strong type checking. Modern +// compilers compile passing these by value to identical code as passing +// the integer type (at least with optimization applied). Please do not +// access the ID member directly. + +typedef struct nng_ctx_s { + uint32_t id; +} nng_ctx; + +typedef struct nng_dialer_s { + uint32_t id; +} nng_dialer; + +typedef struct nng_listener_s { + uint32_t id; +} nng_listener; + +typedef struct nng_pipe_s { + uint32_t id; +} nng_pipe; + +typedef struct nng_socket_s { + uint32_t id; +} nng_socket; + typedef int32_t nng_duration; // in milliseconds typedef struct nng_msg nng_msg; typedef struct nng_snapshot nng_snapshot; -- cgit v1.2.3-70-g09d2