src/network.h

changeset 183
39aa77b7188b
parent 182
04c65336777f
child 184
93c81539b702
--- a/src/network.h	Sat Aug 22 16:22:05 2026 +0200
+++ b/src/network.h	Sun Aug 23 11:38:27 2026 +0200
@@ -31,7 +31,7 @@
 #define	TCHESS_NETWORK_H
 
 #include <sys/socket.h>
-#include <netdb.h>
+#include <stdint.h>
 
 #ifdef	__cplusplus
 extern "C" {
@@ -99,6 +99,54 @@
 uint8_t net_recieve_code_async(int socket);
 void net_recieve_data(int socket, void *data, size_t len);
 
+
+/* Functions that convert WORD and DWORD values to terminal-chess
+ * network protocol byte order.
+ *
+ * Note: due to the vast majority of processors using little-endian,
+ * the network byte order of terminal-chess is little-endian, too.
+ * While the standard network byte order is big-endian for historic reasons.
+ */
+
+static inline uint16_t net_htons(uint16_t s) {
+#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+    return s;
+#else
+#if !defined(__BYTE_ORDER__)
+    const uint16_t endian_test = 1;
+    if (*(const uint8_t *)&endian_test) {
+        return s;
+    }
+#endif
+    return (uint16_t)((s >> 8) | (s << 8));
+#endif
+}
+
+static inline uint16_t net_ntohs(uint16_t s) {
+    return net_htons(s);
+}
+
+static inline uint32_t net_ntohl(uint32_t l) {
+#if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
+    return l;
+#else
+#if !defined(__BYTE_ORDER__)
+    const uint16_t endian_test = 1;
+    if (*(const uint8_t *)&endian_test) {
+        return l;
+    }
+#endif
+    return ((l & 0x000000FFu) << 24)
+         | ((l & 0x0000FF00u) << 8)
+         | ((l & 0x00FF0000u) >> 8)
+         | ((l & 0xFF000000u) >> 24);
+#endif
+}
+
+static inline uint32_t net_htonl(uint32_t l) {
+    return net_ntohl(l);
+}
+
 #ifdef	__cplusplus
 }
 #endif

mercurial