1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2008 Index Data
3 * See the file LICENSE for details.
8 * \brief Implements BER INTEGER encoding and decoding.
10 * This source file implements BER encoding and decoding of
21 #include <sys/types.h>
27 #include <netinet/in.h>
32 static int ber_encinteger(ODR o, int val);
33 static int ber_decinteger(const unsigned char *buf, int *val, int max);
35 int ber_integer(ODR o, int *val)
42 if ((res = ber_decinteger(o->bp, val, odr_max(o))) <= 0)
44 odr_seterror(o, OPROTO, 50);
50 if ((res = ber_encinteger(o, *val)) < 0)
56 odr_seterror(o, OOTHER, 51); return 0;
61 * Returns: number of bytes written or -1 for error (out of bounds).
63 int ber_encinteger(ODR o, int val)
66 union { int i; unsigned char c[sizeof(int)]; } tmp;
68 tmp.i = htonl(val); /* ensure that that we're big-endian */
69 for (a = 0; a < (int) sizeof(int) - 1; a++) /* skip superfluous octets */
70 if (!((tmp.c[a] == 0 && !(tmp.c[a+1] & 0X80)) ||
71 (tmp.c[a] == 0XFF && (tmp.c[a+1] & 0X80))))
73 len = sizeof(int) - a;
74 if (ber_enclen(o, len, 1, 1) != 1)
76 if (odr_write(o, (unsigned char*) tmp.c + a, len) < 0)
82 * Returns: Number of bytes read or 0 if no match, -1 if error.
84 int ber_decinteger(const unsigned char *buf, int *val, int max)
86 const unsigned char *b = buf;
88 int res, len, remains;
89 union { int i; unsigned char c[sizeof(int)]; } tmp;
91 if ((res = ber_declen(b, &len, max)) < 0)
93 if (len+res > max || len < 0) /* out of bounds or indefinite encoding */
95 if (len > (int) sizeof(int)) /* let's be reasonable, here */
99 remains = sizeof(int) - len;
100 memcpy(tmp.c + remains, b, len);
105 memset(tmp.c, fill, remains);
114 * indent-tabs-mode: nil
116 * vim: shiftwidth=4 tabstop=8 expandtab