@@ -164,6 +164,168 @@ template <size_t radix> using Custom = details::Fmt<radix>;
164
164
165
165
} // namespace radix
166
166
167
+ // Extract the low-order decimal digit from a value of integer type T. The
168
+ // returned value is the digit itself, from 0 to 9. The input value is passed
169
+ // by reference, and modified by dividing by 10, so that iterating this
170
+ // function extracts all the digits of the original number one at a time from
171
+ // low to high.
172
+ template <typename T, cpp::enable_if_t <cpp::is_integral_v<T>, int > = 0 >
173
+ LIBC_INLINE uint8_t extract_decimal_digit (T &value) {
174
+ const uint8_t digit (static_cast <uint8_t >(value % 10 ));
175
+ // For built-in integer types, we assume that an adequately fast division is
176
+ // available. If hardware division isn't implemented, then with a divisor
177
+ // known at compile time the compiler might be able to generate an optimized
178
+ // sequence instead.
179
+ value /= 10 ;
180
+ return digit;
181
+ }
182
+
183
+ // A specialization of extract_decimal_digit for the BigInt type in big_int.h,
184
+ // avoiding the use of general-purpose BigInt division which is very slow.
185
+ template <typename T, cpp::enable_if_t <is_big_int_v<T>, int > = 0 >
186
+ LIBC_INLINE uint8_t extract_decimal_digit (T &value) {
187
+ // There are two essential ways you can turn n into (n/10,n%10). One is
188
+ // ordinary integer division. The other is a modular-arithmetic approach in
189
+ // which you first compute n%10 by bit twiddling, then subtract it off to get
190
+ // a value that is definitely a multiple of 10. Then you divide that by 10 in
191
+ // two steps: shift right to divide off a factor of 2, and then divide off a
192
+ // factor of 5 by multiplying by the modular inverse of 5 mod 2^BITS. (That
193
+ // last step only works if you know there's no remainder, which is why you
194
+ // had to subtract off the output digit first.)
195
+ //
196
+ // Either approach can be made to work in linear time. This code uses the
197
+ // modular-arithmetic technique, because the other approach either does a lot
198
+ // of integer divisions (requiring a fast hardware divider), or else uses a
199
+ // "multiply by an approximation to the reciprocal" technique which depends
200
+ // on careful error analysis which might go wrong in an untested edge case.
201
+
202
+ using Word = typename T::word_type;
203
+
204
+ // Find the remainder (value % 10). We do this by breaking up the input
205
+ // integer into chunks of size WORD_SIZE/2, so that the sum of them doesn't
206
+ // overflow a Word. Then we sum all the half-words times 6, except the bottom
207
+ // one, which is added to that sum without scaling.
208
+ //
209
+ // Why 6? Because you can imagine that the original number had the form
210
+ //
211
+ // halfwords[0] + K*halfwords[1] + K^2*halfwords[2] + ...
212
+ //
213
+ // where K = 2^(WORD_SIZE/2). Since WORD_SIZE is expected to be a multiple of
214
+ // 8, that makes WORD_SIZE/2 a multiple of 4, so that K is a power of 16. And
215
+ // all powers of 16 (larger than 1) are congruent to 6 mod 10, by induction:
216
+ // 16 itself is, and 6^2=36 is also congruent to 6.
217
+ Word acc_remainder = 0 ;
218
+ const Word HALFWORD_BITS = T::WORD_SIZE / 2 ;
219
+ const Word HALFWORD_MASK = ((Word (1 ) << HALFWORD_BITS) - 1 );
220
+ // Sum both halves of all words except the low one.
221
+ for (size_t i = 1 ; i < T::WORD_COUNT; i++) {
222
+ acc_remainder += value.val [i] >> HALFWORD_BITS;
223
+ acc_remainder += value.val [i] & HALFWORD_MASK;
224
+ }
225
+ // Add the high half of the low word. Then we have everything that needs to
226
+ // be multiplied by 6, so do that.
227
+ acc_remainder += value.val [0 ] >> HALFWORD_BITS;
228
+ acc_remainder *= 6 ;
229
+ // Having multiplied it by 6, add the lowest half-word, and then reduce mod
230
+ // 10 by normal integer division to finish.
231
+ acc_remainder += value.val [0 ] & HALFWORD_MASK;
232
+ uint8_t digit = acc_remainder % 10 ;
233
+
234
+ // Now we have the output digit. Subtract it from the input value, and shift
235
+ // right to divide by 2.
236
+ value -= digit;
237
+ value >>= 1 ;
238
+
239
+ // Now all that's left is to multiply by the inverse of 5 mod 2^BITS. No
240
+ // matter what the value of BITS, the inverse of 5 has the very convenient
241
+ // form 0xCCCC...CCCD, with as many C hex digits in the middle as necessary.
242
+ //
243
+ // We could construct a second BigInt with all words 0xCCCCCCCCCCCCCCCC,
244
+ // increment the bottom word, and call a general-purpose multiply function.
245
+ // But we can do better, by taking advantage of the regularity: we can do
246
+ // this particular operation in linear time, whereas a general multiplier
247
+ // would take superlinear time (quadratic in small cases).
248
+ //
249
+ // To begin with, instead of computing n*0xCCCC...CCCD, we'll compute
250
+ // n*0xCCCC...CCCC and then add it to the original n. Then all the words of
251
+ // the multiplier have the same value 0xCCCCCCCCCCCCCCCC, which I'll just
252
+ // denote as C. If we also write t = 2^WORD_SIZE, and imagine (as an example)
253
+ // that the input number has three words x,y,z with x being the low word,
254
+ // then we're computing
255
+ //
256
+ // (x + y t + z t^2) * (C + C t + C t^2)
257
+ //
258
+ // = x C + y C t + z C t^2
259
+ // + x C t + y C t^2 + z C t^3
260
+ // + x C t^2 + y C t^3 + z C t^4
261
+ //
262
+ // but we're working mod t^3, so the high-order terms vanish and this becomes
263
+ //
264
+ // x C + y C t + z C t^2
265
+ // + x C t + y C t^2
266
+ // + x C t^2
267
+ //
268
+ // = x C + (x+y) C t + (x+y+z) C t^2
269
+ //
270
+ // So all you have to do is to work from the low word of the integer upwards,
271
+ // accumulating C times the sum of all the words you've seen so far to get
272
+ // x*C, (x+y)*C, (x+y+z)*C and so on. In each step you add another product to
273
+ // the accumulator, and add the accumulator to the corresponding word of the
274
+ // original number (so that we end up with value*CCCD, not just value*CCCC).
275
+ //
276
+ // If you do that literally, then your accumulator has to be three words
277
+ // wide, because the sum of words can overflow into a second word, and
278
+ // multiplying by C adds another word. But we can do slightly better by
279
+ // breaking each product word*C up into a bottom half and a top half. If we
280
+ // write x*C = xl + xh*t, and similarly for y and z, then our sum becomes
281
+ //
282
+ // (xl + xh t) + (yl + yh t) t + (zl + zh t) t^2
283
+ // + (xl + xh t) t + (yl + yh t) t^2
284
+ // + (xl + xh t) t^2
285
+ //
286
+ // and if you expand out again, collect terms, and discard t^3 terms, you get
287
+ //
288
+ // (xl)
289
+ // + (xl + xh + yl) t
290
+ // + (xl + xh + yl + yh + zl) t^2
291
+ //
292
+ // in which each coefficient is the sum of all the low words of the products
293
+ // up to _and including_ the current word, plus all the high words up to but
294
+ // _not_ including the current word. So now you only have to retain two words
295
+ // of sum instead of three.
296
+ //
297
+ // We do this entire procedure in a single in-place pass over the input
298
+ // number, reading each word to make its product with C and then adding the
299
+ // low word of the accumulator to it.
300
+ const Word C = (Word (0 ) - 1 ) / 5 * 4 ; // calculate 0xCCCC as 4/5 of 0xFFFF
301
+ Word acc_lo = 0 , acc_hi = 0 ; // accumulator of all the half-products so far
302
+ Word carry_bit, carry_word = 0 ;
303
+
304
+ for (size_t i = 0 ; i < T::WORD_COUNT; i++) {
305
+ // Make the two-word product of C with the current input word.
306
+ multiword::DoubleWide<Word> product = multiword::mul2 (C, value.val [i]);
307
+
308
+ // Add the low half of the product to our accumulator, but not yet the high
309
+ // half.
310
+ acc_lo = add_with_carry<Word>(acc_lo, product[0 ], 0 , carry_bit);
311
+ acc_hi += carry_bit;
312
+
313
+ // Now the accumulator contains exactly the value we need to add to the
314
+ // current input word. Add it, plus any carries from lower words, and make
315
+ // a new word of carry data to propagate into the next iteration.
316
+ value.val [i] = add_with_carry<Word>(value.val [i], carry_word, 0 , carry_bit);
317
+ carry_word = acc_hi + carry_bit;
318
+ value.val [i] = add_with_carry<Word>(value.val [i], acc_lo, 0 , carry_bit);
319
+ carry_word += carry_bit;
320
+
321
+ // Now add the high half of the current product to our accumulator.
322
+ acc_lo = add_with_carry<Word>(acc_lo, product[1 ], 0 , carry_bit);
323
+ acc_hi += carry_bit;
324
+ }
325
+
326
+ return digit;
327
+ }
328
+
167
329
// See file header for documentation.
168
330
template <typename T, typename Fmt = radix::Dec> class IntegerToString {
169
331
static_assert (cpp::is_integral_v<T> || is_big_int_v<T>);
@@ -229,6 +391,15 @@ template <typename T, typename Fmt = radix::Dec> class IntegerToString {
229
391
}
230
392
}
231
393
394
+ LIBC_INLINE static void
395
+ write_unsigned_number_dec (UNSIGNED_T value,
396
+ details::BackwardStringBufferWriter &sink) {
397
+ while (sink.ok () && value != 0 ) {
398
+ const uint8_t digit = extract_decimal_digit (value);
399
+ sink.push (digit_char (digit));
400
+ }
401
+ }
402
+
232
403
// Returns the absolute value of 'value' as 'UNSIGNED_T'.
233
404
LIBC_INLINE static UNSIGNED_T abs (T value) {
234
405
if (cpp::is_unsigned_v<T> || value >= 0 )
@@ -256,7 +427,7 @@ template <typename T, typename Fmt = radix::Dec> class IntegerToString {
256
427
LIBC_INLINE static void write (T value,
257
428
details::BackwardStringBufferWriter &sink) {
258
429
if constexpr (Fmt::BASE == 10 ) {
259
- write_unsigned_number (abs (value), sink);
430
+ write_unsigned_number_dec (abs (value), sink);
260
431
} else {
261
432
write_unsigned_number (static_cast <UNSIGNED_T>(value), sink);
262
433
}
0 commit comments