1 /* This file is part of the YAZ toolkit.
2 * Copyright (C) 1995-2009 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>
28 #include <netinet/in.h>
33 static int ber_encinteger(ODR o, Odr_int val);
34 static int ber_decinteger(const unsigned char *buf, Odr_int *val, int max);
36 int ber_integer(ODR o, Odr_int *val)
43 if ((res = ber_decinteger(o->bp, val, odr_max(o))) <= 0)
45 odr_seterror(o, OPROTO, 50);
51 if ((res = ber_encinteger(o, *val)) < 0)
57 odr_seterror(o, OOTHER, 51); return 0;
62 * Returns: number of bytes written or -1 for error (out of bounds).
64 int ber_encinteger(ODR o, Odr_int val)
67 union { int i; unsigned char c[sizeof(int)]; } tmp;
69 tmp.i = htonl(val); /* ensure that that we're big-endian */
70 for (a = 0; a < (int) sizeof(int) - 1; a++) /* skip superfluous octets */
71 if (!((tmp.c[a] == 0 && !(tmp.c[a+1] & 0X80)) ||
72 (tmp.c[a] == 0XFF && (tmp.c[a+1] & 0X80))))
74 len = sizeof(int) - a;
75 if (ber_enclen(o, len, 1, 1) != 1)
77 if (odr_write(o, (unsigned char*) tmp.c + a, len) < 0)
83 * Returns: Number of bytes read or 0 if no match, -1 if error.
85 int ber_decinteger(const unsigned char *buf, Odr_int *val, int max)
87 const unsigned char *b = buf;
89 int res, len, remains;
90 union { int i; unsigned char c[sizeof(int)]; } tmp;
92 if ((res = ber_declen(b, &len, max)) < 0)
94 if (len+res > max || len < 0) /* out of bounds or indefinite encoding */
96 if (len > (int) sizeof(int)) /* let's be reasonable, here */
100 remains = sizeof(int) - len;
101 memcpy(tmp.c + remains, b, len);
106 memset(tmp.c, fill, remains);
115 * c-file-style: "Stroustrup"
116 * indent-tabs-mode: nil
118 * vim: shiftwidth=4 tabstop=8 expandtab