lua/lzio.c

89 lines
1.8 KiB
C
Raw Normal View History

1997-06-17 00:50:22 +08:00
/*
2001-03-26 22:31:49 +08:00
** $Id: lzio.c,v 1.13 2000/06/12 13:52:05 roberto Exp roberto $
1997-09-17 03:25:59 +08:00
** a generic input stream interface
** See Copyright Notice in lua.h
1997-06-17 00:50:22 +08:00
*/
1997-09-17 03:25:59 +08:00
1997-06-17 00:50:22 +08:00
#include <stdio.h>
#include <string.h>
1997-09-17 03:25:59 +08:00
2001-03-26 22:31:49 +08:00
#define LUA_PRIVATE
#include "lua.h"
1997-09-17 03:25:59 +08:00
#include "lzio.h"
1997-06-17 00:50:22 +08:00
/* ----------------------------------------------------- memory buffers --- */
static int zmfilbuf (ZIO* z) {
1999-11-10 01:59:35 +08:00
(void)z; /* to avoid warnings */
1999-08-17 04:52:00 +08:00
return EOZ;
1997-06-17 00:50:22 +08:00
}
2000-05-24 21:54:49 +08:00
ZIO* zmopen (ZIO* z, const char* b, size_t size, const char *name) {
1999-08-17 04:52:00 +08:00
if (b==NULL) return NULL;
z->n = size;
2000-03-03 22:58:26 +08:00
z->p = (const unsigned char *)b;
1999-08-17 04:52:00 +08:00
z->filbuf = zmfilbuf;
z->u = NULL;
z->name = name;
return z;
1997-06-17 00:50:22 +08:00
}
/* ------------------------------------------------------------ strings --- */
1999-08-17 04:52:00 +08:00
ZIO* zsopen (ZIO* z, const char* s, const char *name) {
if (s==NULL) return NULL;
2000-02-09 00:39:42 +08:00
return zmopen(z, s, strlen(s), name);
1997-06-17 00:50:22 +08:00
}
/* -------------------------------------------------------------- FILEs --- */
static int zffilbuf (ZIO* z) {
2000-05-24 21:54:49 +08:00
size_t n;
1999-08-17 04:52:00 +08:00
if (feof((FILE *)z->u)) return EOZ;
2000-02-09 00:39:42 +08:00
n = fread(z->buffer, 1, ZBSIZE, (FILE *)z->u);
1999-08-17 04:52:00 +08:00
if (n==0) return EOZ;
z->n = n-1;
z->p = z->buffer;
return *(z->p++);
1997-06-17 00:50:22 +08:00
}
1999-08-17 04:52:00 +08:00
ZIO* zFopen (ZIO* z, FILE* f, const char *name) {
if (f==NULL) return NULL;
z->n = 0;
z->p = z->buffer;
z->filbuf = zffilbuf;
z->u = f;
z->name = name;
return z;
1997-06-17 00:50:22 +08:00
}
/* --------------------------------------------------------------- read --- */
2000-05-24 21:54:49 +08:00
size_t zread (ZIO *z, void *b, size_t n) {
1997-06-17 00:50:22 +08:00
while (n) {
2000-05-24 21:54:49 +08:00
size_t m;
1997-06-17 00:50:22 +08:00
if (z->n == 0) {
if (z->filbuf(z) == EOZ)
1999-02-26 05:07:26 +08:00
return n; /* return number of missing bytes */
2001-03-26 22:31:49 +08:00
else {
++z->n; /* filbuf removed first byte; put back it */
--z->p;
}
1997-06-17 00:50:22 +08:00
}
1999-02-26 05:07:26 +08:00
m = (n <= z->n) ? n : z->n; /* min. between n and z->n */
1997-06-17 00:50:22 +08:00
memcpy(b, z->p, m);
z->n -= m;
z->p += m;
b = (char *)b + m;
n -= m;
}
return 0;
}