2 Various routines for reading and writing bit- and bytewise, from and to memory.
4 Part of the swftools package.
6 Copyright (c) 2001 Matthias Kramm <kramm@quiss.org>
8 This file is distributed under the GPL, see file COPYING for details */
13 void reader_init(struct reader_t*r, uchar*newdata, int newlength)
16 r->datalength = newlength;
20 void reader_skip(struct reader_t*r, int length)
24 void reader_resetbits(struct reader_t*r)
29 void reader_input1(struct reader_t*r, void*target)
31 *(uchar*)target = *(uchar*)&r->data[r->datapos];
34 void reader_input2(struct reader_t*r, void*target)
36 *(u16*)target = GET16(&r->data[r->datapos]);
39 void reader_input4(struct reader_t*r, void*target)
41 *(u32*)target = GET32(&r->data[r->datapos]);
44 uchar*reader_getinputpos(struct reader_t*r)
46 return &r->data[r->datapos];
48 int reader_getinputlength(struct reader_t*r)
52 void reader_setinputpos(struct reader_t*r, uchar*pos)
54 r->datapos = pos-r->data;
56 u32 reader_readbit(struct reader_t*r)
61 reader_input1(r, &r->mybyte);
63 return (r->mybyte>>(7-r->bitpos++))&1;
65 void reader_readbits(struct reader_t*r, u32*val,int num)
72 *val|=reader_readbit(r);
76 void reader_readsbits(struct reader_t*r, s32*val,int num)
79 reader_readbits(r, &x, num);
87 u32 reader_getbits(struct reader_t*r, int num)
90 reader_readbits(r,&x,num);
94 s32 reader_getsbits(struct reader_t*r, int num)
97 reader_readsbits(r, &x,num);
101 u8 reader_readu8(struct reader_t*r)
104 reader_input1(r, &a);
108 u16 reader_readu16(struct reader_t*r)
111 reader_input1(r, &a);
112 reader_input1(r, &b);
113 return ((u16)b)*256+a;
116 u32 reader_readu32(struct reader_t*r)
119 reader_input1(r, &a);
120 reader_input1(r, &b);
121 reader_input1(r, &c);
122 reader_input1(r, &d);
123 return (((((u32)d)*256+(u32)c)*256+(u32)b)*256+(u32)a);
126 void writer_init(struct writer_t*w, u8*data, int maxlength)
129 w->maxlength = maxlength;
135 void writer_write(struct writer_t*w, void*data, int length)
137 memcpy(&w->data[w->pos], data, length);
141 void writer_writeu8(struct writer_t*w, u8 value)
144 writer_write(w, &value, 1);
147 void writer_writeu16(struct writer_t*w, u16 value)
149 u16 value2 = SWAP16(value);
151 writer_write(w, &value2, 2);
154 void writer_writeu32(struct writer_t*w, u32 value)
156 u16 value2 = SWAP32(value);
158 writer_write(w, &value2, 4);
161 void* writer_getpos(struct writer_t*w)
163 return &w->data[w->pos];
166 void writer_resetbits(struct writer_t*w)
169 writer_write(w, &w->mybyte, 1);
174 void writer_writebit(struct writer_t*w, int bit)
178 writer_write(w, &w->mybyte, 1);
183 w->mybyte |= 1 << (7 - w->bitpos);
187 void writer_writebits(struct writer_t*w, u32 data, int bits)
192 writer_writebit(w, (data >> (bits-t-1))&1);