Commit 7bde150a3c7ac27761df52eaef32c7b4f656e10c

Authored by Josh Klontz
1 parent e32fd66b

refactored br_iterate_utemplates_file

Showing 1 changed file with 26 additions and 29 deletions
openbr/universal_template.cpp
... ... @@ -55,44 +55,41 @@ static void callAndFree(br_utemplate_callback callback, br_utemplate t, br_callb
55 55 free(t);
56 56 }
57 57  
  58 +static bool read_buffer(FILE *file, char *buffer, size_t bytes, bool eofAllowed)
  59 +{
  60 + size_t bytesRemaining = bytes;
  61 + while (bytesRemaining) {
  62 + const size_t bytesRead = fread(buffer, 1, bytesRemaining, file);
  63 + buffer += bytesRead;
  64 + bytesRemaining -= bytesRead;
  65 +
  66 + if (feof(file)) {
  67 + if (eofAllowed && (bytesRemaining == bytes))
  68 + return false;
  69 + qFatal("Unexpected end of file after reading %d of %d bytes.", int(bytes - bytesRemaining), int(bytes));
  70 + }
  71 +
  72 + if (ferror(file)) {
  73 + perror(NULL);
  74 + qFatal("Error while reading %d of %d bytes.", int(bytes - bytesRemaining), int(bytes));
  75 + }
  76 + }
  77 + return true;
  78 +}
  79 +
58 80 void br_iterate_utemplates_file(FILE *file, br_utemplate_callback callback, br_callback_context context, bool parallel)
59 81 {
60 82 QFutureSynchronizer<void> futures;
61 83 while (true) {
62 84 br_utemplate t = (br_utemplate) malloc(sizeof(br_universal_template));
63 85  
64   - int bytesRemaining = sizeof(br_universal_template);
65   - while (bytesRemaining > 0) {
66   - bytesRemaining -= fread(reinterpret_cast<char*>(t) + sizeof(br_universal_template) - bytesRemaining, 1, bytesRemaining, file);
67   -
68   - if (feof(file)) {
69   - if (bytesRemaining == sizeof(br_universal_template)) {
70   - free(t);
71   - return;
72   - } else {
73   - qFatal("Unexpected end of file when reading template metadata.");
74   - }
75   - }
76   -
77   - if (ferror(file)) {
78   - perror(NULL);
79   - qFatal("Error while reading template metadata.");
80   - }
  86 + if (!read_buffer(file, (char*) t, sizeof(br_universal_template), true)) {
  87 + free(t);
  88 + return;
81 89 }
82 90  
83 91 t = (br_utemplate) realloc(t, sizeof(br_universal_template) + t->size);
84   - bytesRemaining = t->size;
85   - while (bytesRemaining > 0) {
86   - bytesRemaining -= fread(&t->data[t->size - bytesRemaining], 1, bytesRemaining, file);
87   -
88   - if (feof(file))
89   - qFatal("Unexpected end of file when reading template data.");
90   -
91   - if (ferror(file)) {
92   - perror(NULL);
93   - qFatal("Error while reading template data.");
94   - }
95   - }
  92 + read_buffer(file, (char*) &t->data, t->size, false);
96 93  
97 94 if (parallel) futures.addFuture(QtConcurrent::run(callAndFree, callback, t, context));
98 95 else callAndFree(callback, t, context);
... ...