diff --git a/src/fwrite_le.c b/src/fwrite_le.c index ee5ff12..1e6d502 100644 --- a/src/fwrite_le.c +++ b/src/fwrite_le.c @@ -17,6 +17,29 @@ int detect_endianness(void) { 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) { /* * 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); } memcpy(bytes, ptr, bytes_count); -#else - uint8_t* bytes = (uint8_t*) ptr; #endif - for (size_t i = 0; i < bytes_count; i += size) { - 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; + reorder_le_for_be( #if FWRITE_LE_NO_MODIFICATION - bytes[old_pos] = ptr[new_pos]; - bytes[new_pos] = ptr[old_pos]; -#else - uint8_t temp = bytes[old_pos]; - bytes[old_pos] = bytes[new_pos]; - bytes[new_pos] = temp; + bytes, #endif - } - } + (uint8_t*) ptr, bytes_count, size); #if FWRITE_LE_NO_MODIFICATION size_t res = #else return #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 free(bytes); return res; diff --git a/src/fwrite_le.h b/src/fwrite_le.h index aa61722..cc56b02 100644 --- a/src/fwrite_le.h +++ b/src/fwrite_le.h @@ -14,5 +14,12 @@ int detect_endianness(void); 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 */