2 * Copyright (C) 1995-2005, Index Data ApS
3 * See the file LICENSE for details.
5 * $Id: ber_len.c,v 1.4 2005-06-25 15:46:03 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)];
39 fprintf(stderr, "[len=%d]", len);
41 if (len < 0) /* Indefinite */
43 if (odr_putc(o, 0x80) < 0)
46 fprintf(stderr, "[indefinite]");
50 if (len <= 127 && (lenlen == 1 || !exact)) /* definite short form */
52 if (odr_putc(o, (unsigned char) len) < 0)
58 if (odr_putc(o, 0x80) < 0)
62 /* definite long form */
71 lenpos = odr_tell(o); /* remember length-of-length position */
72 if (odr_putc(o, 0) < 0) /* dummy */
75 while (n < --lenlen) /* pad length octets */
76 if (odr_putc(o, 0) < 0)
79 if (odr_putc(o, octs[n]) < 0)
81 /* set length of length */
83 odr_seek(o, ODR_S_SET, lenpos);
84 if (odr_putc(o, (end - lenpos - 1) | 0X80) < 0)
86 odr_seek(o, ODR_S_END, 0);
87 return odr_tell(o) - lenpos;
92 * Decode BER length octets. Returns
93 * > 0 : number of bytes read
94 * -1 : not enough room to read bytes within max bytes
98 * len = -1 indefinite length.
99 * len >= 0 definite length
101 int ber_declen(const unsigned char *buf, int *len, int max)
103 const unsigned char *b = buf;
108 if (*b == 0X80) /* Indefinite */
112 fprintf(stderr, "[len=%d]", *len);
116 if (!(*b & 0X80)) /* Definite short form */
120 fprintf(stderr, "[len=%d]", *len);
124 if (*b == 0XFF) /* reserved value */
126 /* indefinite long form */
140 fprintf(stderr, "[len=%d]", *len);
147 * indent-tabs-mode: nil
149 * vim: shiftwidth=4 tabstop=8 expandtab