lzio.c 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. ** $Id: lzio.c,v 1.6 1999/03/04 14:49:18 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, char* b, int size, char *name)
  14. {
  15. if (b==NULL) return NULL;
  16. z->n=size;
  17. z->p= (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, char* s, char *name)
  25. {
  26. if (s==NULL) return NULL;
  27. return zmopen(z,s,strlen(s),name);
  28. }
  29. /* -------------------------------------------------------------- FILEs --- */
  30. static int zffilbuf (ZIO* z) {
  31. int n;
  32. if (feof((FILE *)z->u)) return EOZ;
  33. n=fread(z->buffer,1,ZBSIZE,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, char *name)
  40. {
  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. int zread (ZIO *z, void *b, int n) {
  51. while (n) {
  52. int m;
  53. if (z->n == 0) {
  54. if (z->filbuf(z) == EOZ)
  55. return n; /* return number of missing bytes */
  56. zungetc(z); /* put result from 'filbuf' in the buffer */
  57. }
  58. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  59. memcpy(b, z->p, m);
  60. z->n -= m;
  61. z->p += m;
  62. b = (char *)b + m;
  63. n -= m;
  64. }
  65. return 0;
  66. }