| 1 | /* -*-c-*- |
| 2 | * |
| 3 | * $Id: mptext.c,v 1.10 2001/06/16 13:22:39 mdw Exp $ |
| 4 | * |
| 5 | * Textual representation of multiprecision numbers |
| 6 | * |
| 7 | * (c) 1999 Straylight/Edgeware |
| 8 | */ |
| 9 | |
| 10 | /*----- Licensing notice --------------------------------------------------* |
| 11 | * |
| 12 | * This file is part of Catacomb. |
| 13 | * |
| 14 | * Catacomb is free software; you can redistribute it and/or modify |
| 15 | * it under the terms of the GNU Library General Public License as |
| 16 | * published by the Free Software Foundation; either version 2 of the |
| 17 | * License, or (at your option) any later version. |
| 18 | * |
| 19 | * Catacomb is distributed in the hope that it will be useful, |
| 20 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 21 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 22 | * GNU Library General Public License for more details. |
| 23 | * |
| 24 | * You should have received a copy of the GNU Library General Public |
| 25 | * License along with Catacomb; if not, write to the Free |
| 26 | * Software Foundation, Inc., 59 Temple Place - Suite 330, Boston, |
| 27 | * MA 02111-1307, USA. |
| 28 | */ |
| 29 | |
| 30 | /*----- Revision history --------------------------------------------------* |
| 31 | * |
| 32 | * $Log: mptext.c,v $ |
| 33 | * Revision 1.10 2001/06/16 13:22:39 mdw |
| 34 | * Added fast-track code for binary output bases, and tests. |
| 35 | * |
| 36 | * Revision 1.9 2001/02/03 16:05:17 mdw |
| 37 | * Make flags be unsigned. Improve the write algorithm: recurse until the |
| 38 | * parts are one word long and use single-precision arithmetic from there. |
| 39 | * Fix off-by-one bug when breaking the number apart. |
| 40 | * |
| 41 | * Revision 1.8 2000/12/06 20:32:42 mdw |
| 42 | * Reduce binary bytes (to allow marker bits to be ignored). Fix error |
| 43 | * message string a bit. Allow leading `+' signs. |
| 44 | * |
| 45 | * Revision 1.7 2000/07/15 10:01:08 mdw |
| 46 | * Bug fix in binary input. |
| 47 | * |
| 48 | * Revision 1.6 2000/06/25 12:58:23 mdw |
| 49 | * Fix the derivation of `depth' commentary. |
| 50 | * |
| 51 | * Revision 1.5 2000/06/17 11:46:19 mdw |
| 52 | * New and much faster stack-based algorithm for reading integers. Support |
| 53 | * reading and writing binary integers in bases between 2 and 256. |
| 54 | * |
| 55 | * Revision 1.4 1999/12/22 15:56:56 mdw |
| 56 | * Use clever recursive algorithm for writing numbers out. |
| 57 | * |
| 58 | * Revision 1.3 1999/12/10 23:23:26 mdw |
| 59 | * Allocate slightly less memory. |
| 60 | * |
| 61 | * Revision 1.2 1999/11/20 22:24:15 mdw |
| 62 | * Use function versions of MPX_UMULN and MPX_UADDN. |
| 63 | * |
| 64 | * Revision 1.1 1999/11/17 18:02:16 mdw |
| 65 | * New multiprecision integer arithmetic suite. |
| 66 | * |
| 67 | */ |
| 68 | |
| 69 | /*----- Header files ------------------------------------------------------*/ |
| 70 | |
| 71 | #include <ctype.h> |
| 72 | #include <limits.h> |
| 73 | #include <stdio.h> |
| 74 | |
| 75 | #include "mp.h" |
| 76 | #include "mptext.h" |
| 77 | #include "paranoia.h" |
| 78 | |
| 79 | /*----- Magical numbers ---------------------------------------------------*/ |
| 80 | |
| 81 | /* --- Maximum recursion depth --- * |
| 82 | * |
| 83 | * This is the number of bits in a @size_t@ object. Why? |
| 84 | * |
| 85 | * To see this, let %$b = \mathit{MPW\_MAX} + 1$% and let %$Z$% be the |
| 86 | * largest @size_t@ value. Then the largest possible @mp@ is %$M - 1$% where |
| 87 | * %$M = b^Z$%. Let %$r$% be a radix to read or write. Since the recursion |
| 88 | * squares the radix at each step, the highest number reached by the |
| 89 | * recursion is %$d$%, where: |
| 90 | * |
| 91 | * %$r^{2^d} = b^Z$%. |
| 92 | * |
| 93 | * Solving gives that %$d = \lg \log_r b^Z$%. If %$r = 2$%, this is maximum, |
| 94 | * so choosing %$d = \lg \lg b^Z = \lg (Z \lg b) = \lg Z + \lg \lg b$%. |
| 95 | * |
| 96 | * Expressing %$\lg Z$% as @CHAR_BIT * sizeof(size_t)@ yields an |
| 97 | * overestimate, since a @size_t@ representation may contain `holes'. |
| 98 | * Choosing to represent %$\lg \lg b$% by 10 is almost certainly sufficient |
| 99 | * for `some time to come'. |
| 100 | */ |
| 101 | |
| 102 | #define DEPTH (CHAR_BIT * sizeof(size_t) + 10) |
| 103 | |
| 104 | /*----- Main code ---------------------------------------------------------*/ |
| 105 | |
| 106 | /* --- @mp_read@ --- * |
| 107 | * |
| 108 | * Arguments: @mp *m@ = destination multiprecision number |
| 109 | * @int radix@ = base to assume for data (or zero to guess) |
| 110 | * @const mptext_ops *ops@ = pointer to operations block |
| 111 | * @void *p@ = data for the operations block |
| 112 | * |
| 113 | * Returns: The integer read, or zero if it didn't work. |
| 114 | * |
| 115 | * Use: Reads an integer from some source. If the @radix@ is |
| 116 | * specified, the number is assumed to be given in that radix, |
| 117 | * with the letters `a' (either upper- or lower-case) upwards |
| 118 | * standing for digits greater than 9. Otherwise, base 10 is |
| 119 | * assumed unless the number starts with `0' (octal), `0x' (hex) |
| 120 | * or `nnn_' (base `nnn'). An arbitrary amount of whitespace |
| 121 | * before the number is ignored. |
| 122 | */ |
| 123 | |
| 124 | /* --- About the algorithm --- * |
| 125 | * |
| 126 | * The algorithm here is rather aggressive. I maintain an array of |
| 127 | * successive squarings of the radix, and a stack of partial results, each |
| 128 | * with a counter attached indicating which radix square to multiply by. |
| 129 | * Once the item at the top of the stack reaches the same counter level as |
| 130 | * the next item down, they are combined together and the result is given a |
| 131 | * counter level one higher than either of the results. |
| 132 | * |
| 133 | * Gluing the results together at the end is slightly tricky. Pay attention |
| 134 | * to the code. |
| 135 | * |
| 136 | * This is more complicated because of the need to handle the slightly |
| 137 | * bizarre syntax. |
| 138 | */ |
| 139 | |
| 140 | mp *mp_read(mp *m, int radix, const mptext_ops *ops, void *p) |
| 141 | { |
| 142 | int ch; /* Current char being considered */ |
| 143 | unsigned f = 0; /* Flags about the current number */ |
| 144 | int r; /* Radix to switch over to */ |
| 145 | mpw rd; /* Radix as an @mp@ digit */ |
| 146 | mp rr; /* The @mp@ for the radix */ |
| 147 | unsigned nf = m ? m->f & MP_BURN : 0; /* New @mp@ flags */ |
| 148 | |
| 149 | /* --- Stacks --- */ |
| 150 | |
| 151 | mp *pow[DEPTH]; /* List of powers */ |
| 152 | unsigned pows; /* Next index to fill */ |
| 153 | struct { unsigned i; mp *m; } s[DEPTH]; /* Main stack */ |
| 154 | unsigned sp; /* Current stack pointer */ |
| 155 | |
| 156 | /* --- Flags --- */ |
| 157 | |
| 158 | #define f_neg 1u |
| 159 | #define f_ok 2u |
| 160 | #define f_start 4u |
| 161 | |
| 162 | /* --- Initialize the stacks --- */ |
| 163 | |
| 164 | mp_build(&rr, &rd, &rd + 1); |
| 165 | pow[0] = &rr; |
| 166 | pows = 1; |
| 167 | |
| 168 | sp = 0; |
| 169 | |
| 170 | /* --- Initialize the destination number --- */ |
| 171 | |
| 172 | if (m) |
| 173 | MP_DROP(m); |
| 174 | |
| 175 | /* --- Read an initial character --- */ |
| 176 | |
| 177 | ch = ops->get(p); |
| 178 | while (isspace(ch)) |
| 179 | ch = ops->get(p); |
| 180 | |
| 181 | /* --- Handle an initial sign --- */ |
| 182 | |
| 183 | if (radix >= 0 && (ch == '-' || ch == '+')) { |
| 184 | if (ch == '-') |
| 185 | f |= f_neg; |
| 186 | do ch = ops->get(p); while isspace(ch); |
| 187 | } |
| 188 | |
| 189 | /* --- If the radix is zero, look for leading zeros --- */ |
| 190 | |
| 191 | if (radix > 0) { |
| 192 | assert(((void)"ascii radix must be <= 36", radix <= 36)); |
| 193 | rd = radix; |
| 194 | r = -1; |
| 195 | } else if (radix < 0) { |
| 196 | rd = -radix; |
| 197 | assert(((void)"binary radix must fit in a byte", rd < UCHAR_MAX)); |
| 198 | r = -1; |
| 199 | } else if (ch != '0') { |
| 200 | rd = 10; |
| 201 | r = 0; |
| 202 | } else { |
| 203 | ch = ops->get(p); |
| 204 | if (ch == 'x') { |
| 205 | ch = ops->get(p); |
| 206 | rd = 16; |
| 207 | } else { |
| 208 | rd = 8; |
| 209 | f |= f_ok; |
| 210 | } |
| 211 | r = -1; |
| 212 | } |
| 213 | |
| 214 | /* --- Use fast algorithm for binary radix --- * |
| 215 | * |
| 216 | * This is the restart point after having parsed a radix number from the |
| 217 | * input. We check whether the radix is binary, and if so use a fast |
| 218 | * algorithm which just stacks the bits up in the right order. |
| 219 | */ |
| 220 | |
| 221 | restart: |
| 222 | switch (rd) { |
| 223 | unsigned bit; |
| 224 | |
| 225 | case 2: bit = 1; goto bin; |
| 226 | case 4: bit = 2; goto bin; |
| 227 | case 8: bit = 3; goto bin; |
| 228 | case 16: bit = 4; goto bin; |
| 229 | case 32: bit = 5; goto bin; |
| 230 | case 64: bit = 6; goto bin; |
| 231 | case 128: bit = 7; goto bin; |
| 232 | default: |
| 233 | break; |
| 234 | |
| 235 | /* --- The fast binary algorithm --- * |
| 236 | * |
| 237 | * We stack bits up starting at the top end of a word. When one word is |
| 238 | * full, we write it to the integer, and start another with the left-over |
| 239 | * bits. When the array in the integer is full, we resize using low-level |
| 240 | * calls and copy the current data to the top end. Finally, we do a single |
| 241 | * bit-shift when we know where the end of the number is. |
| 242 | */ |
| 243 | |
| 244 | bin: { |
| 245 | mpw a = 0; |
| 246 | unsigned b = MPW_BITS; |
| 247 | size_t len, n; |
| 248 | mpw *v; |
| 249 | |
| 250 | m = mp_dest(MP_NEW, 1, nf); |
| 251 | len = n = m->sz; |
| 252 | n = len; |
| 253 | v = m->v + n; |
| 254 | for (;; ch = ops->get(p)) { |
| 255 | unsigned x; |
| 256 | |
| 257 | if (ch < 0) |
| 258 | break; |
| 259 | |
| 260 | /* --- Check that the character is a digit and in range --- */ |
| 261 | |
| 262 | if (radix < 0) |
| 263 | x = ch % rd; |
| 264 | else { |
| 265 | if (!isalnum(ch)) |
| 266 | break; |
| 267 | if (ch >= '0' && ch <= '9') |
| 268 | x = ch - '0'; |
| 269 | else { |
| 270 | ch = tolower(ch); |
| 271 | if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */ |
| 272 | x = ch - 'a' + 10; |
| 273 | else |
| 274 | break; |
| 275 | } |
| 276 | } |
| 277 | if (x >= rd) |
| 278 | break; |
| 279 | |
| 280 | /* --- Feed the digit into the accumulator --- */ |
| 281 | |
| 282 | f |= f_ok; |
| 283 | if (!x && !(f & f_start)) |
| 284 | continue; |
| 285 | f |= f_start; |
| 286 | if (b > bit) { |
| 287 | b -= bit; |
| 288 | a |= MPW(x) << b; |
| 289 | } else { |
| 290 | a |= MPW(x) >> (bit - b); |
| 291 | b += MPW_BITS - bit; |
| 292 | *--v = MPW(a); |
| 293 | n--; |
| 294 | if (!n) { |
| 295 | n = len; |
| 296 | len <<= 1; |
| 297 | v = mpalloc(m->a, len); |
| 298 | memcpy(v + n, m->v, MPWS(n)); |
| 299 | mpfree(m->a, m->v); |
| 300 | m->v = v; |
| 301 | v = m->v + n; |
| 302 | } |
| 303 | a = (b < MPW_BITS) ? MPW(x) << b : 0; |
| 304 | } |
| 305 | } |
| 306 | |
| 307 | /* --- Finish up --- */ |
| 308 | |
| 309 | if (!(f & f_ok)) { |
| 310 | mp_drop(m); |
| 311 | m = 0; |
| 312 | } else { |
| 313 | *--v = MPW(a); |
| 314 | n--; |
| 315 | m->sz = len; |
| 316 | m->vl = m->v + len; |
| 317 | m->f &= ~MP_UNDEF; |
| 318 | m = mp_lsr(m, m, (unsigned long)n * MPW_BITS + b); |
| 319 | } |
| 320 | goto done; |
| 321 | }} |
| 322 | |
| 323 | /* --- Time to start --- */ |
| 324 | |
| 325 | for (;; ch = ops->get(p)) { |
| 326 | unsigned x; |
| 327 | |
| 328 | if (ch < 0) |
| 329 | break; |
| 330 | |
| 331 | /* --- An underscore indicates a numbered base --- */ |
| 332 | |
| 333 | if (ch == '_' && r > 0 && r <= 36) { |
| 334 | unsigned i; |
| 335 | |
| 336 | /* --- Clear out the stacks --- */ |
| 337 | |
| 338 | for (i = 1; i < pows; i++) |
| 339 | MP_DROP(pow[i]); |
| 340 | pows = 1; |
| 341 | for (i = 0; i < sp; i++) |
| 342 | MP_DROP(s[i].m); |
| 343 | sp = 0; |
| 344 | |
| 345 | /* --- Restart the search --- */ |
| 346 | |
| 347 | rd = r; |
| 348 | r = -1; |
| 349 | f &= ~f_ok; |
| 350 | ch = ops->get(p); |
| 351 | goto restart; |
| 352 | } |
| 353 | |
| 354 | /* --- Check that the character is a digit and in range --- */ |
| 355 | |
| 356 | if (radix < 0) |
| 357 | x = ch % rd; |
| 358 | else { |
| 359 | if (!isalnum(ch)) |
| 360 | break; |
| 361 | if (ch >= '0' && ch <= '9') |
| 362 | x = ch - '0'; |
| 363 | else { |
| 364 | ch = tolower(ch); |
| 365 | if (ch >= 'a' && ch <= 'z') /* ASCII dependent! */ |
| 366 | x = ch - 'a' + 10; |
| 367 | else |
| 368 | break; |
| 369 | } |
| 370 | } |
| 371 | |
| 372 | /* --- Sort out what to do with the character --- */ |
| 373 | |
| 374 | if (x >= 10 && r >= 0) |
| 375 | r = -1; |
| 376 | if (x >= rd) |
| 377 | break; |
| 378 | |
| 379 | if (r >= 0) |
| 380 | r = r * 10 + x; |
| 381 | |
| 382 | /* --- Stick the character on the end of my integer --- */ |
| 383 | |
| 384 | assert(((void)"Number is too unimaginably huge", sp < DEPTH)); |
| 385 | s[sp].m = m = mp_new(1, nf); |
| 386 | m->v[0] = x; |
| 387 | s[sp].i = 0; |
| 388 | |
| 389 | /* --- Now grind through the stack --- */ |
| 390 | |
| 391 | while (sp > 0 && s[sp - 1].i == s[sp].i) { |
| 392 | |
| 393 | /* --- Combine the top two items --- */ |
| 394 | |
| 395 | sp--; |
| 396 | m = s[sp].m; |
| 397 | m = mp_mul(m, m, pow[s[sp].i]); |
| 398 | m = mp_add(m, m, s[sp + 1].m); |
| 399 | s[sp].m = m; |
| 400 | MP_DROP(s[sp + 1].m); |
| 401 | s[sp].i++; |
| 402 | |
| 403 | /* --- Make a new radix power if necessary --- */ |
| 404 | |
| 405 | if (s[sp].i >= pows) { |
| 406 | assert(((void)"Number is too unimaginably huge", pows < DEPTH)); |
| 407 | pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]); |
| 408 | pows++; |
| 409 | } |
| 410 | } |
| 411 | f |= f_ok; |
| 412 | sp++; |
| 413 | } |
| 414 | |
| 415 | ops->unget(ch, p); |
| 416 | |
| 417 | /* --- If we're done, compute the rest of the number --- */ |
| 418 | |
| 419 | if (f & f_ok) { |
| 420 | if (!sp) |
| 421 | return (MP_ZERO); |
| 422 | else { |
| 423 | mp *z = MP_ONE; |
| 424 | sp--; |
| 425 | |
| 426 | while (sp > 0) { |
| 427 | |
| 428 | /* --- Combine the top two items --- */ |
| 429 | |
| 430 | sp--; |
| 431 | m = s[sp].m; |
| 432 | z = mp_mul(z, z, pow[s[sp + 1].i]); |
| 433 | m = mp_mul(m, m, z); |
| 434 | m = mp_add(m, m, s[sp + 1].m); |
| 435 | s[sp].m = m; |
| 436 | MP_DROP(s[sp + 1].m); |
| 437 | |
| 438 | /* --- Make a new radix power if necessary --- */ |
| 439 | |
| 440 | if (s[sp].i >= pows) { |
| 441 | assert(((void)"Number is too unimaginably huge", pows < DEPTH)); |
| 442 | pow[pows] = mp_sqr(MP_NEW, pow[pows - 1]); |
| 443 | pows++; |
| 444 | } |
| 445 | } |
| 446 | MP_DROP(z); |
| 447 | m = s[0].m; |
| 448 | } |
| 449 | } else { |
| 450 | unsigned i; |
| 451 | for (i = 0; i < sp; i++) |
| 452 | MP_DROP(s[i].m); |
| 453 | } |
| 454 | |
| 455 | /* --- Clear the radix power list --- */ |
| 456 | |
| 457 | { |
| 458 | unsigned i; |
| 459 | for (i = 1; i < pows; i++) |
| 460 | MP_DROP(pow[i]); |
| 461 | } |
| 462 | |
| 463 | /* --- Bail out if the number was bad --- */ |
| 464 | |
| 465 | done: |
| 466 | if (!(f & f_ok)) |
| 467 | return (0); |
| 468 | |
| 469 | /* --- Set the sign and return --- */ |
| 470 | |
| 471 | if (f & f_neg) |
| 472 | m->f |= MP_NEG; |
| 473 | return (m); |
| 474 | |
| 475 | #undef f_start |
| 476 | #undef f_neg |
| 477 | #undef f_ok |
| 478 | } |
| 479 | |
| 480 | /* --- @mp_write@ --- * |
| 481 | * |
| 482 | * Arguments: @mp *m@ = pointer to a multi-precision integer |
| 483 | * @int radix@ = radix to use when writing the number out |
| 484 | * @const mptext_ops *ops@ = pointer to an operations block |
| 485 | * @void *p@ = data for the operations block |
| 486 | * |
| 487 | * Returns: Zero if it worked, nonzero otherwise. |
| 488 | * |
| 489 | * Use: Writes a large integer in textual form. |
| 490 | */ |
| 491 | |
| 492 | /* --- Simple case --- * |
| 493 | * |
| 494 | * Use a fixed-sized buffer and single-precision arithmetic to pick off |
| 495 | * low-order digits. Put each digit in a buffer, working backwards from the |
| 496 | * end. If the buffer becomes full, recurse to get another one. Ensure that |
| 497 | * there are at least @z@ digits by writing leading zeroes if there aren't |
| 498 | * enough real digits. |
| 499 | */ |
| 500 | |
| 501 | static int simple(mpw n, int radix, unsigned z, |
| 502 | const mptext_ops *ops, void *p) |
| 503 | { |
| 504 | int rc = 0; |
| 505 | char buf[64]; |
| 506 | unsigned i = sizeof(buf); |
| 507 | int rd = radix > 0 ? radix : -radix; |
| 508 | |
| 509 | do { |
| 510 | int ch; |
| 511 | mpw x; |
| 512 | |
| 513 | x = n % rd; |
| 514 | n /= rd; |
| 515 | if (radix < 0) |
| 516 | ch = x; |
| 517 | else if (x < 10) |
| 518 | ch = '0' + x; |
| 519 | else |
| 520 | ch = 'a' + x - 10; |
| 521 | buf[--i] = ch; |
| 522 | if (z) |
| 523 | z--; |
| 524 | } while (i && n); |
| 525 | |
| 526 | if (n) |
| 527 | rc = simple(n, radix, z, ops, p); |
| 528 | else { |
| 529 | char zbuf[32]; |
| 530 | memset(zbuf, (radix < 0) ? 0 : '0', sizeof(zbuf)); |
| 531 | while (!rc && z >= sizeof(zbuf)) { |
| 532 | rc = ops->put(zbuf, sizeof(zbuf), p); |
| 533 | z -= sizeof(zbuf); |
| 534 | } |
| 535 | if (!rc && z) |
| 536 | rc = ops->put(zbuf, z, p); |
| 537 | } |
| 538 | if (!rc) |
| 539 | rc = ops->put(buf + i, sizeof(buf) - i, p); |
| 540 | BURN(buf); |
| 541 | return (rc); |
| 542 | } |
| 543 | |
| 544 | /* --- Complicated case --- * |
| 545 | * |
| 546 | * If the number is small, fall back to the simple case above. Otherwise |
| 547 | * divide and take remainder by current large power of the radix, and emit |
| 548 | * each separately. Don't emit a zero quotient. Be very careful about |
| 549 | * leading zeroes on the remainder part, because they're deeply significant. |
| 550 | */ |
| 551 | |
| 552 | static int complicated(mp *m, int radix, mp **pr, unsigned i, unsigned z, |
| 553 | const mptext_ops *ops, void *p) |
| 554 | { |
| 555 | int rc = 0; |
| 556 | mp *q = MP_NEW; |
| 557 | unsigned d = 1 << i; |
| 558 | |
| 559 | if (MP_LEN(m) < 2) |
| 560 | return (simple(MP_LEN(m) ? m->v[0] : 0, radix, z, ops, p)); |
| 561 | |
| 562 | assert(i); |
| 563 | mp_div(&q, &m, m, pr[i]); |
| 564 | if (!MP_LEN(q)) |
| 565 | d = z; |
| 566 | else { |
| 567 | if (z > d) |
| 568 | z -= d; |
| 569 | else |
| 570 | z = 0; |
| 571 | rc = complicated(q, radix, pr, i - 1, z, ops, p); |
| 572 | } |
| 573 | if (!rc) |
| 574 | rc = complicated(m, radix, pr, i - 1, d, ops, p); |
| 575 | mp_drop(q); |
| 576 | return (rc); |
| 577 | } |
| 578 | |
| 579 | /* --- Binary case --- * |
| 580 | * |
| 581 | * Special case for binary output. Goes much faster. |
| 582 | */ |
| 583 | |
| 584 | static int binary(mp *m, int bit, int radix, const mptext_ops *ops, void *p) |
| 585 | { |
| 586 | mpw *v; |
| 587 | mpw a; |
| 588 | int rc = 0; |
| 589 | unsigned b; |
| 590 | unsigned mask; |
| 591 | unsigned long n; |
| 592 | unsigned f = 0; |
| 593 | char buf[8], *q; |
| 594 | unsigned x; |
| 595 | int ch; |
| 596 | |
| 597 | #define f_out 1u |
| 598 | |
| 599 | /* --- Work out where to start --- */ |
| 600 | |
| 601 | n = mp_bits(m); |
| 602 | n += bit - (n % bit); |
| 603 | b = n % MPW_BITS; |
| 604 | n /= MPW_BITS; |
| 605 | |
| 606 | if (n > MP_LEN(m)) { |
| 607 | n--; |
| 608 | b += MPW_BITS; |
| 609 | } |
| 610 | |
| 611 | v = m->v + n; |
| 612 | a = *v; |
| 613 | mask = (1 << bit) - 1; |
| 614 | q = buf; |
| 615 | |
| 616 | /* --- Main code --- */ |
| 617 | |
| 618 | for (;;) { |
| 619 | if (b > bit) { |
| 620 | b -= bit; |
| 621 | x = a >> b; |
| 622 | } else { |
| 623 | x = a << (bit - b); |
| 624 | b += MPW_BITS - bit; |
| 625 | if (v == m->v) |
| 626 | break; |
| 627 | a = *--v; |
| 628 | if (b < MPW_BITS) |
| 629 | x |= a >> b; |
| 630 | } |
| 631 | x &= mask; |
| 632 | if (!x && !(f & f_out)) |
| 633 | continue; |
| 634 | |
| 635 | if (radix < 0) |
| 636 | ch = x; |
| 637 | else if (x < 10) |
| 638 | ch = '0' + x; |
| 639 | else |
| 640 | ch = 'a' + x - 10; |
| 641 | *q++ = ch; |
| 642 | if (q >= buf + sizeof(buf)) { |
| 643 | if ((rc = ops->put(buf, sizeof(buf), p)) != 0) |
| 644 | goto done; |
| 645 | q = buf; |
| 646 | } |
| 647 | f |= f_out; |
| 648 | } |
| 649 | |
| 650 | x &= mask; |
| 651 | if (radix < 0) |
| 652 | ch = x; |
| 653 | else if (x < 10) |
| 654 | ch = '0' + x; |
| 655 | else |
| 656 | ch = 'a' + x - 10; |
| 657 | *q++ = ch; |
| 658 | rc = ops->put(buf, q - buf, p); |
| 659 | |
| 660 | done: |
| 661 | mp_drop(m); |
| 662 | return (rc); |
| 663 | |
| 664 | #undef f_out |
| 665 | } |
| 666 | |
| 667 | /* --- Main driver code --- */ |
| 668 | |
| 669 | int mp_write(mp *m, int radix, const mptext_ops *ops, void *p) |
| 670 | { |
| 671 | int rc; |
| 672 | |
| 673 | /* --- Set various things up --- */ |
| 674 | |
| 675 | m = MP_COPY(m); |
| 676 | MP_SPLIT(m); |
| 677 | |
| 678 | /* --- Check the radix for sensibleness --- */ |
| 679 | |
| 680 | if (radix > 0) |
| 681 | assert(((void)"ascii radix must be <= 36", radix <= 36)); |
| 682 | else if (radix < 0) |
| 683 | assert(((void)"binary radix must fit in a byte", -radix < UCHAR_MAX)); |
| 684 | else |
| 685 | assert(((void)"radix can't be zero in mp_write", 0)); |
| 686 | |
| 687 | /* --- If the number is negative, sort that out --- */ |
| 688 | |
| 689 | if (m->f & MP_NEG) { |
| 690 | if (ops->put("-", 1, p)) |
| 691 | return (EOF); |
| 692 | m->f &= ~MP_NEG; |
| 693 | } |
| 694 | |
| 695 | /* --- Handle binary radix --- */ |
| 696 | |
| 697 | switch (radix) { |
| 698 | case 2: case -2: return (binary(m, 1, radix, ops, p)); |
| 699 | case 4: case -4: return (binary(m, 2, radix, ops, p)); |
| 700 | case 8: case -8: return (binary(m, 3, radix, ops, p)); |
| 701 | case 16: case -16: return (binary(m, 4, radix, ops, p)); |
| 702 | case 32: case -32: return (binary(m, 5, radix, ops, p)); |
| 703 | case -64: return (binary(m, 6, radix, ops, p)); |
| 704 | case -128: return (binary(m, 7, radix, ops, p)); |
| 705 | } |
| 706 | |
| 707 | /* --- If the number is small, do it the easy way --- */ |
| 708 | |
| 709 | if (MP_LEN(m) < 2) |
| 710 | rc = simple(MP_LEN(m) ? m->v[0] : 0, radix, 0, ops, p); |
| 711 | |
| 712 | /* --- Use a clever algorithm --- * |
| 713 | * |
| 714 | * Square the radix repeatedly, remembering old results, until I get |
| 715 | * something more than half the size of the number @m@. Use this to divide |
| 716 | * the number: the quotient and remainder will be approximately the same |
| 717 | * size, and I'll have split them on a digit boundary, so I can just emit |
| 718 | * the quotient and remainder recursively, in order. |
| 719 | */ |
| 720 | |
| 721 | else { |
| 722 | mp *pr[DEPTH]; |
| 723 | size_t target = (MP_LEN(m) + 1) / 2; |
| 724 | unsigned i = 0; |
| 725 | mp *z = mp_new(1, 0); |
| 726 | |
| 727 | /* --- Set up the exponent table --- */ |
| 728 | |
| 729 | z->v[0] = (radix > 0 ? radix : -radix); |
| 730 | z->f = 0; |
| 731 | for (;;) { |
| 732 | assert(((void)"Number is too unimaginably huge", i < DEPTH)); |
| 733 | pr[i++] = z; |
| 734 | if (MP_LEN(z) > target) |
| 735 | break; |
| 736 | z = mp_sqr(MP_NEW, z); |
| 737 | } |
| 738 | |
| 739 | /* --- Write out the answer --- */ |
| 740 | |
| 741 | rc = complicated(m, radix, pr, i - 1, 0, ops, p); |
| 742 | |
| 743 | /* --- Tidy away the array --- */ |
| 744 | |
| 745 | while (i > 0) |
| 746 | mp_drop(pr[--i]); |
| 747 | } |
| 748 | |
| 749 | /* --- Tidying up code --- */ |
| 750 | |
| 751 | MP_DROP(m); |
| 752 | return (rc); |
| 753 | } |
| 754 | |
| 755 | /*----- Test rig ----------------------------------------------------------*/ |
| 756 | |
| 757 | #ifdef TEST_RIG |
| 758 | |
| 759 | #include <mLib/testrig.h> |
| 760 | |
| 761 | static int verify(dstr *v) |
| 762 | { |
| 763 | int ok = 1; |
| 764 | int ib = *(int *)v[0].buf, ob = *(int *)v[2].buf; |
| 765 | dstr d = DSTR_INIT; |
| 766 | mp *m = mp_readdstr(MP_NEW, &v[1], 0, ib); |
| 767 | if (m) { |
| 768 | if (!ob) { |
| 769 | fprintf(stderr, "*** unexpected successful parse\n" |
| 770 | "*** input [%2i] = ", ib); |
| 771 | if (ib < 0) |
| 772 | type_hex.dump(&v[1], stderr); |
| 773 | else |
| 774 | fputs(v[1].buf, stderr); |
| 775 | mp_writedstr(m, &d, 10); |
| 776 | fprintf(stderr, "\n*** (value = %s)\n", d.buf); |
| 777 | ok = 0; |
| 778 | } else { |
| 779 | mp_writedstr(m, &d, ob); |
| 780 | if (d.len != v[3].len || memcmp(d.buf, v[3].buf, d.len) != 0) { |
| 781 | fprintf(stderr, "*** failed read or write\n" |
| 782 | "*** input [%2i] = ", ib); |
| 783 | if (ib < 0) |
| 784 | type_hex.dump(&v[1], stderr); |
| 785 | else |
| 786 | fputs(v[1].buf, stderr); |
| 787 | fprintf(stderr, "\n*** output [%2i] = ", ob); |
| 788 | if (ob < 0) |
| 789 | type_hex.dump(&d, stderr); |
| 790 | else |
| 791 | fputs(d.buf, stderr); |
| 792 | fprintf(stderr, "\n*** expected [%2i] = ", ob); |
| 793 | if (ob < 0) |
| 794 | type_hex.dump(&v[3], stderr); |
| 795 | else |
| 796 | fputs(v[3].buf, stderr); |
| 797 | fputc('\n', stderr); |
| 798 | ok = 0; |
| 799 | } |
| 800 | } |
| 801 | mp_drop(m); |
| 802 | } else { |
| 803 | if (ob) { |
| 804 | fprintf(stderr, "*** unexpected parse failure\n" |
| 805 | "*** input [%i] = ", ib); |
| 806 | if (ib < 0) |
| 807 | type_hex.dump(&v[1], stderr); |
| 808 | else |
| 809 | fputs(v[1].buf, stderr); |
| 810 | fprintf(stderr, "\n*** expected [%i] = ", ob); |
| 811 | if (ob < 0) |
| 812 | type_hex.dump(&v[3], stderr); |
| 813 | else |
| 814 | fputs(v[3].buf, stderr); |
| 815 | fputc('\n', stderr); |
| 816 | ok = 0; |
| 817 | } |
| 818 | } |
| 819 | |
| 820 | dstr_destroy(&d); |
| 821 | assert(mparena_count(MPARENA_GLOBAL) == 0); |
| 822 | return (ok); |
| 823 | } |
| 824 | |
| 825 | static test_chunk tests[] = { |
| 826 | { "mptext-ascii", verify, |
| 827 | { &type_int, &type_string, &type_int, &type_string, 0 } }, |
| 828 | { "mptext-bin-in", verify, |
| 829 | { &type_int, &type_hex, &type_int, &type_string, 0 } }, |
| 830 | { "mptext-bin-out", verify, |
| 831 | { &type_int, &type_string, &type_int, &type_hex, 0 } }, |
| 832 | { 0, 0, { 0 } } |
| 833 | }; |
| 834 | |
| 835 | int main(int argc, char *argv[]) |
| 836 | { |
| 837 | sub_init(); |
| 838 | test_run(argc, argv, tests, SRCDIR "/tests/mptext"); |
| 839 | return (0); |
| 840 | } |
| 841 | |
| 842 | #endif |
| 843 | |
| 844 | /*----- That's all, folks -------------------------------------------------*/ |