lzio.c 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. /*
  2. ** $Id: lzio.c,v 1.3 1997/12/22 20:57: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. {
  32. int n=fread(z->buffer,1,ZBSIZE,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, char *name)
  39. {
  40. if (f==NULL) return NULL;
  41. z->n=0;
  42. z->p=z->buffer;
  43. z->filbuf=zffilbuf;
  44. z->u=f;
  45. z->name=name;
  46. return z;
  47. }
  48. /* --------------------------------------------------------------- read --- */
  49. int zread (ZIO *z, void *b, int n)
  50. {
  51. while (n) {
  52. int m;
  53. if (z->n == 0) {
  54. if (z->filbuf(z) == EOZ)
  55. return n; /* retorna quantos faltaram ler */
  56. zungetc(z); /* poe o resultado de filbuf no buffer */
  57. }
  58. m = (n <= z->n) ? n : z->n; /* minimo de n e 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. }