1
0

fwrite_le.*: optimize, extract a function

This commit is contained in:
Intel A80486DX2-66 2024-01-02 00:19:51 +03:00
parent e293d66441
commit 08a7c255db
Signed by: 80486DX2-66
GPG Key ID: 83631EF27054609B
2 changed files with 40 additions and 15 deletions

View File

@ -17,6 +17,29 @@ int detect_endianness(void) {
return UNSUPPORTED_ENDIANNESS; return UNSUPPORTED_ENDIANNESS;
} }
void reorder_le_for_be(
#if FWRITE_LE_NO_MODIFICATION
uint8_t* dest, uint8_t* src,
#else
uint8_t* bytes,
#endif
size_t count, size_t step) {
for (size_t i = 0; i < count; i += step) {
const size_t div_size = step >> 1; // divide by 2
for (size_t j = 0; j < div_size; j++) {
const size_t old_pos = i + j, new_pos = i + step - j - 1;
#if FWRITE_LE_NO_MODIFICATION
dest[old_pos] = src[new_pos];
dest[new_pos] = src[old_pos];
#else
uint8_t temp = bytes[old_pos];
bytes[old_pos] = bytes[new_pos];
bytes[new_pos] = temp;
#endif
}
}
}
size_t fwrite_le(void* ptr, size_t size, size_t count, FILE* stream) { size_t fwrite_le(void* ptr, size_t size, size_t count, FILE* stream) {
/* /*
* warning: this function modifies `void* ptr` by default! * warning: this function modifies `void* ptr` by default!
@ -41,31 +64,26 @@ size_t fwrite_le(void* ptr, size_t size, size_t count, FILE* stream) {
exit(EXIT_FAILURE); exit(EXIT_FAILURE);
} }
memcpy(bytes, ptr, bytes_count); memcpy(bytes, ptr, bytes_count);
#else
uint8_t* bytes = (uint8_t*) ptr;
#endif #endif
for (size_t i = 0; i < bytes_count; i += size) { reorder_le_for_be(
const size_t div_size = size >> 1; // divide by 2
for (size_t j = 0; j < div_size; j++) {
const size_t old_pos = i + j, new_pos = i + size - j - 1;
#if FWRITE_LE_NO_MODIFICATION #if FWRITE_LE_NO_MODIFICATION
bytes[old_pos] = ptr[new_pos]; bytes,
bytes[new_pos] = ptr[old_pos];
#else
uint8_t temp = bytes[old_pos];
bytes[old_pos] = bytes[new_pos];
bytes[new_pos] = temp;
#endif #endif
} (uint8_t*) ptr, bytes_count, size);
}
#if FWRITE_LE_NO_MODIFICATION #if FWRITE_LE_NO_MODIFICATION
size_t res = size_t res =
#else #else
return return
#endif #endif
fwrite(bytes, size, count, stream); fwrite(
#if FWRITE_LE_NO_MODIFICATION
bytes,
#else
(uint8_t*) ptr,
#endif
size, count, stream);
#if FWRITE_LE_NO_MODIFICATION #if FWRITE_LE_NO_MODIFICATION
free(bytes); free(bytes);
return res; return res;

View File

@ -14,5 +14,12 @@
int detect_endianness(void); int detect_endianness(void);
size_t fwrite_le(void* ptr, size_t size, size_t count, FILE* stream); size_t fwrite_le(void* ptr, size_t size, size_t count, FILE* stream);
void reorder_le_for_be(
#if FWRITE_LE_NO_MODIFICATION
uint8_t* dest, uint8_t* src,
#else
uint8_t* bytes,
#endif
size_t count, size_t step);
#endif /* _FWRITE_LE_H */ #endif /* _FWRITE_LE_H */