From: =?utf-8?b?0L3QsNCx?= <nabijaczleweli@nabijaczleweli.xyz>
Date: Sat, 25 Jan 2025 15:45:49 +0100
Subject: Detect endianness more portably

Bug-Debian: http://bugs.debian.org/154520
Last-Update: 2025-01-25
---
 io.c | 56 +++++++-------------------------------------------------
 1 file changed, 7 insertions(+), 49 deletions(-)

diff --git a/io.c b/io.c
index 0d6214b..0d4f3fe 100644
--- a/io.c
+++ b/io.c
@@ -40,65 +40,23 @@
 #include <assert.h>
 #include <errno.h>
 #include <stdio.h>
+#include <stdint.h>
 #include <stdlib.h>
 #include <string.h>
 #include <unistd.h>
+#include <endian.h>
 
 #include "io.h"
 #include "ttyrec.h"
 #include "compress.h"
 
-#define SWAP_ENDIAN(val)                                             \
-    ((unsigned int)(                                                 \
-         (((unsigned int)(val) & (unsigned int)0x000000ffU) << 24) | \
-         (((unsigned int)(val) & (unsigned int)0x0000ff00U) << 8) |  \
-         (((unsigned int)(val) & (unsigned int)0x00ff0000U) >> 8) |  \
-         (((unsigned int)(val) & (unsigned int)0xff000000U) >> 24)))
-
-static int is_little_endian(void)
-{
-    static int retval = -1;
-
-    if (retval == -1)
-    {
-        int  n   = 1;
-        char *p  = (char *)&n;
-        char x[] = { 1, 0, 0, 0 };
-
-        assert(sizeof(int) == 4);
-
-        if (memcmp(p, x, 4) == 0)
-        {
-            retval = 1;
-        }
-        else
-        {
-            retval = 0;
-        }
-    }
-
-    return retval;
-}
-
-
-static int convert_to_little_endian(int x)
-{
-    if (is_little_endian())
-    {
-        return x;
-    }
-    else
-    {
-        return SWAP_ENDIAN(x);
-    }
-}
-
+#define convert_to_little_endian htole32
 
 int read_header(FILE *fp, Header *h)
 {
-    int buf[3];
+    uint32_t buf[3];
 
-    if (fread_wrapper(buf, sizeof(int), 3, fp) == 0)
+    if (fread_wrapper(buf, sizeof(uint32_t), 3, fp) == 0)
     {
         return 0;
     }
@@ -113,13 +71,13 @@ int read_header(FILE *fp, Header *h)
 
 int write_header(FILE *fp, Header *h)
 {
-    int buf[3];
+    uint32_t buf[3];
 
     buf[0] = convert_to_little_endian(h->tv.tv_sec);
     buf[1] = convert_to_little_endian(h->tv.tv_usec);
     buf[2] = convert_to_little_endian(h->len);
 
-    if (fwrite_wrapper(buf, sizeof(int), 3, fp) == 0)
+    if (fwrite_wrapper(buf, sizeof(uint32_t), 3, fp) == 0)
     {
         return 0;
     }
