Remove the complicated fopen/realloc logic.
Unified · Split
| @@ -351,30 +351,14 @@ static void af_push_file(js_State *J, const char *fname, int limit, void *af) · 350 unmodified lines | |||
| 351 | return; | 351 | return; |
| 352 | } | 352 | } |
| 353 | 353 | ||
| 354 | FILE *f = fopen(filename, "rb"); | 354 | bstr data = stream_read_file(filename, NULL, jctx(J)->mpctx->global, limit); |
| 355 | if (!f) | 355 | if (data.start) { |
| 356 | js_pushlstring(J, data.start, data.len); | ||
| 357 | } else { | ||
| 356 | js_error(J, "cannot open file: '%s'", filename); | 358 | js_error(J, "cannot open file: '%s'", filename); |
| 357 | add_af_file(af, f); | ||
| 358 | |||
| 359 | int len = MPMIN(limit, 32 * 1024); // initial allocation, size*2 strategy | ||
| 360 | int got = 0; | ||
| 361 | char *s = NULL; | ||
| 362 | while ((s = talloc_realloc(af, s, char, len))) { | ||
| 363 | int want = len - got; | ||
| 364 | int r = fread(s + got, 1, want, f); | ||
| 365 | |||
| 366 | if (feof(f) || (len == limit && r == want)) { | ||
| 367 | js_pushlstring(J, s, got + r); | ||
| 368 | return; | ||
| 369 | } | ||
| 370 | if (r != want) | ||
| 371 | js_error(J, "cannot read data from file: '%s'", filename); | ||
| 372 | |||
| 373 | got = got + r; | ||
| 374 | len = MPMIN(limit, len * 2); | ||
| 375 | } | 359 | } |
| 376 | 360 | ||
| 377 | js_error(J, "cannot allocate %d bytes for file: '%s'", len, filename); | 361 | talloc_free(data.start); |
| 378 | } | 362 | } |
| 379 | 363 | ||
| 380 | // Safely run af_push_file. | 364 | // Safely run af_push_file. |