blob: e8198492c63e545ff9b8bf931b3c25ee30e14b4f [file] [log] [blame]
Guido van Rossume15dee51995-07-18 14:12:02 +00001/* Abstract Object Interface (many thanks to Jim Fulton) */
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002
Guido van Rossume15dee51995-07-18 14:12:02 +00003#include "Python.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02004#include "pycore_abstract.h" // _PyIndex_Check()
5#include "pycore_ceval.h" // _Py_EnterRecursiveCall()
Victor Stinnerbe434dc2019-11-05 00:51:22 +01006#include "pycore_pyerrors.h"
Victor Stinner4a21e572020-04-15 02:35:41 +02007#include "pycore_pystate.h" // _PyThreadState_GET()
Guido van Rossumfa0b6ab1998-05-22 15:23:36 +00008#include <ctype.h>
Victor Stinner4a21e572020-04-15 02:35:41 +02009#include <stddef.h> // offsetof()
Tim Peters64b5ce32001-09-10 20:52:51 +000010#include "longintrepr.h"
Neil Schemenauer5a1f0152001-01-04 01:39:06 +000011
Thomas Wouters49fd7fa2006-04-21 10:40:58 +000012
Thomas Wouters00ee7ba2006-08-21 19:07:27 +000013
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000014/* Shorthands to return certain errors */
Guido van Rossume15dee51995-07-18 14:12:02 +000015
16static PyObject *
Thomas Wouters0e3f5912006-08-11 14:57:12 +000017type_error(const char *msg, PyObject *obj)
Guido van Rossume15dee51995-07-18 14:12:02 +000018{
Victor Stinner0d76d2b2020-02-07 01:53:23 +010019 PyErr_Format(PyExc_TypeError, msg, Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000020 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000021}
22
Guido van Rossum052b7e11996-11-11 15:08:19 +000023static PyObject *
Fred Drake79912472000-07-09 04:06:11 +000024null_error(void)
Guido van Rossume15dee51995-07-18 14:12:02 +000025{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000026 if (!PyErr_Occurred())
27 PyErr_SetString(PyExc_SystemError,
28 "null argument to internal routine");
29 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +000030}
31
Guido van Rossumcea1c8c1998-05-22 00:47:05 +000032/* Operations on any object */
33
Guido van Rossume15dee51995-07-18 14:12:02 +000034PyObject *
Fred Drake79912472000-07-09 04:06:11 +000035PyObject_Type(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000036{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000037 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +000038
Victor Stinner71aea8e2016-08-19 16:59:55 +020039 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000040 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +020041 }
42
Victor Stinner0d76d2b2020-02-07 01:53:23 +010043 v = (PyObject *)Py_TYPE(o);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000044 Py_INCREF(v);
45 return v;
Guido van Rossume15dee51995-07-18 14:12:02 +000046}
47
Martin v. Löwis18e16552006-02-15 17:27:45 +000048Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +000049PyObject_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +000050{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000051 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +000052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000053 if (o == NULL) {
54 null_error();
55 return -1;
56 }
Guido van Rossume15dee51995-07-18 14:12:02 +000057
Victor Stinner0d76d2b2020-02-07 01:53:23 +010058 m = Py_TYPE(o)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +030059 if (m && m->sq_length) {
60 Py_ssize_t len = m->sq_length(o);
61 assert(len >= 0 || PyErr_Occurred());
62 return len;
63 }
Guido van Rossume15dee51995-07-18 14:12:02 +000064
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000065 return PyMapping_Size(o);
Guido van Rossume15dee51995-07-18 14:12:02 +000066}
67
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000068#undef PyObject_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +000069Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000070PyObject_Length(PyObject *o)
71{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +000072 return PyObject_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +000073}
74#define PyObject_Length PyObject_Size
75
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020076int
77_PyObject_HasLen(PyObject *o) {
78 return (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) ||
79 (Py_TYPE(o)->tp_as_mapping && Py_TYPE(o)->tp_as_mapping->mp_length);
80}
Raymond Hettinger6b27cda2005-09-24 21:23:05 +000081
Christian Heimes255f53b2007-12-08 15:33:56 +000082/* The length hint function returns a non-negative value from o.__len__()
Armin Ronacher74b38b12012-10-07 10:29:32 +020083 or o.__length_hint__(). If those methods aren't found the defaultvalue is
84 returned. If one of the calls fails with an exception other than TypeError
85 this function returns -1.
Christian Heimes255f53b2007-12-08 15:33:56 +000086*/
87
88Py_ssize_t
Armin Ronacheraa9a79d2012-10-06 14:03:24 +020089PyObject_LengthHint(PyObject *o, Py_ssize_t defaultvalue)
Christian Heimes255f53b2007-12-08 15:33:56 +000090{
Christian Heimesb70e8a12012-10-06 17:16:39 +020091 PyObject *hint, *result;
Christian Heimes6314d162012-10-06 17:13:29 +020092 Py_ssize_t res;
Benjamin Petersonce798522012-01-22 11:24:29 -050093 _Py_IDENTIFIER(__length_hint__);
Serhiy Storchakaf740d462013-10-24 23:19:51 +030094 if (_PyObject_HasLen(o)) {
95 res = PyObject_Length(o);
Serhiy Storchaka813f9432017-04-16 09:21:44 +030096 if (res < 0) {
97 assert(PyErr_Occurred());
Serhiy Storchakaf740d462013-10-24 23:19:51 +030098 if (!PyErr_ExceptionMatches(PyExc_TypeError)) {
99 return -1;
100 }
101 PyErr_Clear();
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200102 }
Serhiy Storchakaf740d462013-10-24 23:19:51 +0300103 else {
104 return res;
105 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000106 }
Christian Heimes6314d162012-10-06 17:13:29 +0200107 hint = _PyObject_LookupSpecial(o, &PyId___length_hint__);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200108 if (hint == NULL) {
109 if (PyErr_Occurred()) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000110 return -1;
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200111 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000112 return defaultvalue;
113 }
Victor Stinnerf17c3de2016-12-06 18:46:19 +0100114 result = _PyObject_CallNoArg(hint);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200115 Py_DECREF(hint);
116 if (result == NULL) {
117 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
118 PyErr_Clear();
119 return defaultvalue;
120 }
121 return -1;
122 }
123 else if (result == Py_NotImplemented) {
124 Py_DECREF(result);
125 return defaultvalue;
126 }
127 if (!PyLong_Check(result)) {
Armin Ronacher74b38b12012-10-07 10:29:32 +0200128 PyErr_Format(PyExc_TypeError, "__length_hint__ must be an integer, not %.100s",
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200129 Py_TYPE(result)->tp_name);
130 Py_DECREF(result);
131 return -1;
132 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200133 res = PyLong_AsSsize_t(result);
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200134 Py_DECREF(result);
Armin Ronacher74b38b12012-10-07 10:29:32 +0200135 if (res < 0 && PyErr_Occurred()) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200136 return -1;
137 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200138 if (res < 0) {
Armin Ronacheraa9a79d2012-10-06 14:03:24 +0200139 PyErr_Format(PyExc_ValueError, "__length_hint__() should return >= 0");
140 return -1;
141 }
Armin Ronacher74b38b12012-10-07 10:29:32 +0200142 return res;
Raymond Hettinger6b27cda2005-09-24 21:23:05 +0000143}
144
Guido van Rossume15dee51995-07-18 14:12:02 +0000145PyObject *
Fred Drake79912472000-07-09 04:06:11 +0000146PyObject_GetItem(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +0000147{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000148 PyMappingMethods *m;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000149 PySequenceMethods *ms;
Guido van Rossume15dee51995-07-18 14:12:02 +0000150
Victor Stinner71aea8e2016-08-19 16:59:55 +0200151 if (o == NULL || key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000152 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +0200153 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000154
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100155 m = Py_TYPE(o)->tp_as_mapping;
Victor Stinnere20310f2015-11-05 13:56:58 +0100156 if (m && m->mp_subscript) {
157 PyObject *item = m->mp_subscript(o, key);
158 assert((item != NULL) ^ (PyErr_Occurred() != NULL));
159 return item;
160 }
Guido van Rossume15dee51995-07-18 14:12:02 +0000161
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100162 ms = Py_TYPE(o)->tp_as_sequence;
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000163 if (ms && ms->sq_item) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200164 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000165 Py_ssize_t key_value;
166 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
167 if (key_value == -1 && PyErr_Occurred())
168 return NULL;
169 return PySequence_GetItem(o, key_value);
170 }
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000171 else {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000172 return type_error("sequence index must "
173 "be integer, not '%.200s'", key);
Ivan Levkivskyiac281472019-02-17 23:13:46 +0000174 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000175 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000176
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100177 if (PyType_Check(o)) {
Jeroen Demeyer196a5302019-07-04 12:31:34 +0200178 PyObject *meth, *result;
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100179 _Py_IDENTIFIER(__class_getitem__);
Victor Stinnera15e2602020-04-08 02:01:56 +0200180
Guido van Rossum48b069a2020-04-07 09:50:06 -0700181 // Special case type[int], but disallow other types so str[int] fails
182 if ((PyTypeObject*)o == &PyType_Type) {
183 return Py_GenericAlias(o, key);
184 }
185
Serhiy Storchakaf320be72018-01-25 10:49:40 +0200186 if (_PyObject_LookupAttrId(o, &PyId___class_getitem__, &meth) < 0) {
187 return NULL;
188 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100189 if (meth) {
Petr Viktorinffd97532020-02-11 17:46:57 +0100190 result = PyObject_CallOneArg(meth, key);
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100191 Py_DECREF(meth);
192 return result;
193 }
Ivan Levkivskyi2b5fd1e2017-12-14 23:32:56 +0100194 }
195
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000196 return type_error("'%.200s' object is not subscriptable", o);
Guido van Rossume15dee51995-07-18 14:12:02 +0000197}
198
199int
Fred Drake79912472000-07-09 04:06:11 +0000200PyObject_SetItem(PyObject *o, PyObject *key, PyObject *value)
Guido van Rossume15dee51995-07-18 14:12:02 +0000201{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000202 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +0000203
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000204 if (o == NULL || key == NULL || value == NULL) {
205 null_error();
206 return -1;
207 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100208 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000209 if (m && m->mp_ass_subscript)
210 return m->mp_ass_subscript(o, key, value);
Guido van Rossume15dee51995-07-18 14:12:02 +0000211
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100212 if (Py_TYPE(o)->tp_as_sequence) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200213 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000214 Py_ssize_t key_value;
215 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
216 if (key_value == -1 && PyErr_Occurred())
217 return -1;
218 return PySequence_SetItem(o, key_value, value);
219 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100220 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000221 type_error("sequence index must be "
222 "integer, not '%.200s'", key);
223 return -1;
224 }
225 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000226
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000227 type_error("'%.200s' object does not support item assignment", o);
228 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +0000229}
230
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000231int
Fred Drake79912472000-07-09 04:06:11 +0000232PyObject_DelItem(PyObject *o, PyObject *key)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000233{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000234 PyMappingMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000235
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000236 if (o == NULL || key == NULL) {
237 null_error();
238 return -1;
239 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100240 m = Py_TYPE(o)->tp_as_mapping;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000241 if (m && m->mp_ass_subscript)
242 return m->mp_ass_subscript(o, key, (PyObject*)NULL);
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000243
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100244 if (Py_TYPE(o)->tp_as_sequence) {
Victor Stinnera15e2602020-04-08 02:01:56 +0200245 if (_PyIndex_Check(key)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000246 Py_ssize_t key_value;
247 key_value = PyNumber_AsSsize_t(key, PyExc_IndexError);
248 if (key_value == -1 && PyErr_Occurred())
249 return -1;
250 return PySequence_DelItem(o, key_value);
251 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100252 else if (Py_TYPE(o)->tp_as_sequence->sq_ass_item) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000253 type_error("sequence index must be "
254 "integer, not '%.200s'", key);
255 return -1;
256 }
257 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000258
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000259 type_error("'%.200s' object does not support item deletion", o);
260 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +0000261}
262
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000263int
Serhiy Storchakac6792272013-10-19 21:03:34 +0300264PyObject_DelItemString(PyObject *o, const char *key)
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000266 PyObject *okey;
267 int ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000268
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000269 if (o == NULL || key == NULL) {
270 null_error();
271 return -1;
272 }
273 okey = PyUnicode_FromString(key);
274 if (okey == NULL)
275 return -1;
276 ret = PyObject_DelItem(o, okey);
277 Py_DECREF(okey);
278 return ret;
Martin v. Löwisb0d71d02002-01-05 10:50:30 +0000279}
280
Victor Stinneref5c6152020-04-08 01:13:53 +0200281
282/* Return 1 if the getbuffer function is available, otherwise return 0. */
283int
284PyObject_CheckBuffer(PyObject *obj)
285{
286 PyBufferProcs *tp_as_buffer = Py_TYPE(obj)->tp_as_buffer;
287 return (tp_as_buffer != NULL && tp_as_buffer->bf_getbuffer != NULL);
288}
289
290
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000291/* We release the buffer right after use of this function which could
Guido van Rossum98297ee2007-11-06 21:34:58 +0000292 cause issues later on. Don't use these functions in new code.
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000293 */
Thomas Wouters73e5a5b2006-06-08 15:35:45 +0000294int
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000295PyObject_CheckReadBuffer(PyObject *obj)
296{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100297 PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000298 Py_buffer view;
Jeremy Hylton89c3a222001-11-09 21:59:42 +0000299
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000300 if (pb == NULL ||
301 pb->bf_getbuffer == NULL)
302 return 0;
303 if ((*pb->bf_getbuffer)(obj, &view, PyBUF_SIMPLE) == -1) {
304 PyErr_Clear();
305 return 0;
306 }
307 PyBuffer_Release(&view);
308 return 1;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000309}
310
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200311static int
312as_read_buffer(PyObject *obj, const void **buffer, Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000313{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000314 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000315
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000316 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
317 null_error();
318 return -1;
319 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200320 if (PyObject_GetBuffer(obj, &view, PyBUF_SIMPLE) != 0)
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000321 return -1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000322
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000323 *buffer = view.buf;
324 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200325 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000326 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000327}
328
Serhiy Storchaka460bd0d2016-11-20 12:16:46 +0200329int
330PyObject_AsCharBuffer(PyObject *obj,
331 const char **buffer,
332 Py_ssize_t *buffer_len)
333{
334 return as_read_buffer(obj, (const void **)buffer, buffer_len);
335}
336
337int PyObject_AsReadBuffer(PyObject *obj,
338 const void **buffer,
339 Py_ssize_t *buffer_len)
340{
341 return as_read_buffer(obj, buffer, buffer_len);
342}
343
Guido van Rossum4c08d552000-03-10 22:55:18 +0000344int PyObject_AsWriteBuffer(PyObject *obj,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000345 void **buffer,
346 Py_ssize_t *buffer_len)
Guido van Rossum4c08d552000-03-10 22:55:18 +0000347{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000348 PyBufferProcs *pb;
349 Py_buffer view;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000350
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000351 if (obj == NULL || buffer == NULL || buffer_len == NULL) {
352 null_error();
353 return -1;
354 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100355 pb = Py_TYPE(obj)->tp_as_buffer;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000356 if (pb == NULL ||
357 pb->bf_getbuffer == NULL ||
358 ((*pb->bf_getbuffer)(obj, &view, PyBUF_WRITABLE) != 0)) {
359 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400360 "expected a writable bytes-like object");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000361 return -1;
362 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000363
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000364 *buffer = view.buf;
365 *buffer_len = view.len;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200366 PyBuffer_Release(&view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000367 return 0;
Guido van Rossum4c08d552000-03-10 22:55:18 +0000368}
369
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000370/* Buffer C-API for Python 3.0 */
371
372int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000373PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000374{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100375 PyBufferProcs *pb = Py_TYPE(obj)->tp_as_buffer;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200376
377 if (pb == NULL || pb->bf_getbuffer == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000378 PyErr_Format(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400379 "a bytes-like object is required, not '%.100s'",
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000380 Py_TYPE(obj)->tp_name);
381 return -1;
382 }
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200383 return (*pb->bf_getbuffer)(obj, view, flags);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000384}
385
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000386static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100387_IsFortranContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000388{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000389 Py_ssize_t sd, dim;
390 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000391
Stefan Krah363af442015-02-01 14:53:54 +0100392 /* 1) len = product(shape) * itemsize
393 2) itemsize > 0
394 3) len = 0 <==> exists i: shape[i] = 0 */
395 if (view->len == 0) return 1;
396 if (view->strides == NULL) { /* C-contiguous by definition */
397 /* Trivially F-contiguous */
398 if (view->ndim <= 1) return 1;
399
400 /* ndim > 1 implies shape != NULL */
401 assert(view->shape != NULL);
402
403 /* Effectively 1-d */
404 sd = 0;
405 for (i=0; i<view->ndim; i++) {
406 if (view->shape[i] > 1) sd += 1;
407 }
408 return sd <= 1;
409 }
410
411 /* strides != NULL implies both of these */
412 assert(view->ndim > 0);
413 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000414
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000415 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000416 for (i=0; i<view->ndim; i++) {
417 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100418 if (dim > 1 && view->strides[i] != sd) {
419 return 0;
420 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000421 sd *= dim;
422 }
423 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000424}
425
426static int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100427_IsCContiguous(const Py_buffer *view)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000428{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000429 Py_ssize_t sd, dim;
430 int i;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000431
Stefan Krah363af442015-02-01 14:53:54 +0100432 /* 1) len = product(shape) * itemsize
433 2) itemsize > 0
434 3) len = 0 <==> exists i: shape[i] = 0 */
435 if (view->len == 0) return 1;
436 if (view->strides == NULL) return 1; /* C-contiguous by definition */
437
438 /* strides != NULL implies both of these */
439 assert(view->ndim > 0);
440 assert(view->shape != NULL);
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000441
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000442 sd = view->itemsize;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000443 for (i=view->ndim-1; i>=0; i--) {
444 dim = view->shape[i];
Stefan Krah363af442015-02-01 14:53:54 +0100445 if (dim > 1 && view->strides[i] != sd) {
446 return 0;
447 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000448 sd *= dim;
449 }
450 return 1;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000451}
452
453int
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100454PyBuffer_IsContiguous(const Py_buffer *view, char order)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000455{
456
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000457 if (view->suboffsets != NULL) return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000458
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100459 if (order == 'C')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000460 return _IsCContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100461 else if (order == 'F')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000462 return _IsFortranContiguous(view);
Stefan Krah9a2d99e2012-02-25 12:24:21 +0100463 else if (order == 'A')
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000464 return (_IsCContiguous(view) || _IsFortranContiguous(view));
465 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000466}
467
468
Guido van Rossum98297ee2007-11-06 21:34:58 +0000469void*
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000470PyBuffer_GetPointer(Py_buffer *view, Py_ssize_t *indices)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000472 char* pointer;
473 int i;
474 pointer = (char *)view->buf;
475 for (i = 0; i < view->ndim; i++) {
476 pointer += view->strides[i]*indices[i];
477 if ((view->suboffsets != NULL) && (view->suboffsets[i] >= 0)) {
478 pointer = *((char**)pointer) + view->suboffsets[i];
479 }
480 }
481 return (void*)pointer;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000482}
483
484
Guido van Rossum98297ee2007-11-06 21:34:58 +0000485void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000486_Py_add_one_to_index_F(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000487{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000488 int k;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000489
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000490 for (k=0; k<nd; k++) {
491 if (index[k] < shape[k]-1) {
492 index[k]++;
493 break;
494 }
495 else {
496 index[k] = 0;
497 }
498 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000499}
500
Guido van Rossum98297ee2007-11-06 21:34:58 +0000501void
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000502_Py_add_one_to_index_C(int nd, Py_ssize_t *index, const Py_ssize_t *shape)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000503{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000504 int k;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000505
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000506 for (k=nd-1; k>=0; k--) {
507 if (index[k] < shape[k]-1) {
508 index[k]++;
509 break;
510 }
511 else {
512 index[k] = 0;
513 }
514 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000515}
516
Joannah Nanjekye9e66aba2019-08-20 11:46:36 -0300517Py_ssize_t
518PyBuffer_SizeFromFormat(const char *format)
519{
520 PyObject *structmodule = NULL;
521 PyObject *calcsize = NULL;
522 PyObject *res = NULL;
523 PyObject *fmt = NULL;
524 Py_ssize_t itemsize = -1;
525
526 structmodule = PyImport_ImportModule("struct");
527 if (structmodule == NULL) {
528 return itemsize;
529 }
530
531 calcsize = PyObject_GetAttrString(structmodule, "calcsize");
532 if (calcsize == NULL) {
533 goto done;
534 }
535
536 fmt = PyUnicode_FromString(format);
537 if (fmt == NULL) {
538 goto done;
539 }
540
541 res = PyObject_CallFunctionObjArgs(calcsize, fmt, NULL);
542 if (res == NULL) {
543 goto done;
544 }
545
546 itemsize = PyLong_AsSsize_t(res);
547 if (itemsize < 0) {
548 goto done;
549 }
550
551done:
552 Py_DECREF(structmodule);
553 Py_XDECREF(calcsize);
554 Py_XDECREF(fmt);
555 Py_XDECREF(res);
556 return itemsize;
557}
558
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000559int
Travis E. Oliphant8ae62b62007-09-23 02:00:13 +0000560PyBuffer_FromContiguous(Py_buffer *view, void *buf, Py_ssize_t len, char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000561{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000562 int k;
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000563 void (*addone)(int, Py_ssize_t *, const Py_ssize_t *);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000564 Py_ssize_t *indices, elements;
565 char *src, *ptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000566
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000567 if (len > view->len) {
568 len = view->len;
569 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000570
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000571 if (PyBuffer_IsContiguous(view, fort)) {
572 /* simplest copy is all that is needed */
573 memcpy(view->buf, buf, len);
574 return 0;
575 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000576
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000577 /* Otherwise a more elaborate scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000578
Stefan Krah7213fcc2015-02-01 16:19:23 +0100579 /* view->ndim <= 64 */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000580 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*(view->ndim));
581 if (indices == NULL) {
582 PyErr_NoMemory();
583 return -1;
584 }
585 for (k=0; k<view->ndim;k++) {
586 indices[k] = 0;
587 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000588
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000589 if (fort == 'F') {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000590 addone = _Py_add_one_to_index_F;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000591 }
592 else {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000593 addone = _Py_add_one_to_index_C;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000594 }
595 src = buf;
596 /* XXX : This is not going to be the fastest code in the world
597 several optimizations are possible.
598 */
599 elements = len / view->itemsize;
600 while (elements--) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000601 ptr = PyBuffer_GetPointer(view, indices);
602 memcpy(ptr, src, view->itemsize);
603 src += view->itemsize;
Stefan Krah7213fcc2015-02-01 16:19:23 +0100604 addone(view->ndim, indices, view->shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000605 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000606
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000607 PyMem_Free(indices);
608 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000609}
610
Guido van Rossum98297ee2007-11-06 21:34:58 +0000611int PyObject_CopyData(PyObject *dest, PyObject *src)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000612{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000613 Py_buffer view_dest, view_src;
614 int k;
615 Py_ssize_t *indices, elements;
616 char *dptr, *sptr;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000618 if (!PyObject_CheckBuffer(dest) ||
619 !PyObject_CheckBuffer(src)) {
620 PyErr_SetString(PyExc_TypeError,
R David Murray861470c2014-10-05 11:47:01 -0400621 "both destination and source must be "\
622 "bytes-like objects");
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000623 return -1;
624 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000626 if (PyObject_GetBuffer(dest, &view_dest, PyBUF_FULL) != 0) return -1;
627 if (PyObject_GetBuffer(src, &view_src, PyBUF_FULL_RO) != 0) {
628 PyBuffer_Release(&view_dest);
629 return -1;
630 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000631
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000632 if (view_dest.len < view_src.len) {
633 PyErr_SetString(PyExc_BufferError,
634 "destination is too small to receive data from source");
635 PyBuffer_Release(&view_dest);
636 PyBuffer_Release(&view_src);
637 return -1;
638 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000639
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000640 if ((PyBuffer_IsContiguous(&view_dest, 'C') &&
641 PyBuffer_IsContiguous(&view_src, 'C')) ||
642 (PyBuffer_IsContiguous(&view_dest, 'F') &&
643 PyBuffer_IsContiguous(&view_src, 'F'))) {
644 /* simplest copy is all that is needed */
645 memcpy(view_dest.buf, view_src.buf, view_src.len);
646 PyBuffer_Release(&view_dest);
647 PyBuffer_Release(&view_src);
648 return 0;
649 }
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000650
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000651 /* Otherwise a more elaborate copy scheme is needed */
Guido van Rossum98297ee2007-11-06 21:34:58 +0000652
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000653 /* XXX(nnorwitz): need to check for overflow! */
654 indices = (Py_ssize_t *)PyMem_Malloc(sizeof(Py_ssize_t)*view_src.ndim);
655 if (indices == NULL) {
656 PyErr_NoMemory();
657 PyBuffer_Release(&view_dest);
658 PyBuffer_Release(&view_src);
659 return -1;
660 }
661 for (k=0; k<view_src.ndim;k++) {
662 indices[k] = 0;
663 }
664 elements = 1;
665 for (k=0; k<view_src.ndim; k++) {
666 /* XXX(nnorwitz): can this overflow? */
667 elements *= view_src.shape[k];
668 }
669 while (elements--) {
Antoine Pitrouf68c2a72010-09-01 12:58:21 +0000670 _Py_add_one_to_index_C(view_src.ndim, indices, view_src.shape);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000671 dptr = PyBuffer_GetPointer(&view_dest, indices);
672 sptr = PyBuffer_GetPointer(&view_src, indices);
673 memcpy(dptr, sptr, view_src.itemsize);
674 }
675 PyMem_Free(indices);
676 PyBuffer_Release(&view_dest);
677 PyBuffer_Release(&view_src);
678 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000679}
680
681void
682PyBuffer_FillContiguousStrides(int nd, Py_ssize_t *shape,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000683 Py_ssize_t *strides, int itemsize,
684 char fort)
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000685{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000686 int k;
687 Py_ssize_t sd;
Guido van Rossum98297ee2007-11-06 21:34:58 +0000688
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000689 sd = itemsize;
690 if (fort == 'F') {
691 for (k=0; k<nd; k++) {
692 strides[k] = sd;
693 sd *= shape[k];
694 }
695 }
696 else {
697 for (k=nd-1; k>=0; k--) {
698 strides[k] = sd;
699 sd *= shape[k];
700 }
701 }
702 return;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000703}
704
705int
Martin v. Löwis423be952008-08-13 15:53:07 +0000706PyBuffer_FillInfo(Py_buffer *view, PyObject *obj, void *buf, Py_ssize_t len,
Stefan Krah4e141742012-03-06 15:27:31 +0100707 int readonly, int flags)
Guido van Rossum98297ee2007-11-06 21:34:58 +0000708{
Stefan Krah5178d912015-02-03 16:57:21 +0100709 if (view == NULL) {
710 PyErr_SetString(PyExc_BufferError,
711 "PyBuffer_FillInfo: view==NULL argument is obsolete");
712 return -1;
713 }
714
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000715 if (((flags & PyBUF_WRITABLE) == PyBUF_WRITABLE) &&
716 (readonly == 1)) {
717 PyErr_SetString(PyExc_BufferError,
718 "Object is not writable.");
719 return -1;
720 }
Guido van Rossum98297ee2007-11-06 21:34:58 +0000721
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000722 view->obj = obj;
723 if (obj)
724 Py_INCREF(obj);
725 view->buf = buf;
726 view->len = len;
727 view->readonly = readonly;
728 view->itemsize = 1;
729 view->format = NULL;
730 if ((flags & PyBUF_FORMAT) == PyBUF_FORMAT)
731 view->format = "B";
732 view->ndim = 1;
733 view->shape = NULL;
734 if ((flags & PyBUF_ND) == PyBUF_ND)
735 view->shape = &(view->len);
736 view->strides = NULL;
737 if ((flags & PyBUF_STRIDES) == PyBUF_STRIDES)
738 view->strides = &(view->itemsize);
739 view->suboffsets = NULL;
740 view->internal = NULL;
741 return 0;
Travis E. Oliphantb99f7622007-08-18 11:21:56 +0000742}
743
Martin v. Löwis423be952008-08-13 15:53:07 +0000744void
745PyBuffer_Release(Py_buffer *view)
746{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000747 PyObject *obj = view->obj;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200748 PyBufferProcs *pb;
749 if (obj == NULL)
750 return;
751 pb = Py_TYPE(obj)->tp_as_buffer;
752 if (pb && pb->bf_releasebuffer)
753 pb->bf_releasebuffer(obj, view);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000754 view->obj = NULL;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +0200755 Py_DECREF(obj);
Martin v. Löwis423be952008-08-13 15:53:07 +0000756}
757
Eric Smith8fd3eba2008-02-17 19:48:00 +0000758PyObject *
759PyObject_Format(PyObject *obj, PyObject *format_spec)
760{
Eric Smith8fd3eba2008-02-17 19:48:00 +0000761 PyObject *meth;
762 PyObject *empty = NULL;
763 PyObject *result = NULL;
Benjamin Petersonce798522012-01-22 11:24:29 -0500764 _Py_IDENTIFIER(__format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000765
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300766 if (format_spec != NULL && !PyUnicode_Check(format_spec)) {
767 PyErr_Format(PyExc_SystemError,
768 "Format specifier must be a string, not %.200s",
769 Py_TYPE(format_spec)->tp_name);
770 return NULL;
771 }
772
773 /* Fast path for common types. */
774 if (format_spec == NULL || PyUnicode_GET_LENGTH(format_spec) == 0) {
775 if (PyUnicode_CheckExact(obj)) {
776 Py_INCREF(obj);
777 return obj;
778 }
779 if (PyLong_CheckExact(obj)) {
780 return PyObject_Str(obj);
781 }
782 }
783
Eric Smith8fd3eba2008-02-17 19:48:00 +0000784 /* If no format_spec is provided, use an empty string */
785 if (format_spec == NULL) {
Victor Stinner9d3b93b2011-11-22 02:27:30 +0100786 empty = PyUnicode_New(0, 0);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000787 format_spec = empty;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000788 }
789
Serhiy Storchakaea525a22016-09-06 22:07:53 +0300790 /* Find the (unbound!) __format__ method */
Benjamin Petersonce798522012-01-22 11:24:29 -0500791 meth = _PyObject_LookupSpecial(obj, &PyId___format__);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000792 if (meth == NULL) {
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000793 if (!PyErr_Occurred())
794 PyErr_Format(PyExc_TypeError,
795 "Type %.100s doesn't define __format__",
796 Py_TYPE(obj)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000797 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000798 }
799
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000800 /* And call it. */
Petr Viktorinffd97532020-02-11 17:46:57 +0100801 result = PyObject_CallOneArg(meth, format_spec);
Benjamin Peterson6f889ad32010-06-05 02:11:45 +0000802 Py_DECREF(meth);
Eric Smith8fd3eba2008-02-17 19:48:00 +0000803
804 if (result && !PyUnicode_Check(result)) {
Ethan Furmanb95b5612015-01-23 20:05:18 -0800805 PyErr_Format(PyExc_TypeError,
806 "__format__ must return a str, not %.200s",
807 Py_TYPE(result)->tp_name);
Benjamin Petersonda2cf042010-06-05 00:45:37 +0000808 Py_DECREF(result);
809 result = NULL;
810 goto done;
Eric Smith8fd3eba2008-02-17 19:48:00 +0000811 }
812
813done:
814 Py_XDECREF(empty);
815 return result;
816}
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000817/* Operations on numbers */
818
819int
Fred Drake79912472000-07-09 04:06:11 +0000820PyNumber_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +0000821{
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100822 return o && Py_TYPE(o)->tp_as_number &&
823 (Py_TYPE(o)->tp_as_number->nb_index ||
824 Py_TYPE(o)->tp_as_number->nb_int ||
825 Py_TYPE(o)->tp_as_number->nb_float);
Guido van Rossume15dee51995-07-18 14:12:02 +0000826}
827
Guido van Rossumcea1c8c1998-05-22 00:47:05 +0000828/* Binary operators */
Guido van Rossume15dee51995-07-18 14:12:02 +0000829
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000830#define NB_SLOT(x) offsetof(PyNumberMethods, x)
831#define NB_BINOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000832 (*(binaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000833#define NB_TERNOP(nb_methods, slot) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000834 (*(ternaryfunc*)(& ((char*)nb_methods)[slot]))
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000835
836/*
837 Calling scheme used for binary operations:
838
Neal Norwitz4886cc32006-08-21 17:06:07 +0000839 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000840 w.op(v,w)[*], v.op(v,w), w.op(v,w)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000841
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100842 [*] only when Py_TYPE(v) != Py_TYPE(w) && Py_TYPE(w) is a subclass of
843 Py_TYPE(v)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000844 */
845
846static PyObject *
847binary_op1(PyObject *v, PyObject *w, const int op_slot)
Guido van Rossume15dee51995-07-18 14:12:02 +0000848{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000849 PyObject *x;
850 binaryfunc slotv = NULL;
851 binaryfunc slotw = NULL;
Guido van Rossum4bb1e362001-09-28 23:49:48 +0000852
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100853 if (Py_TYPE(v)->tp_as_number != NULL)
854 slotv = NB_BINOP(Py_TYPE(v)->tp_as_number, op_slot);
Andy Lester55728702020-03-06 16:53:17 -0600855 if (!Py_IS_TYPE(w, Py_TYPE(v)) &&
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100856 Py_TYPE(w)->tp_as_number != NULL) {
857 slotw = NB_BINOP(Py_TYPE(w)->tp_as_number, op_slot);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000858 if (slotw == slotv)
859 slotw = NULL;
860 }
861 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100862 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000863 x = slotw(v, w);
864 if (x != Py_NotImplemented)
865 return x;
866 Py_DECREF(x); /* can't do it */
867 slotw = NULL;
868 }
869 x = slotv(v, w);
870 if (x != Py_NotImplemented)
871 return x;
872 Py_DECREF(x); /* can't do it */
873 }
874 if (slotw) {
875 x = slotw(v, w);
876 if (x != Py_NotImplemented)
877 return x;
878 Py_DECREF(x); /* can't do it */
879 }
Brian Curtindfc80e32011-08-10 20:28:54 -0500880 Py_RETURN_NOTIMPLEMENTED;
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000881}
Guido van Rossum77660912002-04-16 16:32:50 +0000882
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000883static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000884binop_type_error(PyObject *v, PyObject *w, const char *op_name)
885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000886 PyErr_Format(PyExc_TypeError,
887 "unsupported operand type(s) for %.100s: "
888 "'%.100s' and '%.100s'",
889 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100890 Py_TYPE(v)->tp_name,
891 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000892 return NULL;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +0000893}
894
895static PyObject *
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000896binary_op(PyObject *v, PyObject *w, const int op_slot, const char *op_name)
897{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000898 PyObject *result = binary_op1(v, w, op_slot);
899 if (result == Py_NotImplemented) {
900 Py_DECREF(result);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530901
902 if (op_slot == NB_SLOT(nb_rshift) &&
scoder4c9ea092020-05-12 16:12:41 +0200903 PyCFunction_CheckExact(v) &&
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530904 strcmp(((PyCFunctionObject *)v)->m_ml->ml_name, "print") == 0)
905 {
906 PyErr_Format(PyExc_TypeError,
907 "unsupported operand type(s) for %.100s: "
908 "'%.100s' and '%.100s'. Did you mean \"print(<message>, "
Sanyam Khuranaa7c449b2017-08-18 17:48:14 +0530909 "file=<output_stream>)\"?",
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530910 op_name,
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100911 Py_TYPE(v)->tp_name,
912 Py_TYPE(w)->tp_name);
Sanyam Khurana5e2eb352017-08-18 16:07:36 +0530913 return NULL;
914 }
915
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000916 return binop_type_error(v, w, op_name);
917 }
918 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +0000919}
920
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000921
922/*
923 Calling scheme used for ternary operations:
924
Neal Norwitz4886cc32006-08-21 17:06:07 +0000925 Order operations are tried until either a valid result or error:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000926 v.op(v,w,z), w.op(v,w,z), z.op(v,w,z)
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000927 */
928
929static PyObject *
930ternary_op(PyObject *v,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000931 PyObject *w,
932 PyObject *z,
933 const int op_slot,
934 const char *op_name)
Guido van Rossume15dee51995-07-18 14:12:02 +0000935{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000936 PyNumberMethods *mv, *mw, *mz;
937 PyObject *x = NULL;
938 ternaryfunc slotv = NULL;
939 ternaryfunc slotw = NULL;
940 ternaryfunc slotz = NULL;
Guido van Rossum77660912002-04-16 16:32:50 +0000941
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100942 mv = Py_TYPE(v)->tp_as_number;
943 mw = Py_TYPE(w)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000944 if (mv != NULL)
945 slotv = NB_TERNOP(mv, op_slot);
Andy Lester55728702020-03-06 16:53:17 -0600946 if (!Py_IS_TYPE(w, Py_TYPE(v)) && mw != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000947 slotw = NB_TERNOP(mw, op_slot);
948 if (slotw == slotv)
949 slotw = NULL;
950 }
951 if (slotv) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100952 if (slotw && PyType_IsSubtype(Py_TYPE(w), Py_TYPE(v))) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000953 x = slotw(v, w, z);
954 if (x != Py_NotImplemented)
955 return x;
956 Py_DECREF(x); /* can't do it */
957 slotw = NULL;
958 }
959 x = slotv(v, w, z);
960 if (x != Py_NotImplemented)
961 return x;
962 Py_DECREF(x); /* can't do it */
963 }
964 if (slotw) {
965 x = slotw(v, w, z);
966 if (x != Py_NotImplemented)
967 return x;
968 Py_DECREF(x); /* can't do it */
969 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100970 mz = Py_TYPE(z)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000971 if (mz != NULL) {
972 slotz = NB_TERNOP(mz, op_slot);
973 if (slotz == slotv || slotz == slotw)
974 slotz = NULL;
975 if (slotz) {
976 x = slotz(v, w, z);
977 if (x != Py_NotImplemented)
978 return x;
979 Py_DECREF(x); /* can't do it */
980 }
981 }
Neil Schemenauer5a1f0152001-01-04 01:39:06 +0000982
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000983 if (z == Py_None)
984 PyErr_Format(
985 PyExc_TypeError,
986 "unsupported operand type(s) for ** or pow(): "
987 "'%.100s' and '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100988 Py_TYPE(v)->tp_name,
989 Py_TYPE(w)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000990 else
991 PyErr_Format(
992 PyExc_TypeError,
993 "unsupported operand type(s) for pow(): "
994 "'%.100s', '%.100s', '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +0100995 Py_TYPE(v)->tp_name,
996 Py_TYPE(w)->tp_name,
997 Py_TYPE(z)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +0000998 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +0000999}
1000
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001001#define BINARY_FUNC(func, op, op_name) \
1002 PyObject * \
1003 func(PyObject *v, PyObject *w) { \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001004 return binary_op(v, w, NB_SLOT(op), op_name); \
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001005 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001006
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001007BINARY_FUNC(PyNumber_Or, nb_or, "|")
1008BINARY_FUNC(PyNumber_Xor, nb_xor, "^")
1009BINARY_FUNC(PyNumber_And, nb_and, "&")
1010BINARY_FUNC(PyNumber_Lshift, nb_lshift, "<<")
1011BINARY_FUNC(PyNumber_Rshift, nb_rshift, ">>")
1012BINARY_FUNC(PyNumber_Subtract, nb_subtract, "-")
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001013BINARY_FUNC(PyNumber_Divmod, nb_divmod, "divmod()")
Guido van Rossume15dee51995-07-18 14:12:02 +00001014
1015PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001016PyNumber_Add(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001017{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001018 PyObject *result = binary_op1(v, w, NB_SLOT(nb_add));
1019 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001020 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001021 Py_DECREF(result);
1022 if (m && m->sq_concat) {
1023 return (*m->sq_concat)(v, w);
1024 }
1025 result = binop_type_error(v, w, "+");
1026 }
1027 return result;
Guido van Rossume15dee51995-07-18 14:12:02 +00001028}
1029
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001030static PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001031sequence_repeat(ssizeargfunc repeatfunc, PyObject *seq, PyObject *n)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001032{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001033 Py_ssize_t count;
Victor Stinnera15e2602020-04-08 02:01:56 +02001034 if (_PyIndex_Check(n)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001035 count = PyNumber_AsSsize_t(n, PyExc_OverflowError);
1036 if (count == -1 && PyErr_Occurred())
1037 return NULL;
1038 }
1039 else {
1040 return type_error("can't multiply sequence by "
1041 "non-int of type '%.200s'", n);
1042 }
1043 return (*repeatfunc)(seq, count);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001044}
1045
1046PyObject *
1047PyNumber_Multiply(PyObject *v, PyObject *w)
1048{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001049 PyObject *result = binary_op1(v, w, NB_SLOT(nb_multiply));
1050 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001051 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1052 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001053 Py_DECREF(result);
1054 if (mv && mv->sq_repeat) {
1055 return sequence_repeat(mv->sq_repeat, v, w);
1056 }
1057 else if (mw && mw->sq_repeat) {
1058 return sequence_repeat(mw->sq_repeat, w, v);
1059 }
1060 result = binop_type_error(v, w, "*");
1061 }
1062 return result;
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001063}
1064
Guido van Rossume15dee51995-07-18 14:12:02 +00001065PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001066PyNumber_MatrixMultiply(PyObject *v, PyObject *w)
1067{
1068 return binary_op(v, w, NB_SLOT(nb_matrix_multiply), "@");
1069}
1070
1071PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001072PyNumber_FloorDivide(PyObject *v, PyObject *w)
1073{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001074 return binary_op(v, w, NB_SLOT(nb_floor_divide), "//");
Guido van Rossum4668b002001-08-08 05:00:18 +00001075}
1076
1077PyObject *
1078PyNumber_TrueDivide(PyObject *v, PyObject *w)
1079{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001080 return binary_op(v, w, NB_SLOT(nb_true_divide), "/");
Guido van Rossum4668b002001-08-08 05:00:18 +00001081}
1082
1083PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001084PyNumber_Remainder(PyObject *v, PyObject *w)
Guido van Rossume15dee51995-07-18 14:12:02 +00001085{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001086 return binary_op(v, w, NB_SLOT(nb_remainder), "%");
Guido van Rossume15dee51995-07-18 14:12:02 +00001087}
1088
1089PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001090PyNumber_Power(PyObject *v, PyObject *w, PyObject *z)
Guido van Rossume15dee51995-07-18 14:12:02 +00001091{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001092 return ternary_op(v, w, z, NB_SLOT(nb_power), "** or pow()");
Guido van Rossume15dee51995-07-18 14:12:02 +00001093}
1094
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001095/* Binary in-place operators */
1096
1097/* The in-place operators are defined to fall back to the 'normal',
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001098 non in-place operations, if the in-place methods are not in place.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001099
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001100 - If the left hand object has the appropriate struct members, and
1101 they are filled, call the appropriate function and return the
1102 result. No coercion is done on the arguments; the left-hand object
1103 is the one the operation is performed on, and it's up to the
1104 function to deal with the right-hand object.
Guido van Rossum77660912002-04-16 16:32:50 +00001105
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001106 - Otherwise, in-place modification is not supported. Handle it exactly as
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001107 a non in-place operation of the same kind.
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001108
1109 */
1110
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001111static PyObject *
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001112binary_iop1(PyObject *v, PyObject *w, const int iop_slot, const int op_slot)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001113{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001114 PyNumberMethods *mv = Py_TYPE(v)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001115 if (mv != NULL) {
1116 binaryfunc slot = NB_BINOP(mv, iop_slot);
1117 if (slot) {
1118 PyObject *x = (slot)(v, w);
1119 if (x != Py_NotImplemented) {
1120 return x;
1121 }
1122 Py_DECREF(x);
1123 }
1124 }
1125 return binary_op1(v, w, op_slot);
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001126}
1127
1128static PyObject *
1129binary_iop(PyObject *v, PyObject *w, const int iop_slot, const int op_slot,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001130 const char *op_name)
Neil Schemenauerd4b0fea2002-12-30 20:18:15 +00001131{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001132 PyObject *result = binary_iop1(v, w, iop_slot, op_slot);
1133 if (result == Py_NotImplemented) {
1134 Py_DECREF(result);
1135 return binop_type_error(v, w, op_name);
1136 }
1137 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001138}
1139
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001140#define INPLACE_BINOP(func, iop, op, op_name) \
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001141 PyObject * \
1142 func(PyObject *v, PyObject *w) { \
1143 return binary_iop(v, w, NB_SLOT(iop), NB_SLOT(op), op_name); \
1144 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001145
Neil Schemenauer5a1f0152001-01-04 01:39:06 +00001146INPLACE_BINOP(PyNumber_InPlaceOr, nb_inplace_or, nb_or, "|=")
1147INPLACE_BINOP(PyNumber_InPlaceXor, nb_inplace_xor, nb_xor, "^=")
1148INPLACE_BINOP(PyNumber_InPlaceAnd, nb_inplace_and, nb_and, "&=")
1149INPLACE_BINOP(PyNumber_InPlaceLshift, nb_inplace_lshift, nb_lshift, "<<=")
1150INPLACE_BINOP(PyNumber_InPlaceRshift, nb_inplace_rshift, nb_rshift, ">>=")
1151INPLACE_BINOP(PyNumber_InPlaceSubtract, nb_inplace_subtract, nb_subtract, "-=")
Benjamin Petersond51374e2014-04-09 23:55:56 -04001152INPLACE_BINOP(PyNumber_InMatrixMultiply, nb_inplace_matrix_multiply, nb_matrix_multiply, "@=")
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001153
1154PyObject *
Guido van Rossum4668b002001-08-08 05:00:18 +00001155PyNumber_InPlaceFloorDivide(PyObject *v, PyObject *w)
1156{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001157 return binary_iop(v, w, NB_SLOT(nb_inplace_floor_divide),
1158 NB_SLOT(nb_floor_divide), "//=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001159}
1160
1161PyObject *
1162PyNumber_InPlaceTrueDivide(PyObject *v, PyObject *w)
1163{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001164 return binary_iop(v, w, NB_SLOT(nb_inplace_true_divide),
1165 NB_SLOT(nb_true_divide), "/=");
Guido van Rossum4668b002001-08-08 05:00:18 +00001166}
1167
1168PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001169PyNumber_InPlaceAdd(PyObject *v, PyObject *w)
1170{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001171 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_add),
1172 NB_SLOT(nb_add));
1173 if (result == Py_NotImplemented) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001174 PySequenceMethods *m = Py_TYPE(v)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001175 Py_DECREF(result);
1176 if (m != NULL) {
1177 binaryfunc f = NULL;
1178 f = m->sq_inplace_concat;
1179 if (f == NULL)
1180 f = m->sq_concat;
1181 if (f != NULL)
1182 return (*f)(v, w);
1183 }
1184 result = binop_type_error(v, w, "+=");
1185 }
1186 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001187}
1188
1189PyObject *
1190PyNumber_InPlaceMultiply(PyObject *v, PyObject *w)
1191{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001192 PyObject *result = binary_iop1(v, w, NB_SLOT(nb_inplace_multiply),
1193 NB_SLOT(nb_multiply));
1194 if (result == Py_NotImplemented) {
1195 ssizeargfunc f = NULL;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001196 PySequenceMethods *mv = Py_TYPE(v)->tp_as_sequence;
1197 PySequenceMethods *mw = Py_TYPE(w)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001198 Py_DECREF(result);
1199 if (mv != NULL) {
1200 f = mv->sq_inplace_repeat;
1201 if (f == NULL)
1202 f = mv->sq_repeat;
1203 if (f != NULL)
1204 return sequence_repeat(f, v, w);
1205 }
1206 else if (mw != NULL) {
1207 /* Note that the right hand operand should not be
1208 * mutated in this case so sq_inplace_repeat is not
1209 * used. */
1210 if (mw->sq_repeat)
1211 return sequence_repeat(mw->sq_repeat, w, v);
1212 }
1213 result = binop_type_error(v, w, "*=");
1214 }
1215 return result;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001216}
1217
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001218PyObject *
Benjamin Petersond51374e2014-04-09 23:55:56 -04001219PyNumber_InPlaceMatrixMultiply(PyObject *v, PyObject *w)
1220{
1221 return binary_iop(v, w, NB_SLOT(nb_inplace_matrix_multiply),
1222 NB_SLOT(nb_matrix_multiply), "@=");
1223}
1224
1225PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001226PyNumber_InPlaceRemainder(PyObject *v, PyObject *w)
1227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001228 return binary_iop(v, w, NB_SLOT(nb_inplace_remainder),
1229 NB_SLOT(nb_remainder), "%=");
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001230}
1231
1232PyObject *
1233PyNumber_InPlacePower(PyObject *v, PyObject *w, PyObject *z)
1234{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001235 if (Py_TYPE(v)->tp_as_number &&
1236 Py_TYPE(v)->tp_as_number->nb_inplace_power != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001237 return ternary_op(v, w, z, NB_SLOT(nb_inplace_power), "**=");
1238 }
1239 else {
1240 return ternary_op(v, w, z, NB_SLOT(nb_power), "**=");
1241 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001242}
1243
1244
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001245/* Unary operators and functions */
Guido van Rossume15dee51995-07-18 14:12:02 +00001246
1247PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001248PyNumber_Negative(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001249{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001250 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001251
Victor Stinner71aea8e2016-08-19 16:59:55 +02001252 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001253 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001254 }
1255
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001256 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001257 if (m && m->nb_negative)
1258 return (*m->nb_negative)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001260 return type_error("bad operand type for unary -: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001261}
1262
1263PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001264PyNumber_Positive(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001265{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001266 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001267
Victor Stinner71aea8e2016-08-19 16:59:55 +02001268 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001269 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001270 }
1271
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001272 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001273 if (m && m->nb_positive)
1274 return (*m->nb_positive)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001275
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001276 return type_error("bad operand type for unary +: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001277}
1278
1279PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001280PyNumber_Invert(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001281{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001282 PyNumberMethods *m;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001283
Victor Stinner71aea8e2016-08-19 16:59:55 +02001284 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001285 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001286 }
1287
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001288 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001289 if (m && m->nb_invert)
1290 return (*m->nb_invert)(o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001291
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001292 return type_error("bad operand type for unary ~: '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001293}
1294
1295PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001296PyNumber_Absolute(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001297{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001298 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001299
Victor Stinner71aea8e2016-08-19 16:59:55 +02001300 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001301 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001302 }
1303
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001304 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001305 if (m && m->nb_absolute)
1306 return m->nb_absolute(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001307
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001308 return type_error("bad operand type for abs(): '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001309}
1310
Victor Stinnera15e2602020-04-08 02:01:56 +02001311
Christian Tismerea62ce72018-06-09 20:32:25 +02001312int
1313PyIndex_Check(PyObject *obj)
1314{
Victor Stinnera15e2602020-04-08 02:01:56 +02001315 return _PyIndex_Check(obj);
Christian Tismerea62ce72018-06-09 20:32:25 +02001316}
1317
Victor Stinnera15e2602020-04-08 02:01:56 +02001318
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001319/* Return a Python int from the object item.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001320 Raise TypeError if the result is not an int
Guido van Rossum98297ee2007-11-06 21:34:58 +00001321 or if the object cannot be interpreted as an index.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001322*/
1323PyObject *
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001324PyNumber_Index(PyObject *item)
1325{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001326 PyObject *result = NULL;
Victor Stinner71aea8e2016-08-19 16:59:55 +02001327 if (item == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001328 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001329 }
1330
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001331 if (PyLong_Check(item)) {
1332 Py_INCREF(item);
1333 return item;
1334 }
Victor Stinnera15e2602020-04-08 02:01:56 +02001335 if (!_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001336 PyErr_Format(PyExc_TypeError,
1337 "'%.200s' object cannot be interpreted "
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001338 "as an integer", Py_TYPE(item)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001339 return NULL;
1340 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001341 result = Py_TYPE(item)->tp_as_number->nb_index(item);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001342 if (!result || PyLong_CheckExact(result))
1343 return result;
1344 if (!PyLong_Check(result)) {
1345 PyErr_Format(PyExc_TypeError,
1346 "__index__ returned non-int (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001347 Py_TYPE(result)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001348 Py_DECREF(result);
1349 return NULL;
1350 }
1351 /* Issue #17576: warn if 'result' not of exact type int. */
1352 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1353 "__index__ returned non-int (type %.200s). "
1354 "The ability to return an instance of a strict subclass of int "
1355 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001356 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001357 Py_DECREF(result);
1358 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001359 }
1360 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001361}
1362
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001363/* Return an error on Overflow only if err is not NULL*/
1364
1365Py_ssize_t
1366PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1367{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001368 Py_ssize_t result;
1369 PyObject *runerr;
1370 PyObject *value = PyNumber_Index(item);
1371 if (value == NULL)
1372 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001373
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001374 /* We're done if PyLong_AsSsize_t() returns without error. */
1375 result = PyLong_AsSsize_t(value);
1376 if (result != -1 || !(runerr = PyErr_Occurred()))
1377 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001378
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001379 /* Error handling code -- only manage OverflowError differently */
1380 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1381 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001382
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 PyErr_Clear();
1384 /* If no error-handling desired then the default clipping
1385 is sufficient.
1386 */
1387 if (!err) {
1388 assert(PyLong_Check(value));
1389 /* Whether or not it is less than or equal to
1390 zero is determined by the sign of ob_size
1391 */
1392 if (_PyLong_Sign(value) < 0)
1393 result = PY_SSIZE_T_MIN;
1394 else
1395 result = PY_SSIZE_T_MAX;
1396 }
1397 else {
1398 /* Otherwise replace the error with caller's error object. */
1399 PyErr_Format(err,
1400 "cannot fit '%.200s' into an index-sized integer",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001401 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001402 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001403
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001404 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001405 Py_DECREF(value);
1406 return result;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001407}
1408
1409
Guido van Rossume15dee51995-07-18 14:12:02 +00001410PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001411PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001412{
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001413 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001414 PyNumberMethods *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001415 PyObject *trunc_func;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001416 Py_buffer view;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04001417 _Py_IDENTIFIER(__trunc__);
Christian Heimes15ebc882008-02-04 18:48:49 +00001418
Victor Stinner71aea8e2016-08-19 16:59:55 +02001419 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001421 }
1422
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001423 if (PyLong_CheckExact(o)) {
1424 Py_INCREF(o);
1425 return o;
1426 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001427 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001428 if (m && m->nb_int) { /* This should include subclasses of int */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001429 /* Convert using the nb_int slot, which should return something
1430 of exact type int. */
1431 result = m->nb_int(o);
1432 if (!result || PyLong_CheckExact(result))
1433 return result;
1434 if (!PyLong_Check(result)) {
1435 PyErr_Format(PyExc_TypeError,
1436 "__int__ returned non-int (type %.200s)",
1437 result->ob_type->tp_name);
1438 Py_DECREF(result);
1439 return NULL;
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001440 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001441 /* Issue #17576: warn if 'result' not of exact type int. */
1442 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1443 "__int__ returned non-int (type %.200s). "
1444 "The ability to return an instance of a strict subclass of int "
1445 "is deprecated, and may be removed in a future version of Python.",
1446 result->ob_type->tp_name)) {
1447 Py_DECREF(result);
1448 return NULL;
1449 }
1450 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001451 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001452 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001453 if (m && m->nb_index) {
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001454 result = PyNumber_Index(o);
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001455 if (result != NULL && !PyLong_CheckExact(result)) {
1456 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1457 }
1458 return result;
1459 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001460 trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001461 if (trunc_func) {
INADA Naoki72dccde2017-02-16 09:26:01 +09001462 result = _PyObject_CallNoArg(trunc_func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001463 Py_DECREF(trunc_func);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001464 if (result == NULL || PyLong_CheckExact(result)) {
1465 return result;
1466 }
1467 if (PyLong_Check(result)) {
1468 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1469 return result;
1470 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001471 /* __trunc__ is specified to return an Integral type,
Martin Panter7462b6492015-11-02 03:37:02 +00001472 but int() needs to return an int. */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001473 if (!PyIndex_Check(result)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001474 PyErr_Format(
1475 PyExc_TypeError,
1476 "__trunc__ returned non-Integral (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001477 Py_TYPE(result)->tp_name);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001478 Py_DECREF(result);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001479 return NULL;
1480 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001481 Py_SETREF(result, PyNumber_Index(result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001482 if (result != NULL && !PyLong_CheckExact(result)) {
1483 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1484 }
1485 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001486 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001487 if (PyErr_Occurred())
1488 return NULL;
Christian Heimes15ebc882008-02-04 18:48:49 +00001489
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001490 if (PyUnicode_Check(o))
1491 /* The below check is done in PyLong_FromUnicode(). */
1492 return PyLong_FromUnicodeObject(o, 10);
1493
Martin Pantereeb896c2015-11-07 02:32:21 +00001494 if (PyBytes_Check(o))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001495 /* need to do extra error checking that PyLong_FromString()
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03001496 * doesn't do. In particular int('9\x005') must raise an
1497 * exception, not truncate at the null.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001498 */
Martin Pantereeb896c2015-11-07 02:32:21 +00001499 return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1500 PyBytes_GET_SIZE(o), 10);
1501
1502 if (PyByteArray_Check(o))
1503 return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1504 PyByteArray_GET_SIZE(o), 10);
1505
1506 if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001507 PyObject *bytes;
Martin Pantereeb896c2015-11-07 02:32:21 +00001508
1509 /* Copy to NUL-terminated buffer. */
1510 bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1511 if (bytes == NULL) {
1512 PyBuffer_Release(&view);
1513 return NULL;
1514 }
1515 result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1516 PyBytes_GET_SIZE(bytes), 10);
1517 Py_DECREF(bytes);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001518 PyBuffer_Release(&view);
1519 return result;
1520 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001521
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001522 return type_error("int() argument must be a string, a bytes-like object "
1523 "or a number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001524}
1525
1526PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001527PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001528{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001529 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001530
Victor Stinner71aea8e2016-08-19 16:59:55 +02001531 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001532 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001533 }
1534
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001535 if (PyFloat_CheckExact(o)) {
1536 Py_INCREF(o);
1537 return o;
1538 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001539 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 if (m && m->nb_float) { /* This should include subclasses of float */
1541 PyObject *res = m->nb_float(o);
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001542 double val;
1543 if (!res || PyFloat_CheckExact(res)) {
1544 return res;
1545 }
1546 if (!PyFloat_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001547 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001548 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001549 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001550 Py_DECREF(res);
1551 return NULL;
1552 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001553 /* Issue #26983: warn if 'res' not of exact type float. */
1554 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1555 "%.50s.__float__ returned non-float (type %.50s). "
1556 "The ability to return an instance of a strict subclass of float "
1557 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001558 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001559 Py_DECREF(res);
1560 return NULL;
1561 }
1562 val = PyFloat_AS_DOUBLE(res);
1563 Py_DECREF(res);
1564 return PyFloat_FromDouble(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001565 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001566 if (m && m->nb_index) {
1567 PyObject *res = PyNumber_Index(o);
1568 if (!res) {
1569 return NULL;
1570 }
1571 double val = PyLong_AsDouble(res);
1572 Py_DECREF(res);
1573 if (val == -1.0 && PyErr_Occurred()) {
1574 return NULL;
1575 }
1576 return PyFloat_FromDouble(val);
1577 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001578 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001579 return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001580 }
1581 return PyFloat_FromString(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001582}
1583
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001584
1585PyObject *
1586PyNumber_ToBase(PyObject *n, int base)
1587{
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001588 if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
1589 PyErr_SetString(PyExc_SystemError,
1590 "PyNumber_ToBase: base must be 2, 8, 10 or 16");
1591 return NULL;
1592 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001593 PyObject *index = PyNumber_Index(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001594 if (!index)
1595 return NULL;
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001596 PyObject *res = _PyLong_Format(index, base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001597 Py_DECREF(index);
1598 return res;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001599}
1600
1601
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001602/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001603
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001604int
Fred Drake79912472000-07-09 04:06:11 +00001605PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001606{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001607 if (PyDict_Check(s))
1608 return 0;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001609 return Py_TYPE(s)->tp_as_sequence &&
1610 Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001611}
1612
Martin v. Löwis18e16552006-02-15 17:27:45 +00001613Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001614PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001615{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001616 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001617
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001618 if (s == NULL) {
1619 null_error();
1620 return -1;
1621 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001622
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001623 m = Py_TYPE(s)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001624 if (m && m->sq_length) {
1625 Py_ssize_t len = m->sq_length(s);
1626 assert(len >= 0 || PyErr_Occurred());
1627 return len;
1628 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001629
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001630 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001631 type_error("%.200s is not a sequence", s);
1632 return -1;
1633 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001634 type_error("object of type '%.200s' has no len()", s);
1635 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001636}
1637
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001638#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001639Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001640PySequence_Length(PyObject *s)
1641{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001643}
1644#define PySequence_Length PySequence_Size
1645
Guido van Rossume15dee51995-07-18 14:12:02 +00001646PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001647PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001648{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001649 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001650
Victor Stinner71aea8e2016-08-19 16:59:55 +02001651 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001652 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001653 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001654
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001655 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001656 if (m && m->sq_concat)
1657 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001658
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001659 /* Instances of user classes defining an __add__() method only
1660 have an nb_add slot, not an sq_concat slot. So we fall back
1661 to nb_add if both arguments appear to be sequences. */
1662 if (PySequence_Check(s) && PySequence_Check(o)) {
1663 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1664 if (result != Py_NotImplemented)
1665 return result;
1666 Py_DECREF(result);
1667 }
1668 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001669}
1670
1671PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001672PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001673{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001674 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001675
Victor Stinner71aea8e2016-08-19 16:59:55 +02001676 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001677 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001678 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001679
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001680 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001681 if (m && m->sq_repeat)
1682 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001683
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001684 /* Instances of user classes defining a __mul__() method only
1685 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1686 to nb_multiply if o appears to be a sequence. */
1687 if (PySequence_Check(o)) {
1688 PyObject *n, *result;
1689 n = PyLong_FromSsize_t(count);
1690 if (n == NULL)
1691 return NULL;
1692 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1693 Py_DECREF(n);
1694 if (result != Py_NotImplemented)
1695 return result;
1696 Py_DECREF(result);
1697 }
1698 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001699}
1700
1701PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001702PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1703{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001704 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001705
Victor Stinner71aea8e2016-08-19 16:59:55 +02001706 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001707 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001708 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001709
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001710 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001711 if (m && m->sq_inplace_concat)
1712 return m->sq_inplace_concat(s, o);
1713 if (m && m->sq_concat)
1714 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001715
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001716 if (PySequence_Check(s) && PySequence_Check(o)) {
1717 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1718 NB_SLOT(nb_add));
1719 if (result != Py_NotImplemented)
1720 return result;
1721 Py_DECREF(result);
1722 }
1723 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001724}
1725
1726PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001727PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001728{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001729 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001730
Victor Stinner71aea8e2016-08-19 16:59:55 +02001731 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001732 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001733 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001734
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001735 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001736 if (m && m->sq_inplace_repeat)
1737 return m->sq_inplace_repeat(o, count);
1738 if (m && m->sq_repeat)
1739 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001740
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001741 if (PySequence_Check(o)) {
1742 PyObject *n, *result;
1743 n = PyLong_FromSsize_t(count);
1744 if (n == NULL)
1745 return NULL;
1746 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1747 NB_SLOT(nb_multiply));
1748 Py_DECREF(n);
1749 if (result != Py_NotImplemented)
1750 return result;
1751 Py_DECREF(result);
1752 }
1753 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001754}
1755
1756PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001757PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001758{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001759 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001760
Victor Stinner71aea8e2016-08-19 16:59:55 +02001761 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001762 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001763 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001764
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001765 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001766 if (m && m->sq_item) {
1767 if (i < 0) {
1768 if (m->sq_length) {
1769 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnere20310f2015-11-05 13:56:58 +01001770 if (l < 0) {
1771 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001772 return NULL;
Victor Stinnere20310f2015-11-05 13:56:58 +01001773 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 i += l;
1775 }
1776 }
1777 return m->sq_item(s, i);
1778 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001779
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001780 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001781 return type_error("%.200s is not a sequence", s);
1782 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001783 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001784}
1785
1786PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001787PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001788{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001789 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001790
Victor Stinner71aea8e2016-08-19 16:59:55 +02001791 if (!s) {
1792 return null_error();
1793 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001794
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001795 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001796 if (mp && mp->mp_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyObject *res;
1798 PyObject *slice = _PySlice_FromIndices(i1, i2);
1799 if (!slice)
1800 return NULL;
1801 res = mp->mp_subscript(s, slice);
1802 Py_DECREF(slice);
1803 return res;
1804 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001805
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001806 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001807}
1808
1809int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001810PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001811{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001812 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 if (s == NULL) {
1815 null_error();
1816 return -1;
1817 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001818
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001819 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 if (m && m->sq_ass_item) {
1821 if (i < 0) {
1822 if (m->sq_length) {
1823 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001824 if (l < 0) {
1825 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001826 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001827 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 i += l;
1829 }
1830 }
1831 return m->sq_ass_item(s, i, o);
1832 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001833
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001834 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001835 type_error("%.200s is not a sequence", s);
1836 return -1;
1837 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001838 type_error("'%.200s' object does not support item assignment", s);
1839 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001840}
1841
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001842int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001843PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001844{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001845 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001846
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001847 if (s == NULL) {
1848 null_error();
1849 return -1;
1850 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001851
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001852 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 if (m && m->sq_ass_item) {
1854 if (i < 0) {
1855 if (m->sq_length) {
1856 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001857 if (l < 0) {
1858 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001859 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001860 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 i += l;
1862 }
1863 }
1864 return m->sq_ass_item(s, i, (PyObject *)NULL);
1865 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001866
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001867 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001868 type_error("%.200s is not a sequence", s);
1869 return -1;
1870 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001871 type_error("'%.200s' object doesn't support item deletion", s);
1872 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001873}
1874
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001875int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001876PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001877{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001878 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001879
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001880 if (s == NULL) {
1881 null_error();
1882 return -1;
1883 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001884
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001885 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001886 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001887 int res;
1888 PyObject *slice = _PySlice_FromIndices(i1, i2);
1889 if (!slice)
1890 return -1;
1891 res = mp->mp_ass_subscript(s, slice, o);
1892 Py_DECREF(slice);
1893 return res;
1894 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00001895
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001896 type_error("'%.200s' object doesn't support slice assignment", s);
1897 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001898}
1899
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001900int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001901PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001902{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001903 PyMappingMethods *mp;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001904
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001905 if (s == NULL) {
1906 null_error();
1907 return -1;
1908 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001909
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001910 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001911 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001912 int res;
1913 PyObject *slice = _PySlice_FromIndices(i1, i2);
1914 if (!slice)
1915 return -1;
1916 res = mp->mp_ass_subscript(s, slice, NULL);
1917 Py_DECREF(slice);
1918 return res;
1919 }
1920 type_error("'%.200s' object doesn't support slice deletion", s);
1921 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001922}
1923
Guido van Rossume15dee51995-07-18 14:12:02 +00001924PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001925PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00001926{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001927 PyObject *it; /* iter(v) */
1928 Py_ssize_t n; /* guess for result tuple size */
1929 PyObject *result = NULL;
1930 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00001931
Victor Stinner71aea8e2016-08-19 16:59:55 +02001932 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001933 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001934 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001935
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001936 /* Special-case the common tuple and list cases, for efficiency. */
1937 if (PyTuple_CheckExact(v)) {
1938 /* Note that we can't know whether it's safe to return
1939 a tuple *subclass* instance as-is, hence the restriction
1940 to exact tuples here. In contrast, lists always make
1941 a copy, so there's no need for exactness below. */
1942 Py_INCREF(v);
1943 return v;
1944 }
Raymond Hettinger610a51f2015-05-17 14:45:58 -07001945 if (PyList_CheckExact(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001946 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001947
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001948 /* Get iterator. */
1949 it = PyObject_GetIter(v);
1950 if (it == NULL)
1951 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001952
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001953 /* Guess result size and allocate space. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001954 n = PyObject_LengthHint(v, 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001955 if (n == -1)
1956 goto Fail;
1957 result = PyTuple_New(n);
1958 if (result == NULL)
1959 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 /* Fill the tuple. */
1962 for (j = 0; ; ++j) {
1963 PyObject *item = PyIter_Next(it);
1964 if (item == NULL) {
1965 if (PyErr_Occurred())
1966 goto Fail;
1967 break;
1968 }
1969 if (j >= n) {
Martin Pantere8db8612016-07-25 02:30:05 +00001970 size_t newn = (size_t)n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001971 /* The over-allocation strategy can grow a bit faster
1972 than for lists because unlike lists the
1973 over-allocation isn't permanent -- we reclaim
1974 the excess before the end of this routine.
1975 So, grow by ten and then add 25%.
1976 */
Martin Pantere8db8612016-07-25 02:30:05 +00001977 newn += 10u;
1978 newn += newn >> 2;
1979 if (newn > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001980 /* Check for overflow */
1981 PyErr_NoMemory();
1982 Py_DECREF(item);
1983 goto Fail;
1984 }
Martin Pantere8db8612016-07-25 02:30:05 +00001985 n = (Py_ssize_t)newn;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001986 if (_PyTuple_Resize(&result, n) != 0) {
1987 Py_DECREF(item);
1988 goto Fail;
1989 }
1990 }
1991 PyTuple_SET_ITEM(result, j, item);
1992 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001993
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 /* Cut tuple back if guess was too large. */
1995 if (j < n &&
1996 _PyTuple_Resize(&result, j) != 0)
1997 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001998
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001999 Py_DECREF(it);
2000 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00002001
2002Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002003 Py_XDECREF(result);
2004 Py_DECREF(it);
2005 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002006}
2007
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002008PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002009PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002010{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 PyObject *result; /* result list */
2012 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00002013
Victor Stinner71aea8e2016-08-19 16:59:55 +02002014 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002015 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002016 }
Guido van Rossum5dba9e81998-07-10 18:03:50 +00002017
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002018 result = PyList_New(0);
2019 if (result == NULL)
2020 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00002021
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002022 rv = _PyList_Extend((PyListObject *)result, v);
2023 if (rv == NULL) {
2024 Py_DECREF(result);
2025 return NULL;
2026 }
2027 Py_DECREF(rv);
2028 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002029}
2030
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002031PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002032PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002033{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002034 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002035
Victor Stinner71aea8e2016-08-19 16:59:55 +02002036 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002037 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002038 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002039
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002040 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2041 Py_INCREF(v);
2042 return v;
2043 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002044
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 it = PyObject_GetIter(v);
2046 if (it == NULL) {
2047 if (PyErr_ExceptionMatches(PyExc_TypeError))
2048 PyErr_SetString(PyExc_TypeError, m);
2049 return NULL;
2050 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002051
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002052 v = PySequence_List(it);
2053 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002054
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002055 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002056}
2057
Tim Peters16a77ad2001-09-08 04:00:12 +00002058/* Iterate over seq. Result depends on the operation:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002059 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2060 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2061 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002062 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2063*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002064Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002065_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002066{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 Py_ssize_t n;
2068 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2069 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002070
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002071 if (seq == NULL || obj == NULL) {
2072 null_error();
2073 return -1;
2074 }
Tim Peters75f8e352001-05-05 11:33:43 +00002075
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002076 it = PyObject_GetIter(seq);
2077 if (it == NULL) {
2078 type_error("argument of type '%.200s' is not iterable", seq);
2079 return -1;
2080 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002081
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002082 n = wrapped = 0;
2083 for (;;) {
2084 int cmp;
2085 PyObject *item = PyIter_Next(it);
2086 if (item == NULL) {
2087 if (PyErr_Occurred())
2088 goto Fail;
2089 break;
2090 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002091
Serhiy Storchaka18b711c2019-08-04 14:12:48 +03002092 cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002093 Py_DECREF(item);
2094 if (cmp < 0)
2095 goto Fail;
2096 if (cmp > 0) {
2097 switch (operation) {
2098 case PY_ITERSEARCH_COUNT:
2099 if (n == PY_SSIZE_T_MAX) {
2100 PyErr_SetString(PyExc_OverflowError,
2101 "count exceeds C integer size");
2102 goto Fail;
2103 }
2104 ++n;
2105 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002106
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002107 case PY_ITERSEARCH_INDEX:
2108 if (wrapped) {
2109 PyErr_SetString(PyExc_OverflowError,
2110 "index exceeds C integer size");
2111 goto Fail;
2112 }
2113 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 case PY_ITERSEARCH_CONTAINS:
2116 n = 1;
2117 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002118
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002119 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002120 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002121 }
2122 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002123
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002124 if (operation == PY_ITERSEARCH_INDEX) {
2125 if (n == PY_SSIZE_T_MAX)
2126 wrapped = 1;
2127 ++n;
2128 }
2129 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002130
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002131 if (operation != PY_ITERSEARCH_INDEX)
2132 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002133
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002134 PyErr_SetString(PyExc_ValueError,
2135 "sequence.index(x): x not in sequence");
2136 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002137Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002138 n = -1;
2139 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002140Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002141 Py_DECREF(it);
2142 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002143
Guido van Rossume15dee51995-07-18 14:12:02 +00002144}
2145
Tim Peters16a77ad2001-09-08 04:00:12 +00002146/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002147Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002148PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002149{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002150 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002151}
2152
Tim Peterscb8d3682001-05-05 21:05:01 +00002153/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002154 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002155 */
2156int
2157PySequence_Contains(PyObject *seq, PyObject *ob)
2158{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002159 Py_ssize_t result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002160 PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002161 if (sqm != NULL && sqm->sq_contains != NULL)
2162 return (*sqm->sq_contains)(seq, ob);
2163 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2164 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002165}
2166
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002167/* Backwards compatibility */
2168#undef PySequence_In
2169int
Fred Drake79912472000-07-09 04:06:11 +00002170PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002171{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002172 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002173}
2174
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002175Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002176PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002177{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002178 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002179}
2180
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002181/* Operations on mappings */
2182
2183int
Fred Drake79912472000-07-09 04:06:11 +00002184PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002185{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002186 return o && Py_TYPE(o)->tp_as_mapping &&
2187 Py_TYPE(o)->tp_as_mapping->mp_subscript;
Guido van Rossume15dee51995-07-18 14:12:02 +00002188}
2189
Martin v. Löwis18e16552006-02-15 17:27:45 +00002190Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002191PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002192{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002193 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002194
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002195 if (o == NULL) {
2196 null_error();
2197 return -1;
2198 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002199
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002200 m = Py_TYPE(o)->tp_as_mapping;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03002201 if (m && m->mp_length) {
2202 Py_ssize_t len = m->mp_length(o);
2203 assert(len >= 0 || PyErr_Occurred());
2204 return len;
2205 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002206
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002207 if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03002208 type_error("%.200s is not a mapping", o);
2209 return -1;
2210 }
2211 /* PyMapping_Size() can be called from PyObject_Size(). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002212 type_error("object of type '%.200s' has no len()", o);
2213 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002214}
2215
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002216#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002217Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002218PyMapping_Length(PyObject *o)
2219{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002221}
2222#define PyMapping_Length PyMapping_Size
2223
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002224PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002225PyMapping_GetItemString(PyObject *o, const char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002226{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002227 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002228
Victor Stinner71aea8e2016-08-19 16:59:55 +02002229 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002230 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002231 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002232
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002233 okey = PyUnicode_FromString(key);
2234 if (okey == NULL)
2235 return NULL;
2236 r = PyObject_GetItem(o, okey);
2237 Py_DECREF(okey);
2238 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002239}
2240
2241int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002242PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002243{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002244 PyObject *okey;
2245 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002246
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002247 if (key == NULL) {
2248 null_error();
2249 return -1;
2250 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002251
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 okey = PyUnicode_FromString(key);
2253 if (okey == NULL)
2254 return -1;
2255 r = PyObject_SetItem(o, okey, value);
2256 Py_DECREF(okey);
2257 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002258}
2259
2260int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002261PyMapping_HasKeyString(PyObject *o, const char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002262{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002263 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002264
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002265 v = PyMapping_GetItemString(o, key);
2266 if (v) {
2267 Py_DECREF(v);
2268 return 1;
2269 }
2270 PyErr_Clear();
2271 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002272}
2273
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002274int
Fred Drake79912472000-07-09 04:06:11 +00002275PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002276{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002277 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002278
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002279 v = PyObject_GetItem(o, key);
2280 if (v) {
2281 Py_DECREF(v);
2282 return 1;
2283 }
2284 PyErr_Clear();
2285 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002286}
2287
Oren Milman0ccc0f62017-10-08 11:17:46 +03002288/* This function is quite similar to PySequence_Fast(), but specialized to be
2289 a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2290 */
2291static PyObject *
2292method_output_as_list(PyObject *o, _Py_Identifier *meth_id)
2293{
2294 PyObject *it, *result, *meth_output;
2295
2296 assert(o != NULL);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002297 meth_output = _PyObject_CallMethodIdNoArgs(o, meth_id);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002298 if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2299 return meth_output;
2300 }
2301 it = PyObject_GetIter(meth_output);
2302 if (it == NULL) {
2303 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2304 PyErr_Format(PyExc_TypeError,
2305 "%.200s.%U() returned a non-iterable (type %.200s)",
2306 Py_TYPE(o)->tp_name,
Victor Stinner4804b5b2020-05-12 01:43:38 +02002307 _PyUnicode_FromId(meth_id),
Oren Milman0ccc0f62017-10-08 11:17:46 +03002308 Py_TYPE(meth_output)->tp_name);
2309 }
2310 Py_DECREF(meth_output);
2311 return NULL;
2312 }
2313 Py_DECREF(meth_output);
2314 result = PySequence_List(it);
2315 Py_DECREF(it);
2316 return result;
2317}
2318
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002319PyObject *
2320PyMapping_Keys(PyObject *o)
2321{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002322 _Py_IDENTIFIER(keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002323
Oren Milman0ccc0f62017-10-08 11:17:46 +03002324 if (o == NULL) {
2325 return null_error();
2326 }
2327 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002328 return PyDict_Keys(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002329 }
2330 return method_output_as_list(o, &PyId_keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002331}
2332
2333PyObject *
2334PyMapping_Items(PyObject *o)
2335{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002336 _Py_IDENTIFIER(items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002337
Oren Milman0ccc0f62017-10-08 11:17:46 +03002338 if (o == NULL) {
2339 return null_error();
2340 }
2341 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002342 return PyDict_Items(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002343 }
2344 return method_output_as_list(o, &PyId_items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002345}
2346
2347PyObject *
2348PyMapping_Values(PyObject *o)
2349{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002350 _Py_IDENTIFIER(values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002351
Oren Milman0ccc0f62017-10-08 11:17:46 +03002352 if (o == NULL) {
2353 return null_error();
2354 }
2355 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002356 return PyDict_Values(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002357 }
2358 return method_output_as_list(o, &PyId_values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002359}
2360
Guido van Rossum823649d2001-03-21 18:40:58 +00002361/* isinstance(), issubclass() */
2362
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002363/* abstract_get_bases() has logically 4 return states:
Barry Warsawf16951c2002-04-23 22:45:44 +00002364 *
Barry Warsawf16951c2002-04-23 22:45:44 +00002365 * 1. getattr(cls, '__bases__') could raise an AttributeError
2366 * 2. getattr(cls, '__bases__') could raise some other exception
2367 * 3. getattr(cls, '__bases__') could return a tuple
2368 * 4. getattr(cls, '__bases__') could return something other than a tuple
2369 *
2370 * Only state #3 is a non-error state and only it returns a non-NULL object
2371 * (it returns the retrieved tuple).
2372 *
2373 * Any raised AttributeErrors are masked by clearing the exception and
2374 * returning NULL. If an object other than a tuple comes out of __bases__,
2375 * then again, the return value is NULL. So yes, these two situations
2376 * produce exactly the same results: NULL is returned and no error is set.
2377 *
2378 * If some exception other than AttributeError is raised, then NULL is also
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002379 * returned, but the exception is not cleared. That's because we want the
Barry Warsawf16951c2002-04-23 22:45:44 +00002380 * exception to be propagated along.
2381 *
2382 * Callers are expected to test for PyErr_Occurred() when the return value
2383 * is NULL to decide whether a valid exception should be propagated or not.
2384 * When there's no exception to propagate, it's customary for the caller to
2385 * set a TypeError.
2386 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002387static PyObject *
2388abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002389{
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002390 _Py_IDENTIFIER(__bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002391 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002392
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002393 Py_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002394 (void)_PyObject_LookupAttrId(cls, &PyId___bases__, &bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002395 Py_END_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002396 if (bases != NULL && !PyTuple_Check(bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002397 Py_DECREF(bases);
2398 return NULL;
2399 }
2400 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002401}
2402
2403
2404static int
2405abstract_issubclass(PyObject *derived, PyObject *cls)
2406{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002407 PyObject *bases = NULL;
2408 Py_ssize_t i, n;
2409 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002410
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002411 while (1) {
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002412 if (derived == cls) {
2413 Py_XDECREF(bases); /* See below comment */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002414 return 1;
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002415 }
2416 /* Use XSETREF to drop bases reference *after* finishing with
2417 derived; bases might be the only reference to it.
2418 XSETREF is used instead of SETREF, because bases is NULL on the
2419 first iteration of the loop.
2420 */
2421 Py_XSETREF(bases, abstract_get_bases(derived));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 if (bases == NULL) {
2423 if (PyErr_Occurred())
2424 return -1;
2425 return 0;
2426 }
2427 n = PyTuple_GET_SIZE(bases);
2428 if (n == 0) {
2429 Py_DECREF(bases);
2430 return 0;
2431 }
2432 /* Avoid recursivity in the single inheritance case */
2433 if (n == 1) {
2434 derived = PyTuple_GET_ITEM(bases, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002435 continue;
2436 }
2437 for (i = 0; i < n; i++) {
2438 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2439 if (r != 0)
2440 break;
2441 }
2442 Py_DECREF(bases);
2443 return r;
2444 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002445}
2446
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002447static int
2448check_class(PyObject *cls, const char *error)
2449{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002450 PyObject *bases = abstract_get_bases(cls);
2451 if (bases == NULL) {
2452 /* Do not mask errors. */
2453 if (!PyErr_Occurred())
2454 PyErr_SetString(PyExc_TypeError, error);
2455 return 0;
2456 }
2457 Py_DECREF(bases);
2458 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002459}
2460
Brett Cannon4f653312004-03-20 22:52:14 +00002461static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002462object_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002463{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002464 PyObject *icls;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002465 int retval;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002466 _Py_IDENTIFIER(__class__);
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002467
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002468 if (PyType_Check(cls)) {
2469 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2470 if (retval == 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002471 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2472 if (icls != NULL) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002473 if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002474 retval = PyType_IsSubtype(
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002475 (PyTypeObject *)icls,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 (PyTypeObject *)cls);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002477 }
2478 else {
2479 retval = 0;
2480 }
2481 Py_DECREF(icls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 }
2483 }
2484 }
2485 else {
2486 if (!check_class(cls,
Benjamin Petersone893af52010-06-28 19:43:42 +00002487 "isinstance() arg 2 must be a type or tuple of types"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002488 return -1;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002489 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2490 if (icls != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002491 retval = abstract_issubclass(icls, cls);
2492 Py_DECREF(icls);
2493 }
2494 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002495
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002497}
2498
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002499static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002500object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002501{
Benjamin Petersonce798522012-01-22 11:24:29 -05002502 _Py_IDENTIFIER(__instancecheck__);
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 /* Quick test for an exact match */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002505 if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002506 return 1;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002507 }
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002508
Georg Brandl72b8a802014-10-03 09:26:37 +02002509 /* We know what type's __instancecheck__ does. */
2510 if (PyType_CheckExact(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002511 return object_isinstance(inst, cls);
Georg Brandl72b8a802014-10-03 09:26:37 +02002512 }
2513
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 if (PyTuple_Check(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002515 /* Not a general sequence -- that opens up the road to
2516 recursion and stack overflow. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002517 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002518 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002519 }
2520 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2521 int r = 0;
2522 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002523 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002524 r = object_recursive_isinstance(tstate, inst, item);
2525 if (r != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 /* either found it, or got an error */
2527 break;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002528 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002529 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002530 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 return r;
2532 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002533
Victor Stinner850a4bd2020-02-04 13:42:13 +01002534 PyObject *checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002535 if (checker != NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002536 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002538 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002540
Petr Viktorinffd97532020-02-11 17:46:57 +01002541 PyObject *res = PyObject_CallOneArg(checker, inst);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002542 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002544
2545 if (res == NULL) {
2546 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002548 int ok = PyObject_IsTrue(res);
2549 Py_DECREF(res);
2550
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 return ok;
2552 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002553 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002554 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002555 }
2556
Victor Stinner850a4bd2020-02-04 13:42:13 +01002557 /* cls has no __instancecheck__() method */
2558 return object_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002559}
2560
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002561
2562int
2563PyObject_IsInstance(PyObject *inst, PyObject *cls)
2564{
2565 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner850a4bd2020-02-04 13:42:13 +01002566 return object_recursive_isinstance(tstate, inst, cls);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002567}
2568
2569
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002570static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002571recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002572{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002573 if (PyType_Check(cls) && PyType_Check(derived)) {
2574 /* Fast path (non-recursive) */
2575 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2576 }
2577 if (!check_class(derived,
2578 "issubclass() arg 1 must be a class"))
2579 return -1;
2580 if (!check_class(cls,
2581 "issubclass() arg 2 must be a class"
2582 " or tuple of classes"))
2583 return -1;
Guido van Rossum823649d2001-03-21 18:40:58 +00002584
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002585 return abstract_issubclass(derived, cls);
Guido van Rossum823649d2001-03-21 18:40:58 +00002586}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002587
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002588static int
2589object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002590{
Benjamin Petersonce798522012-01-22 11:24:29 -05002591 _Py_IDENTIFIER(__subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002592 PyObject *checker;
Georg Brandldcfe8e42009-05-17 08:22:45 +00002593
Georg Brandl72b8a802014-10-03 09:26:37 +02002594 /* We know what type's __subclasscheck__ does. */
2595 if (PyType_CheckExact(cls)) {
2596 /* Quick test for an exact match */
2597 if (derived == cls)
2598 return 1;
2599 return recursive_issubclass(derived, cls);
2600 }
2601
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002602 if (PyTuple_Check(cls)) {
Antoine Pitrouec569b72008-08-26 22:40:48 +00002603
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002604 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002605 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002606 }
2607 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2608 int r = 0;
2609 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002611 r = object_issubclass(tstate, derived, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002612 if (r != 0)
2613 /* either found it, or got an error */
2614 break;
2615 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002616 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002617 return r;
2618 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002619
Benjamin Petersonce798522012-01-22 11:24:29 -05002620 checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002621 if (checker != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002622 int ok = -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002623 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002624 Py_DECREF(checker);
2625 return ok;
2626 }
Petr Viktorinffd97532020-02-11 17:46:57 +01002627 PyObject *res = PyObject_CallOneArg(checker, derived);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002628 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 Py_DECREF(checker);
2630 if (res != NULL) {
2631 ok = PyObject_IsTrue(res);
2632 Py_DECREF(res);
2633 }
2634 return ok;
2635 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002636 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002638 }
2639
Georg Brandl72b8a802014-10-03 09:26:37 +02002640 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002641 return recursive_issubclass(derived, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002642}
2643
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002644
2645int
2646PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2647{
2648 PyThreadState *tstate = _PyThreadState_GET();
2649 return object_issubclass(tstate, derived, cls);
2650}
2651
2652
Antoine Pitrouec569b72008-08-26 22:40:48 +00002653int
2654_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2655{
Victor Stinner850a4bd2020-02-04 13:42:13 +01002656 return object_isinstance(inst, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002657}
2658
2659int
2660_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2661{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002662 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002663}
2664
2665
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002666PyObject *
2667PyObject_GetIter(PyObject *o)
2668{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002669 PyTypeObject *t = Py_TYPE(o);
Victor Stinner14e6d092016-12-09 17:08:59 +01002670 getiterfunc f;
2671
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002672 f = t->tp_iter;
2673 if (f == NULL) {
2674 if (PySequence_Check(o))
2675 return PySeqIter_New(o);
2676 return type_error("'%.200s' object is not iterable", o);
2677 }
2678 else {
2679 PyObject *res = (*f)(o);
2680 if (res != NULL && !PyIter_Check(res)) {
2681 PyErr_Format(PyExc_TypeError,
2682 "iter() returned non-iterator "
2683 "of type '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002684 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002685 Py_DECREF(res);
2686 res = NULL;
2687 }
2688 return res;
2689 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002690}
2691
Christian Tismerea62ce72018-06-09 20:32:25 +02002692#undef PyIter_Check
Christian Tismer83987132018-06-11 00:48:28 +02002693
Christian Tismerea62ce72018-06-09 20:32:25 +02002694int PyIter_Check(PyObject *obj)
2695{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002696 return Py_TYPE(obj)->tp_iternext != NULL &&
2697 Py_TYPE(obj)->tp_iternext != &_PyObject_NextNotImplemented;
Christian Tismerea62ce72018-06-09 20:32:25 +02002698}
2699
Tim Petersf4848da2001-05-05 00:14:56 +00002700/* Return next item.
2701 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2702 * If the iteration terminates normally, return NULL and clear the
2703 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2704 * will be false.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002705 * Else return the next object. PyErr_Occurred() will be false.
Tim Petersf4848da2001-05-05 00:14:56 +00002706 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002707PyObject *
2708PyIter_Next(PyObject *iter)
2709{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002710 PyObject *result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002711 result = (*Py_TYPE(iter)->tp_iternext)(iter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002712 if (result == NULL &&
2713 PyErr_Occurred() &&
2714 PyErr_ExceptionMatches(PyExc_StopIteration))
2715 PyErr_Clear();
2716 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002717}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002718
2719
2720/*
2721 * Flatten a sequence of bytes() objects into a C array of
2722 * NULL terminated string pointers with a NULL char* terminating the array.
2723 * (ie: an argv or env list)
2724 *
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002725 * Memory allocated for the returned list is allocated using PyMem_Malloc()
2726 * and MUST be freed by _Py_FreeCharPArray().
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002727 */
2728char *const *
2729_PySequence_BytesToCharpArray(PyObject* self)
2730{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002731 char **array;
2732 Py_ssize_t i, argc;
2733 PyObject *item = NULL;
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002734 Py_ssize_t size;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002735
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002736 argc = PySequence_Size(self);
2737 if (argc == -1)
2738 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002739
Stefan Krah7cacd2e2012-08-21 08:16:09 +02002740 assert(argc >= 0);
2741
2742 if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
2743 PyErr_NoMemory();
2744 return NULL;
2745 }
2746
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002747 array = PyMem_Malloc((argc + 1) * sizeof(char *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002748 if (array == NULL) {
2749 PyErr_NoMemory();
2750 return NULL;
2751 }
2752 for (i = 0; i < argc; ++i) {
2753 char *data;
2754 item = PySequence_GetItem(self, i);
Stefan Krahfd24f9e2012-08-20 11:04:24 +02002755 if (item == NULL) {
2756 /* NULL terminate before freeing. */
2757 array[i] = NULL;
2758 goto fail;
2759 }
Serhiy Storchakad174d242017-06-23 19:39:27 +03002760 /* check for embedded null bytes */
2761 if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002762 /* NULL terminate before freeing. */
2763 array[i] = NULL;
2764 goto fail;
2765 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002766 size = PyBytes_GET_SIZE(item) + 1;
2767 array[i] = PyMem_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002768 if (!array[i]) {
2769 PyErr_NoMemory();
2770 goto fail;
2771 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002772 memcpy(array[i], data, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002773 Py_DECREF(item);
2774 }
2775 array[argc] = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002776
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002777 return array;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002778
2779fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002780 Py_XDECREF(item);
2781 _Py_FreeCharPArray(array);
2782 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002783}
2784
2785
2786/* Free's a NULL terminated char** array of C strings. */
2787void
2788_Py_FreeCharPArray(char *const array[])
2789{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002790 Py_ssize_t i;
2791 for (i = 0; array[i] != NULL; ++i) {
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002792 PyMem_Free(array[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002793 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002794 PyMem_Free((void*)array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002795}