Skip to content

Commit 336e881

Browse files
committed
use temporary buffer of digits, tmp_digits
1 parent 3854262 commit 336e881

File tree

1 file changed

+14
-17
lines changed

1 file changed

+14
-17
lines changed

Modules/_decimal/_decimal.c

Lines changed: 14 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -3689,37 +3689,34 @@ dec_as_long(PyObject *dec, PyObject *context, int round)
36893689
assert(layout->digit_size == 2 || layout->digit_size == 4);
36903690

36913691
uint32_t base = (uint32_t)1 << layout->bits_per_digit;
3692-
size_t n, len = mpd_sizeinbase(x, base);
3693-
void *digits;
3694-
PyLongWriter *writer = PyLongWriter_Create(mpd_isnegative(x), len, &digits);
3695-
3696-
if (writer == NULL) {
3697-
mpd_del(x);
3698-
return NULL;
3699-
}
3692+
void *tmp_digits = NULL;
3693+
size_t n;
37003694

37013695
status = 0;
3702-
/* The mpd_qexport_*() functions used here assume that no resizing occurs,
3703-
that is, 'len' was obtained via mpd_sizeinbase(). We also fill 'digits'
3704-
with zeros first since 'len' can be overestimated. */
37053696
if (layout->digit_size == 4) {
3706-
memset(digits, 0, 4*len);
3707-
n = mpd_qexport_u32((uint32_t **)&digits, len, base, x, &status);
3697+
n = mpd_qexport_u32((uint32_t **)&tmp_digits, 0, base, x, &status);
37083698
}
37093699
else {
3710-
memset(digits, 0, 2*len);
3711-
n = mpd_qexport_u16((uint16_t **)&digits, len, base, x, &status);
3700+
n = mpd_qexport_u16((uint16_t **)&tmp_digits, 0, base, x, &status);
37123701
}
37133702

37143703
if (n == SIZE_MAX) {
37153704
PyErr_NoMemory();
3716-
PyLongWriter_Discard(writer);
37173705
mpd_del(x);
3706+
mpd_free(tmp_digits);
37183707
return NULL;
37193708
}
37203709

3721-
assert(n <= len);
3710+
void *digits;
3711+
PyLongWriter *writer = PyLongWriter_Create(mpd_isnegative(x), n, &digits);
3712+
37223713
mpd_del(x);
3714+
if (writer == NULL) {
3715+
mpd_free(tmp_digits);
3716+
return NULL;
3717+
}
3718+
memcpy(digits, tmp_digits, layout->digit_size*n);
3719+
mpd_free(tmp_digits);
37233720
return PyLongWriter_Finish(writer);
37243721
}
37253722

0 commit comments

Comments
 (0)