Skip to content

Commit

Permalink
Merge pull request #29 from ReadAlongs/test_byteorder
Browse files Browse the repository at this point in the history
Correct pointer aliasing in SWAP_FLOAT32
  • Loading branch information
dhdaines authored Nov 9, 2022
2 parents 757f2f8 + a790d38 commit 562024d
Show file tree
Hide file tree
Showing 3 changed files with 62 additions and 1 deletion.
5 changes: 4 additions & 1 deletion include/soundswallower/byteorder.h
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@
(0xff000000 & (*(x))<<24))

/* Macro to byteswap a float32 variable. x = ptr to variable */
#define SWAP_FLOAT32(x) SWAP_INT32((int32 *) x)
#define SWAP_FLOAT32(x) { uint8 tmp, *ux = (uint8 *)x; \
tmp = ux[3]; ux[3] = ux[0]; ux[0] = tmp; \
tmp = ux[2]; ux[2] = ux[1]; ux[1] = tmp; \
}

/* Macro to byteswap a float64 variable. x = ptr to variable */
#define SWAP_FLOAT64(x) { int32 *low = (int32 *) (x), *high = (int32 *) (x) + 1,\
Expand Down
1 change: 1 addition & 0 deletions tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ set(TESTS
test_acmod_grow
test_add_words
test_bitvec
test_byteorder
test_ckd_alloc
test_ckd_alloc_catch
test_dict2pid
Expand Down
57 changes: 57 additions & 0 deletions tests/test_byteorder.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
#include "config.h"

#include <stdio.h>
#include <time.h>

#include <soundswallower/byteorder.h>
#include <soundswallower/profile.h>

#include "test_macros.h"

int
main(int argc, char *argv[])
{
uint32 ui32 = 0xdeadbeef;
int32 i32 = 0x12345678;
uint16 ui16 = 0xfeed;
int16 i16 = 0x1234;
float32 f32a = 382.23328f;
float32 f32b = -0.1246f;
ptmr_t t;
int i;

(void)argc; (void)argv;
SWAP_INT32(&ui32);
TEST_EQUAL(0xefbeadde, ui32);
SWAP_INT32(&i32);
TEST_EQUAL(0x78563412, i32);

SWAP_INT16(&ui16);
TEST_EQUAL(0xedfe, ui16);
SWAP_INT16(&i16);
TEST_EQUAL(0x3412, i16);

SWAP_FLOAT32(&f32a);
TEST_ASSERT(fabs(f32a - -1.77607e+17f) < 1e16f);
SWAP_FLOAT32(&f32a);
TEST_EQUAL_FLOAT(f32a, 382.23328f);
SWAP_FLOAT32(&f32b);
TEST_ASSERT(fabs(f32b - 716796.0f) < 1.0f);
SWAP_FLOAT32(&f32b);
TEST_EQUAL_FLOAT(f32b, -0.1246f);

ptmr_start(&t);
for (i = 0; i < 10000000; ++i) {
SWAP_FLOAT32(&f32a);
}
ptmr_stop(&t);
printf("10M SWAP_FLOAT32 in %g\n", t.t_cpu);
ptmr_reset(&t);
ptmr_start(&t);
for (i = 0; i < 10000000; ++i) {
SWAP_INT32(&ui32);
}
ptmr_stop(&t);
printf("10M SWAP_INT32 in %g\n", t.t_cpu);
return 0;
}

0 comments on commit 562024d

Please sign in to comment.