lzio.c 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. /*
  2. ** $Id: lzio.c,v 1.13 2000/06/12 13:52:05 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. #define LUA_PRIVATE
  9. #include "lua.h"
  10. #include "lzio.h"
  11. /* ----------------------------------------------------- memory buffers --- */
  12. static int zmfilbuf (ZIO* z) {
  13. (void)z; /* to avoid warnings */
  14. return EOZ;
  15. }
  16. ZIO* zmopen (ZIO* z, const char* b, size_t size, const char *name) {
  17. if (b==NULL) return NULL;
  18. z->n = size;
  19. z->p = (const unsigned char *)b;
  20. z->filbuf = zmfilbuf;
  21. z->u = NULL;
  22. z->name = name;
  23. return z;
  24. }
  25. /* ------------------------------------------------------------ strings --- */
  26. ZIO* zsopen (ZIO* z, const char* s, const char *name) {
  27. if (s==NULL) return NULL;
  28. return zmopen(z, s, strlen(s), name);
  29. }
  30. /* -------------------------------------------------------------- FILEs --- */
  31. static int zffilbuf (ZIO* z) {
  32. size_t n;
  33. if (feof((FILE *)z->u)) return EOZ;
  34. n = fread(z->buffer, 1, ZBSIZE, (FILE *)z->u);
  35. if (n==0) return EOZ;
  36. z->n = n-1;
  37. z->p = z->buffer;
  38. return *(z->p++);
  39. }
  40. ZIO* zFopen (ZIO* z, FILE* f, const char *name) {
  41. if (f==NULL) return NULL;
  42. z->n = 0;
  43. z->p = z->buffer;
  44. z->filbuf = zffilbuf;
  45. z->u = f;
  46. z->name = name;
  47. return z;
  48. }
  49. /* --------------------------------------------------------------- read --- */
  50. size_t zread (ZIO *z, void *b, size_t n) {
  51. while (n) {
  52. size_t m;
  53. if (z->n == 0) {
  54. if (z->filbuf(z) == EOZ)
  55. return n; /* return number of missing bytes */
  56. else {
  57. ++z->n; /* filbuf removed first byte; put back it */
  58. --z->p;
  59. }
  60. }
  61. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  62. memcpy(b, z->p, m);
  63. z->n -= m;
  64. z->p += m;
  65. b = (char *)b + m;
  66. n -= m;
  67. }
  68. return 0;
  69. }