lzio.c 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. ** $Id: lzio.c,v 1.31.1.1 2007/12/27 13:02:25 roberto Exp $
  3. ** a generic input stream interface
  4. ** See Copyright Notice in lua.h
  5. */
  6. #define lzio_c
  7. #define LUA_CORE
  8. #include "lua.h"
  9. #include <string.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) return EOZ;
  22. z->n = size - 1;
  23. z->p = buff;
  24. return char2int(*(z->p++));
  25. }
  26. int luaZ_lookahead (ZIO *z) {
  27. if (z->n == 0) {
  28. if (luaZ_fill(z) == EOZ)
  29. return EOZ;
  30. else {
  31. z->n++; /* luaZ_fill removed first byte; put back it */
  32. z->p--;
  33. }
  34. }
  35. return char2int(*z->p);
  36. }
  37. void luaZ_init (lua_State *L, ZIO *z, lua_Reader reader, void *data) {
  38. z->L = L;
  39. z->reader = reader;
  40. z->data = data;
  41. z->n = 0;
  42. z->p = NULL;
  43. }
  44. /* --------------------------------------------------------------- read --- */
  45. size_t luaZ_read (ZIO *z, void *b, size_t n) {
  46. while (n) {
  47. size_t m;
  48. if (luaZ_lookahead(z) == EOZ)
  49. return n; /* return number of missing bytes */
  50. m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
  51. if (b)
  52. memcpy(b, z->p, m);
  53. z->n -= m;
  54. z->p += m;
  55. if (b)
  56. b = (char *)b + m;
  57. n -= m;
  58. }
  59. return 0;
  60. }
  61. /* ------------------------------------------------------------------------ */
  62. char *luaZ_openspace (lua_State *L, Mbuffer *buff, size_t n) {
  63. if (n > buff->buffsize) {
  64. if (n < LUA_MINBUFFER) n = LUA_MINBUFFER;
  65. luaZ_resizebuffer(L, buff, n);
  66. }
  67. return buff->buffer;
  68. }