lzio.c 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  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 "lapi.h"
  12. #include "llimits.h"
  13. #include "lmem.h"
  14. #include "lstate.h"
  15. #include "lzio.h"
  16. int luaZ_fill (ZIO *z) {
  17. size_t size;
  18. lua_State *L = z->L;
  19. const char *buff;
  20. lua_unlock(L);
  21. buff = z->reader(L, z->data, &size);
  22. lua_lock(L);
  23. if (buff == NULL || size == 0)
  24. return EOZ;
  25. z->n = size - 1; /* discount char being returned */
  26. z->p = buff;
  27. return cast_uchar(*(z->p++));
  28. }
  29. void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
  30. z->L = L;
  31. z->reader = reader;
  32. z->data = data;
  33. z->n = 0;
  34. z->p = NULL;
  35. }
  36. /* --------------------------------------------------------------- read --- */
  37. static int checkbuffer (ZIO *z) {
  38. if (z->n == 0) { /* no bytes in buffer? */
  39. if (luaZ_fill(z) == EOZ) /* try to read more */
  40. return 0; /* no more input */
  41. else {
  42. z->n++; /* luaZ_fill consumed first byte; put it back */
  43. z->p--;
  44. }
  45. }
  46. return 1; /* now buffer has something */
  47. }
  48. size_t luaZ_read (ZIO *z, void *b, size_t n) {
  49. while (n) {
  50. size_t m;
  51. if (!checkbuffer(z))
  52. return n; /* no more input; return number of missing bytes */
  53. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  54. memcpy(b, z->p, m);
  55. z->n -= m;
  56. z->p += m;
  57. b = (char *)b + m;
  58. n -= m;
  59. }
  60. return 0;
  61. }
  62. const void *luaZ_getaddr (ZIO* z, size_t n) {
  63. const void *res;
  64. if (!checkbuffer(z))
  65. return NULL; /* no more input */
  66. if (z->n < n) /* not enough bytes? */
  67. return NULL; /* block not whole; cannot give an address */
  68. res = z->p; /* get block address */
  69. z->n -= n; /* consume these bytes */
  70. z->p += n;
  71. return res;
  72. }