lzio.c 1.6 KB

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