lzio.c 1.7 KB

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