Simple refactor due to yaz_match_xsd_element 0 check YAZ-822
[yaz-moved-to-github.git] / src / ber_bit.c
1 /* This file is part of the YAZ toolkit.
2  * Copyright (C) Index Data
3  * See the file LICENSE for details.
4  */
5
6 /**
7  * \file ber_bit.c
8  * \brief Implements BER BITSTRING encoding and decoding.
9  *
10  * This source file implements BER encoding and decoding of
11  * the BITSTRING type.
12  */
13
14 #if HAVE_CONFIG_H
15 #include <config.h>
16 #endif
17
18 #include "odr-priv.h"
19
20 int ber_bitstring(ODR o, Odr_bitmask *p, int cons)
21 {
22     int res, len;
23     const char *base;
24
25     switch (o->direction)
26     {
27     case ODR_DECODE:
28         if ((res = ber_declen(o->op->bp, &len, odr_max(o))) < 0)
29         {
30             odr_seterror(o, OPROTO, 4);
31             return 0;
32         }
33         o->op->bp += res;
34         if (cons)       /* fetch component strings */
35         {
36             base = o->op->bp;
37             while (odp_more_chunks(o, base, len))
38                 if (!odr_bitstring(o, &p, 0, 0))
39                     return 0;
40             return 1;
41         }
42         /* primitive bitstring */
43         if (len < 0)
44         {
45             odr_seterror(o, OOTHER, 5);
46             return 0;
47         }
48         if (len == 0)
49             return 1;
50         if (len - 1 > ODR_BITMASK_SIZE)
51         {
52             odr_seterror(o, OOTHER, 6);
53             return 0;
54         }
55         if (len > odr_max(o))
56         {
57             odr_seterror(o, OOTHER, 7);
58             return 0;
59         }
60         o->op->bp++;      /* silently ignore the unused-bits field */
61         len--;
62         memcpy(p->bits + p->top + 1, o->op->bp, len);
63         p->top += len;
64         o->op->bp += len;
65         return 1;
66     case ODR_ENCODE:
67         if ((res = ber_enclen(o, p->top + 2, 5, 0)) < 0)
68             return 0;
69         if (odr_putc(o, 0) < 0)    /* no unused bits here */
70             return 0;
71         if (p->top < 0)
72             return 1;
73         if (odr_write(o, p->bits, p->top + 1) < 0)
74             return 0;
75         return 1;
76     case ODR_PRINT:
77         return 1;
78     default:
79         odr_seterror(o, OOTHER, 8);
80         return 0;
81     }
82 }
83 /*
84  * Local variables:
85  * c-basic-offset: 4
86  * c-file-style: "Stroustrup"
87  * indent-tabs-mode: nil
88  * End:
89  * vim: shiftwidth=4 tabstop=8 expandtab
90  */
91