lzio.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. ** $Id: lzio.c,v 1.12 2000/05/24 13:54:49 roberto Exp roberto $
  3. ** a generic input stream interface
  4. ** See Copyright Notice in lua.h
  5. */
  6. #include <stdio.h>
  7. #include <string.h>
  8. #include "lua.h"
  9. #include "lzio.h"
  10. /* ----------------------------------------------------- memory buffers --- */
  11. static int zmfilbuf (ZIO* z) {
  12. (void)z; /* to avoid warnings */
  13. return EOZ;
  14. }
  15. ZIO* zmopen (ZIO* z, const char* b, size_t size, const char *name) {
  16. if (b==NULL) return NULL;
  17. z->n = size;
  18. z->p = (const unsigned char *)b;
  19. z->filbuf = zmfilbuf;
  20. z->u = NULL;
  21. z->name = name;
  22. return z;
  23. }
  24. /* ------------------------------------------------------------ strings --- */
  25. ZIO* zsopen (ZIO* z, const char* s, const char *name) {
  26. if (s==NULL) return NULL;
  27. return zmopen(z, s, strlen(s), name);
  28. }
  29. /* -------------------------------------------------------------- FILEs --- */
  30. static int zffilbuf (ZIO* z) {
  31. size_t n;
  32. if (feof((FILE *)z->u)) return EOZ;
  33. n = fread(z->buffer, 1, ZBSIZE, (FILE *)z->u);
  34. if (n==0) return EOZ;
  35. z->n = n-1;
  36. z->p = z->buffer;
  37. return *(z->p++);
  38. }
  39. ZIO* zFopen (ZIO* z, FILE* f, const char *name) {
  40. if (f==NULL) return NULL;
  41. z->n = 0;
  42. z->p = z->buffer;
  43. z->filbuf = zffilbuf;
  44. z->u = f;
  45. z->name = name;
  46. return z;
  47. }
  48. /* --------------------------------------------------------------- read --- */
  49. size_t zread (ZIO *z, void *b, size_t n) {
  50. while (n) {
  51. size_t m;
  52. if (z->n == 0) {
  53. if (z->filbuf(z) == EOZ)
  54. return n; /* return number of missing bytes */
  55. zungetc(z); /* put result from `filbuf' in the buffer */
  56. }
  57. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  58. memcpy(b, z->p, m);
  59. z->n -= m;
  60. z->p += m;
  61. b = (char *)b + m;
  62. n -= m;
  63. }
  64. return 0;
  65. }