FileReader.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /* vim: set expandtab ts=4 sw=4: */
  2. /*
  3. * You may redistribute this program and/or modify it under the terms of
  4. * the GNU General Public License as published by the Free Software Foundation,
  5. * either version 3 of the License, or (at your option) any later version.
  6. *
  7. * This program is distributed in the hope that it will be useful,
  8. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. * GNU General Public License for more details.
  11. *
  12. * You should have received a copy of the GNU General Public License
  13. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  14. */
  15. #include "io/Reader.h"
  16. #include "io/FileReader.h"
  17. #include "memory/Allocator.h"
  18. #include "util/Identity.h"
  19. #include <stdio.h>
  20. #include <stdint.h>
  21. struct FileReader {
  22. struct Reader generic;
  23. FILE* toRead;
  24. int failed;
  25. Identity
  26. };
  27. /** @see Reader->read() */
  28. static int read(struct Reader* reader, void* readInto, unsigned long length)
  29. {
  30. struct FileReader* context = Identity_check((struct FileReader*) reader);
  31. int peek = 0;
  32. if (length == 0) {
  33. peek = 1;
  34. length++;
  35. }
  36. if (context->failed || fread((char*)readInto, 1, length, context->toRead) != length) {
  37. context->failed = 1;
  38. return -1;
  39. }
  40. if (peek) {
  41. ungetc(((char*)readInto)[0], context->toRead);
  42. length--;
  43. }
  44. context->generic.bytesRead += length;
  45. return 0;
  46. }
  47. /** @see Reader->skip() */
  48. static void skip(struct Reader* reader, unsigned long length)
  49. {
  50. struct FileReader* context = Identity_check((struct FileReader*) reader);
  51. #define BUFF_SZ 256
  52. uint8_t buff[BUFF_SZ];
  53. // fseek() and ftell() are unreliable.
  54. size_t amount;
  55. while ((amount = (length > BUFF_SZ) ? BUFF_SZ : length) && !context->failed) {
  56. context->failed = read(reader, buff, amount);
  57. length -= amount;
  58. }
  59. }
  60. /** @see FileReader.h */
  61. struct Reader* FileReader_new(FILE* toRead, struct Allocator* allocator)
  62. {
  63. struct FileReader* context = Allocator_clone(allocator, (&(struct FileReader) {
  64. .generic = {
  65. .read = read,
  66. .skip = skip
  67. },
  68. .toRead = toRead
  69. }));
  70. Identity_set(context);
  71. return &context->generic;
  72. }