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