lzio.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. ** $Id: lzio.c,v 1.2 1997/11/21 19:00:46 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. {
  12. return EOZ;
  13. }
  14. ZIO* zmopen (ZIO* z, char* b, int size, char *name)
  15. {
  16. if (b==NULL) return NULL;
  17. z->n=size;
  18. z->p= (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, char* s, char *name)
  26. {
  27. if (s==NULL) return NULL;
  28. return zmopen(z,s,strlen(s),name);
  29. }
  30. /* -------------------------------------------------------------- FILEs --- */
  31. static int zffilbuf (ZIO* z)
  32. {
  33. int 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. {
  52. while (n) {
  53. int m;
  54. if (z->n == 0) {
  55. if (z->filbuf(z) == EOZ)
  56. return n; /* retorna quantos faltaram ler */
  57. zungetc(z); /* poe o resultado de filbuf no buffer */
  58. }
  59. m = (n <= z->n) ? n : z->n; /* minimo de n e z->n */
  60. memcpy(b, z->p, m);
  61. z->n -= m;
  62. z->p += m;
  63. b = (char *)b + m;
  64. n -= m;
  65. }
  66. return 0;
  67. }