9
3

lzio.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. /*
  2. ** $Id: lzio.c $
  3. ** Buffered streams
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lzio_c
  7. #define LUA_CORE
  8. #include "lprefix.h"
  9. #include <string.h>
  10. #include "lua.h"
  11. #include "llimits.h"
  12. #include "lmem.h"
  13. #include "lstate.h"
  14. #include "lzio.h"
  15. int luaZ_fill (ZIO *z) {
  16. size_t size;
  17. lua_State *L = z->L;
  18. const char *buff;
  19. lua_unlock(L);
  20. buff = z->reader(L, z->data, &size);
  21. lua_lock(L);
  22. if (buff == NULL || size == 0)
  23. return EOZ;
  24. z->n = size - 1; /* discount char being returned */
  25. z->p = buff;
  26. return cast_uchar(*(z->p++));
  27. }
  28. void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
  29. z->L = L;
  30. z->reader = reader;
  31. z->data = data;
  32. z->n = 0;
  33. z->p = NULL;
  34. }
  35. /* --------------------------------------------------------------- read --- */
  36. size_t luaZ_read (ZIO *z, void *b, size_t n) {
  37. while (n) {
  38. size_t m;
  39. if (z->n == 0) { /* no bytes in buffer? */
  40. if (luaZ_fill(z) == EOZ) /* try to read more */
  41. return n; /* no more input; return number of missing bytes */
  42. else {
  43. z->n++; /* luaZ_fill consumed first byte; put it back */
  44. z->p--;
  45. }
  46. }
  47. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  48. memcpy(b, z->p, m);
  49. z->n -= m;
  50. z->p += m;
  51. b = (char *)b + m;
  52. n -= m;
  53. }
  54. return 0;
  55. }