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