2 * Copyright (C) 1995-2003, Index Data.
3 * See the file LICENSE for details.
4 * Sebastian Hammer, Adam Dickmeiss
6 * $Id: ber_len.c,v 1.12 2003-03-11 11:03:31 adam Exp $
16 * Encode BER length octets. If exact, lenlen is the exact desired
17 * encoding size, else, lenlen is the max available space. Len < 0 =
18 * Indefinite encoding.
19 * Returns: >0 success, number of bytes encoded.
20 * Returns: =0 success, indefinite start-marker set. 1 byte encoded.
21 * Returns: -1 failure, out of bounds.
23 int ber_enclen(ODR o, int len, int lenlen, int exact)
25 unsigned char octs[sizeof(int)];
30 fprintf(stderr, "[len=%d]", len);
32 if (len < 0) /* Indefinite */
34 if (odr_putc(o, 0x80) < 0)
37 fprintf(stderr, "[indefinite]");
41 if (len <= 127 && (lenlen == 1 || !exact)) /* definite short form */
43 if (odr_putc(o, (unsigned char) len) < 0)
49 if (odr_putc(o, 0x80) < 0)
53 /* definite long form */
62 lenpos = odr_tell(o); /* remember length-of-length position */
63 if (odr_putc(o, 0) < 0) /* dummy */
66 while (n < --lenlen) /* pad length octets */
67 if (odr_putc(o, 0) < 0)
70 if (odr_putc(o, octs[n]) < 0)
72 /* set length of length */
74 odr_seek(o, ODR_S_SET, lenpos);
75 if (odr_putc(o, (end - lenpos - 1) | 0X80) < 0)
77 odr_seek(o, ODR_S_END, 0);
78 return odr_tell(o) - lenpos;
82 * Decode BER length octets. Returns number of bytes read or -1 for error.
84 * len = -1 indefinite.
87 int ber_declen(const unsigned char *buf, int *len, int max)
89 const unsigned char *b = buf;
94 if (*b == 0X80) /* Indefinite */
98 fprintf(stderr, "[len=%d]", *len);
102 if (!(*b & 0X80)) /* Definite short form */
106 fprintf(stderr, "[len=%d]", *len);
110 if (*b == 0XFF) /* reserved value */
112 /* indefinite long form */
126 fprintf(stderr, "[len=%d]", *len);