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