I'm writing a program involving network I/O, so send
and recv
are used, which are POSIX functions. They return a ssize_t
, which is POSIX-specific too.
The wrappers look like this ATM:
ssize_t sock_send(int sock, const void* msg, size_t len) {
return send(sock, msg, len, 0);
}
Even though I'm heavily depending on POSIX in my current implementation, I want to make the interface stick closely to the standard because I am planning on writing a Windows implementation later, where POSIX isn't necessarily available (dammit, Windows!).
What would be a good substitution for ssize_t
as specified by the C11 standard? Perhaps ptrdiff_t
?
Or how should I approach this issue otherwise?
If the type ssize_t
is not defined, you can just define it yourself. It is supposed to be a signed
type with the same size as size_t
. Technically, the type ptrdiff_t
should not be smaller than size_t
, but it could be larger to accommodate for the larger range.
Here is a portable way to define it:
#include <limits.h>
#include <stddef.h>
#include <inttypes.h>
#include <stdint.h>
#if SIZE_MAX == UINT_MAX
typedef int ssize_t; /* common 32 bit case */
#define SSIZE_MIN INT_MIN
#define SSIZE_MAX INT_MAX
#elif SIZE_MAX == ULONG_MAX
typedef long ssize_t; /* linux 64 bits */
#define SSIZE_MIN LONG_MIN
#define SSIZE_MAX LONG_MAX
#elif SIZE_MAX == ULLONG_MAX
typedef long long ssize_t; /* windows 64 bits */
#define SSIZE_MIN LLONG_MIN
#define SSIZE_MAX LLONG_MAX
#elif SIZE_MAX == USHRT_MAX
typedef short ssize_t; /* is this even possible? */
#define SSIZE_MIN SHRT_MIN
#define SSIZE_MAX SHRT_MAX
#elif SIZE_MAX == UINTMAX_MAX
typedef uintmax_t ssize_t; /* last resort, chux suggestion */
#define SSIZE_MIN INTMAX_MIN
#define SSIZE_MAX INTMAX_MAX
#else
#error platform has exotic SIZE_MAX
#endif
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With