1
Fork 0
mirror of https://github.com/RGBCube/serenity synced 2025-07-27 11:57:35 +00:00

LibC: Clean up htonl() and ntohl() families.

Use __builtin_bswap() intrinsics for the byte swapping. Also don't swap on
systems where BYTE_ORDER != LITTLE_ENDIAN. This doesn't really affect us
at the moment since Serenity only targets x86, but I figured it doesn't hurt
to do things right. :^)
This commit is contained in:
Andreas Kling 2019-06-26 20:04:35 +02:00
parent eb129bd730
commit 3c4497aa2d

View file

@ -1,5 +1,6 @@
#pragma once #pragma once
#include <endian.h>
#include <sys/cdefs.h> #include <sys/cdefs.h>
#include <sys/socket.h> #include <sys/socket.h>
@ -10,26 +11,28 @@ __BEGIN_DECLS
const char* inet_ntop(int af, const void* src, char* dst, socklen_t); const char* inet_ntop(int af, const void* src, char* dst, socklen_t);
int inet_pton(int af, const char* src, void* dst); int inet_pton(int af, const char* src, void* dst);
static inline uint16_t htons(uint16_t hs) inline uint16_t htons(uint16_t value)
{ {
uint8_t* s = (uint8_t*)&hs; #if BYTE_ORDER == LITTLE_ENDIAN
return (uint16_t)(s[0] << 8 | s[1]); return __builtin_bswap16(value);
#else
return value;
#endif
} }
static inline uint16_t ntohs(uint16_t ns) inline uint16_t ntohs(uint16_t value)
{ {
return htons(ns); return htons(value);
} }
static inline uint32_t htonl(uint32_t hs) inline uint32_t htonl(uint32_t value)
{ {
uint8_t* s = (uint8_t*)&hs; return __builtin_bswap32(value);
return (uint32_t)(s[0] << 24 | s[1] << 16 | s[2] << 8 | s[3]);
} }
static inline uint32_t ntohl(uint32_t ns) inline uint32_t ntohl(uint32_t value)
{ {
return htonl(ns); return htonl(value);
} }
__END_DECLS __END_DECLS