-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbsread.c
139 lines (127 loc) · 2.39 KB
/
bsread.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
/*
* This file is part of "jelio".
* jelio is an input/output library that replaces the standard C IO library.
*
* Copyright: Jens Låås, SLU 2004
* Copyright license: According to GPL, see file COPYING in this directory.
*
*/
#include "jelio.h"
#include "jelio_internal.h"
#include <stdarg.h>
#include <stdlib.h>
#include <ctype.h>
static unsigned int readbits(struct jelbs *s, int n, int *eof)
{
unsigned int o=0, t;
while(n)
{
if(bseof(s))
{
*eof=1;
return o;
}
if(n > (s->bitpos))
{
/* read all there is */
o <<= (s->bitpos+1);
t = *(s->mem + s->bytepos);
t &= (1 << (s->bitpos+1))-1;
o |= t;
n -= (s->bitpos+1);
s->bitpos = 7;
s->bytepos++;
}
else
{
/* read part of what there is */
o <<= n;
t = *(s->mem + s->bytepos);
t >>= (s->bitpos+1) - n;
t &= (1 << n)-1;
o |= t;
s->bitpos -= n;
if(s->bitpos < 0)
{
s->bitpos = 7;
s->bytepos++;
}
break;
}
}
return o;
}
static int readbytes(struct jelbs *s, unsigned char *oct, int n)
{
int eof=0;
while(n--)
{
if(bseof(s))
return -1;
*oct++ = readbits(s, 8, &eof);
if(eof) return -1;
}
return 0;
}
int bsread(struct jelbs *s, const char *fmt, ...)
{
int count=0, downshift;
int opt, len, consumed;
unsigned int *v;
unsigned char *str;
unsigned char *oct;
va_list ap;
int eof=0;
if(s->eof)
return -1;
va_start(ap, fmt);
while(*fmt)
{
downshift=0;
opt = *fmt++;
switch(opt)
{
case 's':
str = va_arg(ap, unsigned char*);
if(sscanv(fmt, &consumed, "%%", i_d(&len))==1)
{
fmt+=consumed;
/* read 'len' characters from stream into 'str' */
if(readbytes(s, str, len))
return -1;
*(str+len) = 0;
count++;
}
break;
case 'o':
oct = va_arg(ap, unsigned char*);
if(sscanv(fmt, &consumed, "%%", i_d(&len))==1)
{
fmt+=consumed;
/* read 'len' octets from stream into 'oct' */
if(readbytes(s, oct, len))
return -1;
count++;
}
break;
case 'B':
downshift=1;
case 'b':
v = va_arg(ap, unsigned int*);
if(sscanv(fmt, &consumed, "%%", i_d(&len))==1)
{
fmt+=consumed;
*v = readbits(s, len, &eof);
if(eof) return -1;
if(!downshift)
(*v) <<= 32-len;
count++;
}
break;
default:
break;
}
}
va_end(ap);
return count;
}