Asymptotically fast conversion of an 'int' to a decimal string.
(n)
| 176 | return result |
| 177 | |
| 178 | def int_to_decimal_string(n): |
| 179 | """Asymptotically fast conversion of an 'int' to a decimal string.""" |
| 180 | w = n.bit_length() |
| 181 | if w > 450_000 and _decimal is not None: |
| 182 | # It is only usable with the C decimal implementation. |
| 183 | # _pydecimal.py calls str() on very large integers, which in its |
| 184 | # turn calls int_to_decimal_string(), causing very deep recursion. |
| 185 | return str(int_to_decimal(n)) |
| 186 | |
| 187 | # Fallback algorithm for the case when the C decimal module isn't |
| 188 | # available. This algorithm is asymptotically worse than the algorithm |
| 189 | # using the decimal module, but better than the quadratic time |
| 190 | # implementation in longobject.c. |
| 191 | |
| 192 | DIGLIM = 1000 |
| 193 | def inner(n, w): |
| 194 | if w <= DIGLIM: |
| 195 | return str(n) |
| 196 | w2 = w >> 1 |
| 197 | hi, lo = divmod(n, pow10[w2]) |
| 198 | return inner(hi, w - w2) + inner(lo, w2).zfill(w2) |
| 199 | |
| 200 | # The estimation of the number of decimal digits. |
| 201 | # There is no harm in small error. If we guess too large, there may |
| 202 | # be leading 0's that need to be stripped. If we guess too small, we |
| 203 | # may need to call str() recursively for the remaining highest digits, |
| 204 | # which can still potentially be a large integer. This is manifested |
| 205 | # only if the number has way more than 10**15 digits, that exceeds |
| 206 | # the 52-bit physical address limit in both Intel64 and AMD64. |
| 207 | w = int(w * 0.3010299956639812 + 1) # log10(2) |
| 208 | pow10 = compute_powers(w, 5, DIGLIM) |
| 209 | for k, v in pow10.items(): |
| 210 | pow10[k] = v << k # 5**k << k == 5**k * 2**k == 10**k |
| 211 | if n < 0: |
| 212 | n = -n |
| 213 | sign = '-' |
| 214 | else: |
| 215 | sign = '' |
| 216 | s = inner(n, w) |
| 217 | if s[0] == '0' and n: |
| 218 | # If our guess of w is too large, there may be leading 0's that |
| 219 | # need to be stripped. |
| 220 | s = s.lstrip('0') |
| 221 | return sign + s |
| 222 | |
| 223 | def _str_to_int_inner(s): |
| 224 | """Asymptotically fast conversion of a 'str' to an 'int'.""" |
nothing calls this directly
no test coverage detected
searching dependent graphs…