add achitecture-dependent assembly to build, implement hardware byte-swapping

This commit is contained in:
mykola2312 2022-05-11 18:48:46 +03:00
parent 579f9281e0
commit 0b610097b4
4 changed files with 35 additions and 22 deletions

View file

@ -1,5 +1,5 @@
cmake_minimum_required(VERSION 3.10)
project(cutil)
project(cutil C ASM)
set(HEADERS
cutypes.h
@ -20,7 +20,9 @@ set(SOURCES
struct.c
)
add_library(cutil STATIC ${SOURCES} ${HEADERS})
add_library(cutil STATIC ${SOURCES} ${HEADERS}
"arch/${CMAKE_SYSTEM_PROCESSOR}.S"
)
add_executable(test test.c)
target_link_libraries(test cutil)

21
arch/x86_64.S Normal file
View file

@ -0,0 +1,21 @@
.globl hw_bswap16
.globl hw_bswap32
.globl hw_bswap64
.text
hw_bswap16:
mov %edi, %eax
xchg %al, %ah
ret
hw_bswap32:
mov %edi, %eax
bswap %eax
ret
hw_bswap64:
mov %rdi, %rax
bswap %rax
ret

View file

@ -46,29 +46,18 @@ static uint64_t sw_bswap64(uint64_t val)
}
#if (CU_ARCH == x86_32)
static uint32_t hw_bswap32(uint32_t val)
{
__asm__ ("bswap %0" : "=r" (val) : "r" (val));
return val;
}
extern uint16_t hw_bswap16(uint16_t val);
extern uint32_t hw_bswap32(uint32_t val);
bswap16_t cu_bswap16 = sw_bswap16;
bswap16_t cu_bswap16 = hw_bswap16;
bswap32_t cu_bswap32 = hw_bswap32;
bswap64_t cu_bswap64 = sw_bswap64;
#elif (CU_ARCH == x86_64)
static uint32_t hw_bswap32(uint32_t val)
{
__asm__ ("bswap %0" : "=r" (val) : "r" (val));
return val;
}
extern uint16_t hw_bswap16(uint16_t val);
extern uint32_t hw_bswap32(uint32_t val);
extern uint64_t hw_bswap64(uint64_t val);
static uint64_t hw_bswap64(uint64_t val)
{
__asm__ ("bswap %0" : "=r" (val) : "r" (val));
return val;
}
bswap16_t cu_bswap16 = sw_bswap16;
bswap16_t cu_bswap16 = hw_bswap16;
bswap32_t cu_bswap32 = hw_bswap32;
bswap64_t cu_bswap64 = hw_bswap64;
#else

5
test.c
View file

@ -111,8 +111,9 @@ int main()
printf("[endian]\n");
printf("cutil_endian\t%u\n", cu_endian);
printf("%x\t%x\n", 0x12345678, l32toh32(0x12345678));
printf("%lx\t%lx\n", 0x12345678abcd8765, h64ton64(0x12345678abcd8765));
printf("%x\t%x\n", 0x1234, cu_bswap16(0x1234));
printf("%x\t%x\n", 0x12345678, cu_bswap32(0x12345678));
printf("%lx\t%lx\n", 0x12345678abcd8765, cu_bswap64(0x12345678abcd8765));
printf("[struct]\n");
printf("value_offset\t%u\n", value_offset(CU_STRUCT(test_s), 4, &test));