lzio.c 1.7 KB

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