blob: 51098c00b584df06188f70fe317abcc9bc112c43 [file] [log] [blame]
Harald Welte92c45f32010-06-12 18:59:38 +02001/*-
2 * Copyright (c) 2004 Lev Walkin <vlm@lionet.info>. All rights reserved.
3 * Redistribution and modifications are permitted subject to BSD license.
4 */
5#if defined(__alpha)
6#define _ISOC99_SOURCE /* For quiet NAN, through bits/nan.h */
7#define _BSD_SOURCE /* To reintroduce finite(3) */
8#include <sys/resource.h> /* For INFINITY */
9#endif
10#include <asn_internal.h>
11#include <stdlib.h> /* for strtod(3) */
12#include <math.h>
13#include <errno.h>
14#include <REAL.h>
15
16#undef INT_MAX
17#define INT_MAX ((int)(((unsigned int)-1) >> 1))
18
19#if !(defined(NAN) || defined(INFINITY))
20static volatile double real_zero __attribute__ ((unused)) = 0.0;
21#endif
22#ifndef NAN
23#define NAN (real_zero/real_zero)
24#endif
25#ifndef INFINITY
26#define INFINITY (1.0/real_zero)
27#endif
28
29/*
30 * REAL basic type description.
31 */
32static ber_tlv_tag_t asn_DEF_REAL_tags[] = {
33 (ASN_TAG_CLASS_UNIVERSAL | (9 << 2))
34};
35asn_TYPE_descriptor_t asn_DEF_REAL = {
36 "REAL",
37 "REAL",
38 ASN__PRIMITIVE_TYPE_free,
39 REAL_print,
40 asn_generic_no_constraint,
41 ber_decode_primitive,
42 der_encode_primitive,
43 REAL_decode_xer,
44 REAL_encode_xer,
45 0, 0,
46 0, /* Use generic outmost tag fetcher */
47 asn_DEF_REAL_tags,
48 sizeof(asn_DEF_REAL_tags) / sizeof(asn_DEF_REAL_tags[0]),
49 asn_DEF_REAL_tags, /* Same as above */
50 sizeof(asn_DEF_REAL_tags) / sizeof(asn_DEF_REAL_tags[0]),
51 0, /* No PER visible constraints */
52 0, 0, /* No members */
53 0 /* No specifics */
54};
55
56typedef enum specialRealValue {
57 SRV__NOT_A_NUMBER,
58 SRV__MINUS_INFINITY,
59 SRV__PLUS_INFINITY
60} specialRealValue_e;
61static struct specialRealValue_s {
62 char *string;
63 size_t length;
64 long dv;
65} specialRealValue[] = {
66#define SRV_SET(foo, val) { foo, sizeof(foo) - 1, val }
67 SRV_SET("<NOT-A-NUMBER/>", 0),
68 SRV_SET("<MINUS-INFINITY/>", -1),
69 SRV_SET("<PLUS-INFINITY/>", 1),
70#undef SRV_SET
71};
72
73ssize_t
74REAL__dump(double d, int canonical, asn_app_consume_bytes_f *cb, void *app_key) {
75 char local_buf[64];
76 char *buf = local_buf;
77 ssize_t buflen = sizeof(local_buf);
78 const char *fmt = canonical?"%.15E":"%.15f";
79 ssize_t ret;
80
81 /*
82 * Check whether it is a special value.
83 */
84 /* fpclassify(3) is not portable yet */
85 if(isnan(d)) {
86 buf = specialRealValue[SRV__NOT_A_NUMBER].string;
87 buflen = specialRealValue[SRV__NOT_A_NUMBER].length;
88 return (cb(buf, buflen, app_key) < 0) ? -1 : buflen;
89 } else if(!finite(d)) {
90 if(copysign(1.0, d) < 0.0) {
91 buf = specialRealValue[SRV__MINUS_INFINITY].string;
92 buflen = specialRealValue[SRV__MINUS_INFINITY].length;
93 } else {
94 buf = specialRealValue[SRV__PLUS_INFINITY].string;
95 buflen = specialRealValue[SRV__PLUS_INFINITY].length;
96 }
97 return (cb(buf, buflen, app_key) < 0) ? -1 : buflen;
98 } else if(ilogb(d) <= -INT_MAX) {
99 if(copysign(1.0, d) < 0.0) {
100 buf = "-0";
101 buflen = 2;
102 } else {
103 buf = "0";
104 buflen = 1;
105 }
106 return (cb(buf, buflen, app_key) < 0) ? -1 : buflen;
107 }
108
109 /*
110 * Use the libc's double printing, hopefully they got it right.
111 */
112 do {
113 ret = snprintf(buf, buflen, fmt, d);
114 if(ret < 0) {
115 buflen <<= 1;
116 } else if(ret >= buflen) {
117 buflen = ret + 1;
118 } else {
119 buflen = ret;
120 break;
121 }
122 if(buf != local_buf) FREEMEM(buf);
123 buf = (char *)MALLOC(buflen);
124 if(!buf) return -1;
125 } while(1);
126
127 if(canonical) {
128 /*
129 * Transform the "[-]d.dddE+-dd" output into "[-]d.dddE[-]d"
130 * Check that snprintf() constructed the output correctly.
131 */
132 char *dot, *E;
133 char *end = buf + buflen;
134 char *last_zero;
135
136 dot = (buf[0] == 0x2d /* '-' */) ? (buf + 2) : (buf + 1);
137 if(*dot >= 0x30) {
138 errno = EINVAL;
139 return -1; /* Not a dot, really */
140 }
141 *dot = 0x2e; /* Replace possible comma */
142
143 for(last_zero = dot + 2, E = dot; dot < end; E++) {
144 if(*E == 0x45) {
145 char *expptr = ++E;
146 char *s = expptr;
147 int sign;
148 if(*expptr == 0x2b /* '+' */) {
149 /* Skip the "+" */
150 buflen -= 1;
151 sign = 0;
152 } else {
153 sign = 1;
154 s++;
155 }
156 expptr++;
157 if(expptr > end) {
158 errno = EINVAL;
159 return -1;
160 }
161 if(*expptr == 0x30) {
162 buflen--;
163 expptr++;
164 }
165 if(*last_zero == 0x30) {
166 *last_zero = 0x45; /* E */
167 buflen -= s - (last_zero + 1);
168 s = last_zero + 1;
169 if(sign) {
170 *s++ = 0x2d /* '-' */;
171 buflen++;
172 }
173 }
174 for(; expptr <= end; s++, expptr++)
175 *s = *expptr;
176 break;
177 } else if(*E == 0x30) {
178 if(*last_zero != 0x30)
179 last_zero = E;
180 }
181 }
182 if(E == end) {
183 errno = EINVAL;
184 return -1; /* No promised E */
185 }
186 } else {
187 /*
188 * Remove trailing zeros.
189 */
190 char *end = buf + buflen;
191 char *last_zero = end;
192 int stoplooking = 0;
193 char *z;
194 for(z = end - 1; z > buf; z--) {
195 switch(*z) {
196 case 0x30:
197 if(!stoplooking)
198 last_zero = z;
199 continue;
200 case 0x31: case 0x32: case 0x33: case 0x34:
201 case 0x35: case 0x36: case 0x37: case 0x38: case 0x39:
202 stoplooking = 1;
203 continue;
204 default: /* Catch dot and other separators */
205 /*
206 * Replace possible comma (which may even
207 * be not a comma at all: locale-defined).
208 */
209 *z = 0x2e;
210 if(last_zero == z + 1) { /* leave x.0 */
211 last_zero++;
212 }
213 buflen = last_zero - buf;
214 *last_zero = '\0';
215 break;
216 }
217 break;
218 }
219 }
220
221 ret = cb(buf, buflen, app_key);
222 if(buf != local_buf) FREEMEM(buf);
223 return (ret < 0) ? -1 : buflen;
224}
225
226int
227REAL_print(asn_TYPE_descriptor_t *td, const void *sptr, int ilevel,
228 asn_app_consume_bytes_f *cb, void *app_key) {
229 const REAL_t *st = (const REAL_t *)sptr;
230 ssize_t ret;
231 double d;
232
233 (void)td; /* Unused argument */
234 (void)ilevel; /* Unused argument */
235
236 if(!st || !st->buf)
237 ret = cb("<absent>", 8, app_key);
238 else if(asn_REAL2double(st, &d))
239 ret = cb("<error>", 7, app_key);
240 else
241 ret = REAL__dump(d, 0, cb, app_key);
242
243 return (ret < 0) ? -1 : 0;
244}
245
246asn_enc_rval_t
247REAL_encode_xer(asn_TYPE_descriptor_t *td, void *sptr,
248 int ilevel, enum xer_encoder_flags_e flags,
249 asn_app_consume_bytes_f *cb, void *app_key) {
250 REAL_t *st = (REAL_t *)sptr;
251 asn_enc_rval_t er;
252 double d;
253
254 (void)ilevel;
255
256 if(!st || !st->buf || asn_REAL2double(st, &d))
257 _ASN_ENCODE_FAILED;
258
259 er.encoded = REAL__dump(d, flags & XER_F_CANONICAL, cb, app_key);
260 if(er.encoded < 0) _ASN_ENCODE_FAILED;
261
262 _ASN_ENCODED_OK(er);
263}
264
265
266/*
267 * Decode the chunk of XML text encoding REAL.
268 */
269static enum xer_pbd_rval
270REAL__xer_body_decode(asn_TYPE_descriptor_t *td, void *sptr, const void *chunk_buf, size_t chunk_size) {
271 REAL_t *st = (REAL_t *)sptr;
272 double value;
273 const char *xerdata = (const char *)chunk_buf;
274 char *endptr = 0;
275 char *b;
276
277 (void)td;
278
279 if(!chunk_size) return XPBD_BROKEN_ENCODING;
280
281 /*
282 * Decode an XMLSpecialRealValue: <MINUS-INFINITY>, etc.
283 */
284 if(xerdata[0] == 0x3c /* '<' */) {
285 size_t i;
286 for(i = 0; i < sizeof(specialRealValue)
287 / sizeof(specialRealValue[0]); i++) {
288 struct specialRealValue_s *srv = &specialRealValue[i];
289 double dv;
290
291 if(srv->length != chunk_size
292 || memcmp(srv->string, chunk_buf, chunk_size))
293 continue;
294
295 /*
296 * It could've been done using
297 * (double)srv->dv / real_zero,
298 * but it summons fp exception on some platforms.
299 */
300 switch(srv->dv) {
301 case -1: dv = - INFINITY; break;
302 case 0: dv = NAN; break;
303 case 1: dv = INFINITY; break;
304 default: return XPBD_SYSTEM_FAILURE;
305 }
306
307 if(asn_double2REAL(st, dv))
308 return XPBD_SYSTEM_FAILURE;
309
310 return XPBD_BODY_CONSUMED;
311 }
312 ASN_DEBUG("Unknown XMLSpecialRealValue");
313 return XPBD_BROKEN_ENCODING;
314 }
315
316 /*
317 * Copy chunk into the nul-terminated string, and run strtod.
318 */
319 b = (char *)MALLOC(chunk_size + 1);
320 if(!b) return XPBD_SYSTEM_FAILURE;
321 memcpy(b, chunk_buf, chunk_size);
322 b[chunk_size] = 0; /* nul-terminate */
323
324 value = strtod(b, &endptr);
325 FREEMEM(b);
326 if(endptr == b) return XPBD_BROKEN_ENCODING;
327
328 if(asn_double2REAL(st, value))
329 return XPBD_SYSTEM_FAILURE;
330
331 return XPBD_BODY_CONSUMED;
332}
333
334asn_dec_rval_t
335REAL_decode_xer(asn_codec_ctx_t *opt_codec_ctx,
336 asn_TYPE_descriptor_t *td, void **sptr, const char *opt_mname,
337 const void *buf_ptr, size_t size) {
338
339 return xer_decode_primitive(opt_codec_ctx, td,
340 sptr, sizeof(REAL_t), opt_mname,
341 buf_ptr, size, REAL__xer_body_decode);
342}
343
344
345int
346asn_REAL2double(const REAL_t *st, double *dbl_value) {
347 unsigned int octv;
348
349 if(!st || !st->buf) {
350 errno = EINVAL;
351 return -1;
352 }
353
354 if(st->size == 0) {
355 *dbl_value = 0;
356 return 0;
357 }
358
359 octv = st->buf[0]; /* unsigned byte */
360
361 switch(octv & 0xC0) {
362 case 0x40: /* X.690: 8.5.8 */
363 /* "SpecialRealValue" */
364
365 /* Be liberal in what you accept...
366 if(st->size != 1) ...
367 */
368
369 switch(st->buf[0]) {
370 case 0x40: /* 01000000: PLUS-INFINITY */
371 *dbl_value = INFINITY;
372 return 0;
373 case 0x41: /* 01000001: MINUS-INFINITY */
374 *dbl_value = - INFINITY;
375 return 0;
376 /*
377 * The following cases are defined by
378 * X.690 Amendment 1 (10/03)
379 */
380 case 0x42: /* 01000010: NOT-A-NUMBER */
381 *dbl_value = NAN;
382 return 0;
383 case 0x43: /* 01000011: minus zero */
384 *dbl_value = -0.0;
385 return 0;
386 }
387
388 errno = EINVAL;
389 return -1;
390 case 0x00: { /* X.690: 8.5.6 */
391 /*
392 * Decimal. NR{1,2,3} format.
393 */
394 double d;
395
396 assert(st->buf[st->size - 1] == 0); /* Security, vashu mat' */
397
398 d = strtod((char *)st->buf, 0);
399 if(finite(d)) {
400 *dbl_value = d;
401 return 0;
402 } else {
403 errno = ERANGE;
404 return 0;
405 }
406 }
407 }
408
409 /*
410 * Binary representation.
411 */
412 {
413 double m;
414 int expval; /* exponent value */
415 unsigned int elen; /* exponent value length, in octets */
416 unsigned int scaleF;
417 unsigned int baseF;
418 uint8_t *ptr;
419 uint8_t *end;
420 int sign;
421
422 switch((octv & 0x30) >> 4) {
423 case 0x00: baseF = 1; break; /* base 2 */
424 case 0x01: baseF = 3; break; /* base 8 */
425 case 0x02: baseF = 4; break; /* base 16 */
426 default:
427 /* Reserved field, can't parse now. */
428 errno = EINVAL;
429 return -1;
430 }
431
432 sign = (octv & 0x40); /* bit 7 */
433 scaleF = (octv & 0x0C) >> 2; /* bits 4 to 3 */
434
435 if(st->size <= (int)(1 + (octv & 0x03))) {
436 errno = EINVAL;
437 return -1;
438 }
439
440 if((octv & 0x03) == 0x11) {
441 /* 8.5.6.4, case d) */
442 elen = st->buf[1]; /* unsigned binary number */
443 if(elen == 0 || st->size <= (int)(2 + elen)) {
444 errno = EINVAL;
445 return -1;
446 }
447 ptr = &st->buf[2];
448 } else {
449 elen = (octv & 0x03);
450 ptr = &st->buf[1];
451 }
452
453 /* Fetch the multibyte exponent */
454 expval = (int)(*(int8_t *)ptr);
455 end = ptr + elen + 1;
456 for(ptr++; ptr < end; ptr++)
457 expval = (expval * 256) + *ptr;
458
459 m = 0.0; /* Initial mantissa value */
460
461 /* Okay, the exponent is here. Now, what about mantissa? */
462 end = st->buf + st->size;
463 if(ptr < end) {
464 for(; ptr < end; ptr++)
465 m = ldexp(m, 8) + *ptr;
466 }
467
468 if(0)
469 ASN_DEBUG("m=%.10f, scF=%d, bF=%d, expval=%d, ldexp()=%f, ldexp()=%f",
470 m, scaleF, baseF, expval,
471 ldexp(m, expval * baseF + scaleF),
472 ldexp(m, scaleF) * pow(pow(2, baseF), expval)
473 );
474
475 /*
476 * (S * N * 2^F) * B^E
477 * Essentially:
478 m = ldexp(m, scaleF) * pow(pow(2, base), expval);
479 */
480 m = ldexp(m, expval * baseF + scaleF);
481 if(finite(m)) {
482 *dbl_value = sign ? -m : m;
483 } else {
484 errno = ERANGE;
485 return -1;
486 }
487
488 } /* if(binary_format) */
489
490 return 0;
491}
492
493/*
494 * Assume IEEE 754 floating point: standard 64 bit double.
495 * [1 bit sign] [11 bits exponent] [52 bits mantissa]
496 */
497int
498asn_double2REAL(REAL_t *st, double dbl_value) {
499#ifdef WORDS_BIGENDIAN /* Known to be big-endian */
500 int littleEndian = 0;
501#else /* need to test: have no explicit information */
502 unsigned int LE = 1;
503 int littleEndian = *(unsigned char *)&LE;
504#endif
505 uint8_t buf[16]; /* More than enough for 8-byte dbl_value */
506 uint8_t dscr[sizeof(dbl_value)]; /* double value scratch pad */
507 /* Assertion guards: won't even compile, if unexpected double size */
508 char assertion_buffer1[9 - sizeof(dbl_value)] __attribute__((unused));
509 char assertion_buffer2[sizeof(dbl_value) - 7] __attribute__((unused));
510 uint8_t *ptr = buf;
511 uint8_t *mstop; /* Last byte of mantissa */
512 unsigned int mval; /* Value of the last byte of mantissa */
513 unsigned int bmsign; /* binary mask with sign */
514 unsigned int buflen;
515 unsigned int accum;
516 int expval;
517
518 if(!st) {
519 errno = EINVAL;
520 return -1;
521 }
522
523 /*
524 * ilogb(+-0) returns -INT_MAX or INT_MIN (platform-dependent)
525 * ilogb(+-inf) returns INT_MAX, logb(+-inf) returns +inf
526 * ilogb(NaN) returns INT_MIN or INT_MAX (platform-dependent)
527 */
528 expval = ilogb(dbl_value);
529 if(expval <= -INT_MAX /* Also catches +-0 and maybe isnan() */
530 || expval == INT_MAX /* catches isfin() and maybe isnan() */
531 ) {
532 if(!st->buf || st->size < 2) {
533 ptr = (uint8_t *)MALLOC(2);
534 if(!ptr) return -1;
535 st->buf = ptr;
536 }
537 /* fpclassify(3) is not portable yet */
538 if(isnan(dbl_value)) {
539 st->buf[0] = 0x42; /* NaN */
540 st->buf[1] = 0;
541 st->size = 1;
542 } else if(!finite(dbl_value)) {
543 if(copysign(1.0, dbl_value) < 0.0) {
544 st->buf[0] = 0x41; /* MINUS-INFINITY */
545 } else {
546 st->buf[0] = 0x40; /* PLUS-INFINITY */
547 }
548 st->buf[1] = 0;
549 st->size = 1;
550 } else {
551 if(copysign(1.0, dbl_value) < 0.0) {
552 st->buf[0] = 0x80 | 0x40;
553 st->buf[1] = 0;
554 st->size = 2;
555 } else {
556 /* no content octets: positive zero */
557 st->buf[0] = 0; /* JIC */
558 st->size = 0;
559 }
560 }
561 return 0;
562 }
563
564 if(littleEndian) {
565 uint8_t *s = ((uint8_t *)&dbl_value) + sizeof(dbl_value) - 2;
566 uint8_t *start = ((uint8_t *)&dbl_value);
567 uint8_t *d;
568
569 bmsign = 0x80 | ((s[1] >> 1) & 0x40); /* binary mask & - */
570 for(mstop = d = dscr; s >= start; d++, s--) {
571 *d = *s;
572 if(*d) mstop = d;
573 }
574 } else {
575 uint8_t *s = ((uint8_t *)&dbl_value) + 1;
576 uint8_t *end = ((uint8_t *)&dbl_value) + sizeof(double);
577 uint8_t *d;
578
579 bmsign = 0x80 | ((s[-1] >> 1) & 0x40); /* binary mask & - */
580 for(mstop = d = dscr; s < end; d++, s++) {
581 *d = *s;
582 if(*d) mstop = d;
583 }
584 }
585
586 /* Remove parts of the exponent, leave mantissa and explicit 1. */
587 dscr[0] = 0x10 | (dscr[0] & 0x0f);
588
589 /* Adjust exponent in a very unobvious way */
590 expval -= 8 * ((mstop - dscr) + 1) - 4;
591
592 /* This loop ensures DER conformance by forcing mantissa odd: 11.3.1 */
593 mval = *mstop;
594 if(mval && !(mval & 1)) {
595 unsigned int shift_count = 1;
596 unsigned int ishift;
597 uint8_t *mptr;
598
599 /*
600 * Figure out what needs to be done to make mantissa odd.
601 */
602 if(!(mval & 0x0f)) /* Speed-up a little */
603 shift_count = 4;
604 while(((mval >> shift_count) & 1) == 0)
605 shift_count++;
606
607 ishift = 8 - shift_count;
608 accum = 0;
609
610 /* Go over the buffer, shifting it shift_count bits right. */
611 for(mptr = dscr; mptr <= mstop; mptr++) {
612 mval = *mptr;
613 *mptr = accum | (mval >> shift_count);
614 accum = mval << ishift;
615 }
616
617 /* Adjust mantissa appropriately. */
618 expval += shift_count;
619 }
620
621 if(expval < 0) {
622 if((expval >> 7) == -1) {
623 *ptr++ = bmsign | 0x00;
624 *ptr++ = expval;
625 } else if((expval >> 15) == -1) {
626 *ptr++ = bmsign | 0x01;
627 *ptr++ = expval >> 8;
628 *ptr++ = expval;
629 } else {
630 *ptr++ = bmsign | 0x02;
631 *ptr++ = expval >> 16;
632 *ptr++ = expval >> 8;
633 *ptr++ = expval;
634 }
635 } else if(expval <= 0x7f) {
636 *ptr++ = bmsign | 0x00;
637 *ptr++ = expval;
638 } else if(expval <= 0x7fff) {
639 *ptr++ = bmsign | 0x01;
640 *ptr++ = expval >> 8;
641 *ptr++ = expval;
642 } else {
643 assert(expval <= 0x7fffff);
644 *ptr++ = bmsign | 0x02;
645 *ptr++ = expval >> 16;
646 *ptr++ = expval >> 8;
647 *ptr++ = expval;
648 }
649
650 buflen = (mstop - dscr) + 1;
651 memcpy(ptr, dscr, buflen);
652 ptr += buflen;
653 buflen = ptr - buf;
654
655 ptr = (uint8_t *)MALLOC(buflen + 1);
656 if(!ptr) return -1;
657
658 memcpy(ptr, buf, buflen);
659 buf[buflen] = 0; /* JIC */
660
661 if(st->buf) FREEMEM(st->buf);
662 st->buf = ptr;
663 st->size = buflen;
664
665 return 0;
666}