FileCommon.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #include <FpConfig.hpp>
  2. #include <Os/File.hpp>
  3. #include <Fw/Types/Assert.hpp>
  4. #ifdef __cplusplus
  5. extern "C" {
  6. #endif // __cplusplus
  7. #include <Utils/Hash/libcrc/lib_crc.h> // borrow CRC
  8. #ifdef __cplusplus
  9. }
  10. #endif // __cplusplus
  11. namespace Os {
  12. File::Status File::niceCRC32(U32 &crc, const char* fileName)
  13. {
  14. //Constants used in this function
  15. const U32 CHUNK_SIZE = 4096;
  16. const U32 INITIAL_SEED = 0xFFFFFFFF;
  17. const U32 MAX_IT = 0xFFFFFFFF; //Max int for U32
  18. //Loop variables for calculating CRC
  19. NATIVE_INT_TYPE offset = 0;
  20. U32 seed = INITIAL_SEED;
  21. Status status;
  22. File file;
  23. U8 file_buffer[CHUNK_SIZE];
  24. bool eof = false;
  25. //Loop across the whole file
  26. for (U32 i = 0; !eof && i < MAX_IT; i++) {
  27. //Open and check status
  28. status = file.open(fileName, OPEN_READ);
  29. if (status != OP_OK) {
  30. crc = 0;
  31. return status;
  32. }
  33. //Find our place
  34. status = file.seek(offset, true);
  35. if (status != OP_OK) {
  36. crc = 0;
  37. return status;
  38. }
  39. NATIVE_INT_TYPE chunk = CHUNK_SIZE;
  40. //Read data and check status
  41. status = file.read(file_buffer, chunk, false);
  42. offset += chunk;
  43. //Close file, then update CRC. This reduces time file is required open
  44. file.close();
  45. if (chunk != 0 && status == OP_OK) {
  46. for (U32 ci = 0; static_cast<NATIVE_INT_TYPE>(ci) < chunk; ci++) {
  47. seed = update_crc_32(seed, file_buffer[ci]);
  48. }
  49. } else if (chunk == 0 && status == OP_OK) {
  50. eof = true;
  51. break;
  52. } else {
  53. crc = 0;
  54. return status;
  55. }
  56. }
  57. //Reach max-loop
  58. if (!eof) {
  59. crc = 0;
  60. return OTHER_ERROR;
  61. }
  62. //Good CRC
  63. crc = seed;
  64. return OP_OK;
  65. }
  66. }