lzio.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. static int checkbuffer (ZIO *z) {
  37. if (z->n == 0) { /* no bytes in buffer? */
  38. if (luaZ_fill(z) == EOZ) /* try to read more */
  39. return 0; /* no more input */
  40. else {
  41. z->n++; /* luaZ_fill consumed first byte; put it back */
  42. z->p--;
  43. }
  44. }
  45. return 1; /* now buffer has something */
  46. }
  47. size_t luaZ_read (ZIO *z, void *b, size_t n) {
  48. while (n) {
  49. size_t m;
  50. if (!checkbuffer(z))
  51. return n; /* no more input; return number of missing bytes */
  52. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  53. memcpy(b, z->p, m);
  54. z->n -= m;
  55. z->p += m;
  56. b = (char *)b + m;
  57. n -= m;
  58. }
  59. return 0;
  60. }
  61. const void *luaZ_getaddr (ZIO* z, size_t n) {
  62. const void *res;
  63. if (!checkbuffer(z))
  64. return NULL; /* no more input */
  65. if (z->n < n) /* not enough bytes? */
  66. return NULL; /* block not whole; cannot give an address */
  67. res = z->p; /* get block address */
  68. z->n -= n; /* consume these bytes */
  69. z->p += n;
  70. return res;
  71. }