@@ -582,52 +582,48 @@ double CPyTagged_TrueDivide(CPyTagged x, CPyTagged y) {
582582 return 1.0 ;
583583}
584584
585- // int.to_bytes(length, byteorder, signed=False)
586- PyObject * CPyTagged_ToBytes (CPyTagged self , Py_ssize_t length , PyObject * byteorder , int signed_flag ) {
587- PyObject * pyint = CPyTagged_AsObject (self );
588- if (!PyUnicode_Check (byteorder )) {
589- Py_DECREF (pyint );
590- PyErr_SetString (PyExc_TypeError , "byteorder must be str" );
591- return NULL ;
592- }
593- const char * order = PyUnicode_AsUTF8 (byteorder );
594- if (!order ) {
595- Py_DECREF (pyint );
596- return NULL ;
597- }
598- PyObject * result = CPyLong_ToBytes (pyint , length , order , signed_flag );
599- Py_DECREF (pyint );
600- return result ;
601- }
602-
603-
604585static PyObject * CPyLong_ToBytes (PyObject * v , Py_ssize_t length , const char * byteorder , int signed_flag ) {
605586 // This is a wrapper for PyLong_AsByteArray and PyBytes_FromStringAndSize
606- unsigned char * bytes = (unsigned char * )PyMem_Malloc (length );
607- if (!bytes ) {
608- PyErr_NoMemory ();
609- return NULL ;
610- }
611587 int little_endian ;
612588 if (strcmp (byteorder , "big" ) == 0 ) {
613589 little_endian = 0 ;
614590 } else if (strcmp (byteorder , "little" ) == 0 ) {
615591 little_endian = 1 ;
616592 } else {
617- PyMem_Free (bytes );
618593 PyErr_SetString (PyExc_ValueError , "byteorder must be either 'little' or 'big'" );
619594 return NULL ;
620595 }
596+ PyObject * result = PyBytes_FromStringAndSize (NULL , length );
597+ if (!result ) {
598+ return NULL ;
599+ }
600+ unsigned char * bytes = (unsigned char * )PyBytes_AS_STRING (result );
621601#if PY_VERSION_HEX >= 0x030D0000 // 3.13.0
622602 int res = _PyLong_AsByteArray ((PyLongObject * )v , bytes , length , little_endian , signed_flag , 1 );
623603#else
624604 int res = _PyLong_AsByteArray ((PyLongObject * )v , bytes , length , little_endian , signed_flag );
625605#endif
626606 if (res < 0 ) {
627- PyMem_Free (bytes );
607+ Py_DECREF (result );
608+ return NULL ;
609+ }
610+ return result ;
611+ }
612+
613+ // int.to_bytes(length, byteorder, signed=False)
614+ PyObject * CPyTagged_ToBytes (CPyTagged self , Py_ssize_t length , PyObject * byteorder , int signed_flag ) {
615+ PyObject * pyint = CPyTagged_AsObject (self );
616+ if (!PyUnicode_Check (byteorder )) {
617+ Py_DECREF (pyint );
618+ PyErr_SetString (PyExc_TypeError , "byteorder must be str" );
619+ return NULL ;
620+ }
621+ const char * order = PyUnicode_AsUTF8 (byteorder );
622+ if (!order ) {
623+ Py_DECREF (pyint );
628624 return NULL ;
629625 }
630- PyObject * result = PyBytes_FromStringAndSize (( const char * ) bytes , length );
631- PyMem_Free ( bytes );
626+ PyObject * result = CPyLong_ToBytes ( pyint , length , order , signed_flag );
627+ Py_DECREF ( pyint );
632628 return result ;
633629}
0 commit comments