Imported from ../lua-3.1.tar.gz.
[lua.git] / src / lzio.c
blob0ab1adf41dae1c7ed67ceaae794a170bcea5377a
1 /*
2 ** $Id: lzio.c,v 1.3 1997/12/22 20:57:18 roberto Exp $
3 ** a generic input stream interface
4 ** See Copyright Notice in lua.h
5 */
9 #include <stdio.h>
10 #include <string.h>
12 #include "lzio.h"
16 /* ----------------------------------------------------- memory buffers --- */
18 static int zmfilbuf (ZIO* z)
20 return EOZ;
23 ZIO* zmopen (ZIO* z, char* b, int size, char *name)
25 if (b==NULL) return NULL;
26 z->n=size;
27 z->p= (unsigned char *)b;
28 z->filbuf=zmfilbuf;
29 z->u=NULL;
30 z->name=name;
31 return z;
34 /* ------------------------------------------------------------ strings --- */
36 ZIO* zsopen (ZIO* z, char* s, char *name)
38 if (s==NULL) return NULL;
39 return zmopen(z,s,strlen(s),name);
42 /* -------------------------------------------------------------- FILEs --- */
44 static int zffilbuf (ZIO* z)
46 int n=fread(z->buffer,1,ZBSIZE,z->u);
47 if (n==0) return EOZ;
48 z->n=n-1;
49 z->p=z->buffer;
50 return *(z->p++);
54 ZIO* zFopen (ZIO* z, FILE* f, char *name)
56 if (f==NULL) return NULL;
57 z->n=0;
58 z->p=z->buffer;
59 z->filbuf=zffilbuf;
60 z->u=f;
61 z->name=name;
62 return z;
66 /* --------------------------------------------------------------- read --- */
67 int zread (ZIO *z, void *b, int n)
69 while (n) {
70 int m;
71 if (z->n == 0) {
72 if (z->filbuf(z) == EOZ)
73 return n; /* retorna quantos faltaram ler */
74 zungetc(z); /* poe o resultado de filbuf no buffer */
76 m = (n <= z->n) ? n : z->n; /* minimo de n e z->n */
77 memcpy(b, z->p, m);
78 z->n -= m;
79 z->p += m;
80 b = (char *)b + m;
81 n -= m;
83 return 0;