lzio.c 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. ** $Id: lzio.c,v 1.4 1998/12/28 13:44:54 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. while (n) {
  51. int m;
  52. if (z->n == 0) {
  53. if (z->filbuf(z) == EOZ)
  54. return n; /* return number of missing bytes */
  55. zungetc(z); /* put result from 'filbuf' in the buffer */
  56. }
  57. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  58. memcpy(b, z->p, m);
  59. z->n -= m;
  60. z->p += m;
  61. b = (char *)b + m;
  62. n -= m;
  63. }
  64. return 0;
  65. }