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