2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: ber_len.c,v 1.5 2005-08-11 14:21:55 adam Exp $
10 * \brief Implements BER length octet encoding and decoding
12 * This source file implements BER encoding and decoding of
25 * Encode BER length octets. If exact, lenlen is the exact desired
26 * encoding size, else, lenlen is the max available space. Len < 0 =
27 * Indefinite encoding.
28 * Returns: >0 success, number of bytes encoded.
29 * Returns: =0 success, indefinite start-marker set. 1 byte encoded.
30 * Returns: -1 failure, out of bounds.
32 int ber_enclen(ODR o, int len, int lenlen, int exact)
34 unsigned char octs[sizeof(int)];
38 if (len < 0) /* Indefinite */
40 if (odr_putc(o, 0x80) < 0)
44 if (len <= 127 && (lenlen == 1 || !exact)) /* definite short form */
46 if (odr_putc(o, (unsigned char) len) < 0)
52 if (odr_putc(o, 0x80) < 0)
56 /* definite long form */
65 lenpos = odr_tell(o); /* remember length-of-length position */
66 if (odr_putc(o, 0) < 0) /* dummy */
69 while (n < --lenlen) /* pad length octets */
70 if (odr_putc(o, 0) < 0)
73 if (odr_putc(o, octs[n]) < 0)
75 /* set length of length */
77 odr_seek(o, ODR_S_SET, lenpos);
78 if (odr_putc(o, (end - lenpos - 1) | 0X80) < 0)
80 odr_seek(o, ODR_S_END, 0);
81 return odr_tell(o) - lenpos;
86 * Decode BER length octets. Returns
87 * > 0 : number of bytes read
88 * -1 : not enough room to read bytes within max bytes
92 * len = -1 indefinite length.
93 * len >= 0 definite length
95 int ber_declen(const unsigned char *buf, int *len, int max)
97 const unsigned char *b = buf;
102 if (*b == 0X80) /* Indefinite */
107 if (!(*b & 0X80)) /* Definite short form */
112 if (*b == 0XFF) /* reserved value */
114 /* indefinite long form */
132 * indent-tabs-mode: nil
134 * vim: shiftwidth=4 tabstop=8 expandtab