1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) Index Data
3 * See the file LICENSE for details.
8 * \brief Implements BER length octet encoding and decoding
10 * This source file implements BER encoding and decoding of
23 * Encode BER length octets. If exact, lenlen is the exact desired
24 * encoding size, else, lenlen is the max available space. Len < 0 =
25 * Indefinite encoding.
26 * Returns: >0 success, number of bytes encoded.
27 * Returns: =0 success, indefinite start-marker set. 1 byte encoded.
28 * Returns: -1 failure, out of bounds.
30 int ber_enclen(ODR o, int len, int lenlen, int exact)
32 unsigned char octs[sizeof(int)];
36 if (len < 0) /* Indefinite */
38 if (odr_putc(o, 0x80) < 0)
42 if (len <= 127 && (lenlen == 1 || !exact)) /* definite short form */
44 if (odr_putc(o, (unsigned char) len) < 0)
50 if (odr_putc(o, 0x80) < 0)
54 /* definite long form */
63 lenpos = odr_tell(o); /* remember length-of-length position */
64 if (odr_putc(o, 0) < 0) /* dummy */
67 while (n < --lenlen) /* pad length octets */
68 if (odr_putc(o, 0) < 0)
71 if (odr_putc(o, octs[n]) < 0)
73 /* set length of length */
75 odr_seek(o, ODR_S_SET, lenpos);
76 if (odr_putc(o, (end - lenpos - 1) | 0X80) < 0)
78 odr_seek(o, ODR_S_END, 0);
79 return odr_tell(o) - lenpos;
84 * Decode BER length octets. Returns
85 * > 0 : number of bytes read
86 * -1 : not enough room to read bytes within max bytes
90 * len = -1 indefinite length.
91 * len >= 0 definite length
93 int ber_declen(const char *buf, int *len, int max)
95 const unsigned char *b = (const unsigned char *) buf;
100 if (*b == 0X80) /* Indefinite */
105 if (!(*b & 0X80)) /* Definite short form */
110 if (*b == 0XFF) /* reserved value */
112 /* indefinite long form */
125 return ((const char *) b - buf);
130 * c-file-style: "Stroustrup"
131 * indent-tabs-mode: nil
133 * vim: shiftwidth=4 tabstop=8 expandtab