bbb202ed796532a7fe398d29be48f399f1c3c984
[yaz-moved-to-github.git] / odr / ber_bit.c
1 /*
2  * Copyright (c) 1995, Index Data
3  * See the file LICENSE for details.
4  * Sebastian Hammer, Adam Dickmeiss
5  *
6  * $Log: ber_bit.c,v $
7  * Revision 1.6  1995-09-27 15:02:54  quinn
8  * Modified function heads & prototypes.
9  *
10  * Revision 1.5  1995/05/16  08:50:43  quinn
11  * License, documentation, and memory fixes
12  *
13  * Revision 1.4  1995/04/18  08:15:13  quinn
14  * Added dynamic memory allocation on encoding (whew). Code is now somewhat
15  * neater. We'll make the same change for decoding one day.
16  *
17  * Revision 1.3  1995/03/08  12:12:04  quinn
18  * Added better error checking.
19  *
20  * Revision 1.2  1995/02/03  17:04:31  quinn
21  * *** empty log message ***
22  *
23  * Revision 1.1  1995/02/02  20:38:49  quinn
24  * Updates.
25  *
26  *
27  */
28
29 #include <odr.h>
30
31 int MDF ber_bitstring(ODR o, Odr_bitmask *p, int cons)
32 {
33     int res, len;
34     unsigned char *base;
35
36     switch (o->direction)
37     {
38         case ODR_DECODE:
39             if ((res = ber_declen(o->bp, &len)) < 0)
40             {
41                 o->error = OPROTO;
42                 return 0;
43             }
44             o->bp += res;
45             o->left -= res;
46             if (cons)       /* fetch component strings */
47             {
48                 base = o->bp;
49                 while (odp_more_chunks(o, base, len))
50                     if (!odr_bitstring(o, &p, 0))
51                         return 0;
52                 return 1;
53             }
54             /* primitive bitstring */
55             if (len < 0)
56             {
57                 o->error = OOTHER;
58                 return 0;
59             }
60             if (len == 0)
61                 return 1;
62             if (len - 1 > ODR_BITMASK_SIZE)
63             {
64                 o->error = OOTHER;
65                 return 0;
66             }
67             o->bp++;      /* silently ignore the unused-bits field */
68             o->left--;
69             len--;
70             memcpy(p->bits + p->top + 1, o->bp, len);
71             p->top += len;
72             o->bp += len;
73             o->left -= len;
74             return 1;
75         case ODR_ENCODE:
76             if ((res = ber_enclen(o, p->top + 2, 5, 0)) < 0)
77                 return 0;
78             if (odr_putc(o, 0) < 0)    /* no unused bits here */
79                 return 0;
80             if (p->top < 0)
81                 return 1;
82             if (odr_write(o, p->bits, p->top + 1) < 0)
83                 return 0;
84             return 1;
85         case ODR_PRINT: return 1;
86         default: o->error = OOTHER; return 0;
87     }
88 }