blob: 973c43fe7fda9de664204e052c3bed1145c9116f [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 Storchaka5f4b229d2020-05-28 10:33:45 +03001320 Can return an instance of int subclass.
Serhiy Storchaka95949422013-08-27 19:40:23 +03001321 Raise TypeError if the result is not an int
Guido van Rossum98297ee2007-11-06 21:34:58 +00001322 or if the object cannot be interpreted as an index.
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001323*/
1324PyObject *
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001325_PyNumber_Index(PyObject *item)
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001326{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001327 PyObject *result = NULL;
Victor Stinner71aea8e2016-08-19 16:59:55 +02001328 if (item == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001329 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001330 }
1331
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001332 if (PyLong_Check(item)) {
1333 Py_INCREF(item);
1334 return item;
1335 }
Victor Stinnera15e2602020-04-08 02:01:56 +02001336 if (!_PyIndex_Check(item)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001337 PyErr_Format(PyExc_TypeError,
1338 "'%.200s' object cannot be interpreted "
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001339 "as an integer", Py_TYPE(item)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001340 return NULL;
1341 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001342 result = Py_TYPE(item)->tp_as_number->nb_index(item);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001343 if (!result || PyLong_CheckExact(result))
1344 return result;
1345 if (!PyLong_Check(result)) {
1346 PyErr_Format(PyExc_TypeError,
1347 "__index__ returned non-int (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001348 Py_TYPE(result)->tp_name);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001349 Py_DECREF(result);
1350 return NULL;
1351 }
1352 /* Issue #17576: warn if 'result' not of exact type int. */
1353 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1354 "__index__ returned non-int (type %.200s). "
1355 "The ability to return an instance of a strict subclass of int "
1356 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001357 Py_TYPE(result)->tp_name)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001358 Py_DECREF(result);
1359 return NULL;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001360 }
1361 return result;
Guido van Rossum38fff8c2006-03-07 18:50:55 +00001362}
1363
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001364/* Return an exact Python int from the object item.
1365 Raise TypeError if the result is not an int
1366 or if the object cannot be interpreted as an index.
1367*/
1368PyObject *
1369PyNumber_Index(PyObject *item)
1370{
1371 PyObject *result = _PyNumber_Index(item);
1372 if (result != NULL && !PyLong_CheckExact(result)) {
1373 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1374 }
1375 return result;
1376}
1377
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001378/* Return an error on Overflow only if err is not NULL*/
1379
1380Py_ssize_t
1381PyNumber_AsSsize_t(PyObject *item, PyObject *err)
1382{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001383 Py_ssize_t result;
1384 PyObject *runerr;
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001385 PyObject *value = _PyNumber_Index(item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001386 if (value == NULL)
1387 return -1;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001388
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001389 /* We're done if PyLong_AsSsize_t() returns without error. */
1390 result = PyLong_AsSsize_t(value);
1391 if (result != -1 || !(runerr = PyErr_Occurred()))
1392 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001393
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001394 /* Error handling code -- only manage OverflowError differently */
1395 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
1396 goto finish;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001397
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001398 PyErr_Clear();
1399 /* If no error-handling desired then the default clipping
1400 is sufficient.
1401 */
1402 if (!err) {
1403 assert(PyLong_Check(value));
1404 /* Whether or not it is less than or equal to
1405 zero is determined by the sign of ob_size
1406 */
1407 if (_PyLong_Sign(value) < 0)
1408 result = PY_SSIZE_T_MIN;
1409 else
1410 result = PY_SSIZE_T_MAX;
1411 }
1412 else {
1413 /* Otherwise replace the error with caller's error object. */
1414 PyErr_Format(err,
1415 "cannot fit '%.200s' into an index-sized integer",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001416 Py_TYPE(item)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001417 }
Guido van Rossum98297ee2007-11-06 21:34:58 +00001418
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001419 finish:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001420 Py_DECREF(value);
1421 return result;
Thomas Wouters00ee7ba2006-08-21 19:07:27 +00001422}
1423
1424
Guido van Rossume15dee51995-07-18 14:12:02 +00001425PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001426PyNumber_Long(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001427{
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001428 PyObject *result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001429 PyNumberMethods *m;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001430 PyObject *trunc_func;
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001431 Py_buffer view;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04001432 _Py_IDENTIFIER(__trunc__);
Christian Heimes15ebc882008-02-04 18:48:49 +00001433
Victor Stinner71aea8e2016-08-19 16:59:55 +02001434 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001435 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001436 }
1437
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001438 if (PyLong_CheckExact(o)) {
1439 Py_INCREF(o);
1440 return o;
1441 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001442 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001443 if (m && m->nb_int) { /* This should include subclasses of int */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001444 /* Convert using the nb_int slot, which should return something
1445 of exact type int. */
1446 result = m->nb_int(o);
1447 if (!result || PyLong_CheckExact(result))
1448 return result;
1449 if (!PyLong_Check(result)) {
1450 PyErr_Format(PyExc_TypeError,
1451 "__int__ returned non-int (type %.200s)",
1452 result->ob_type->tp_name);
1453 Py_DECREF(result);
1454 return NULL;
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001455 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001456 /* Issue #17576: warn if 'result' not of exact type int. */
1457 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1458 "__int__ returned non-int (type %.200s). "
1459 "The ability to return an instance of a strict subclass of int "
1460 "is deprecated, and may be removed in a future version of Python.",
1461 result->ob_type->tp_name)) {
1462 Py_DECREF(result);
1463 return NULL;
1464 }
1465 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001466 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001467 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001468 if (m && m->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001469 return PyNumber_Index(o);
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001470 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001471 trunc_func = _PyObject_LookupSpecial(o, &PyId___trunc__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001472 if (trunc_func) {
INADA Naoki72dccde2017-02-16 09:26:01 +09001473 result = _PyObject_CallNoArg(trunc_func);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001474 Py_DECREF(trunc_func);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001475 if (result == NULL || PyLong_CheckExact(result)) {
1476 return result;
1477 }
1478 if (PyLong_Check(result)) {
1479 Py_SETREF(result, _PyLong_Copy((PyLongObject *)result));
1480 return result;
1481 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001482 /* __trunc__ is specified to return an Integral type,
Martin Panter7462b6492015-11-02 03:37:02 +00001483 but int() needs to return an int. */
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001484 if (!PyIndex_Check(result)) {
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001485 PyErr_Format(
1486 PyExc_TypeError,
1487 "__trunc__ returned non-Integral (type %.200s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001488 Py_TYPE(result)->tp_name);
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001489 Py_DECREF(result);
Serhiy Storchaka31a65542013-12-11 21:07:54 +02001490 return NULL;
1491 }
Serhiy Storchaka578c3952020-05-26 18:43:38 +03001492 Py_SETREF(result, PyNumber_Index(result));
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001493 return result;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001494 }
Benjamin Peterson1b1a8e72012-03-20 23:48:11 -04001495 if (PyErr_Occurred())
1496 return NULL;
Christian Heimes15ebc882008-02-04 18:48:49 +00001497
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001498 if (PyUnicode_Check(o))
1499 /* The below check is done in PyLong_FromUnicode(). */
1500 return PyLong_FromUnicodeObject(o, 10);
1501
Martin Pantereeb896c2015-11-07 02:32:21 +00001502 if (PyBytes_Check(o))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001503 /* need to do extra error checking that PyLong_FromString()
Serhiy Storchakaf6d0aee2013-08-03 20:55:06 +03001504 * doesn't do. In particular int('9\x005') must raise an
1505 * exception, not truncate at the null.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001506 */
Martin Pantereeb896c2015-11-07 02:32:21 +00001507 return _PyLong_FromBytes(PyBytes_AS_STRING(o),
1508 PyBytes_GET_SIZE(o), 10);
1509
1510 if (PyByteArray_Check(o))
1511 return _PyLong_FromBytes(PyByteArray_AS_STRING(o),
1512 PyByteArray_GET_SIZE(o), 10);
1513
1514 if (PyObject_GetBuffer(o, &view, PyBUF_SIMPLE) == 0) {
Serhiy Storchaka54cd1962016-08-21 20:03:08 +03001515 PyObject *bytes;
Martin Pantereeb896c2015-11-07 02:32:21 +00001516
1517 /* Copy to NUL-terminated buffer. */
1518 bytes = PyBytes_FromStringAndSize((const char *)view.buf, view.len);
1519 if (bytes == NULL) {
1520 PyBuffer_Release(&view);
1521 return NULL;
1522 }
1523 result = _PyLong_FromBytes(PyBytes_AS_STRING(bytes),
1524 PyBytes_GET_SIZE(bytes), 10);
1525 Py_DECREF(bytes);
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001526 PyBuffer_Release(&view);
1527 return result;
1528 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001529
Serhiy Storchaka4fdb6842015-02-03 01:21:08 +02001530 return type_error("int() argument must be a string, a bytes-like object "
1531 "or a number, not '%.200s'", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001532}
1533
1534PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001535PyNumber_Float(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001536{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001537 PyNumberMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001538
Victor Stinner71aea8e2016-08-19 16:59:55 +02001539 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001540 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001541 }
1542
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001543 if (PyFloat_CheckExact(o)) {
1544 Py_INCREF(o);
1545 return o;
1546 }
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001547 m = Py_TYPE(o)->tp_as_number;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001548 if (m && m->nb_float) { /* This should include subclasses of float */
1549 PyObject *res = m->nb_float(o);
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001550 double val;
1551 if (!res || PyFloat_CheckExact(res)) {
1552 return res;
1553 }
1554 if (!PyFloat_Check(res)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001555 PyErr_Format(PyExc_TypeError,
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001556 "%.50s.__float__ returned non-float (type %.50s)",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001557 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001558 Py_DECREF(res);
1559 return NULL;
1560 }
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001561 /* Issue #26983: warn if 'res' not of exact type float. */
1562 if (PyErr_WarnFormat(PyExc_DeprecationWarning, 1,
1563 "%.50s.__float__ returned non-float (type %.50s). "
1564 "The ability to return an instance of a strict subclass of float "
1565 "is deprecated, and may be removed in a future version of Python.",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001566 Py_TYPE(o)->tp_name, Py_TYPE(res)->tp_name)) {
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001567 Py_DECREF(res);
1568 return NULL;
1569 }
1570 val = PyFloat_AS_DOUBLE(res);
1571 Py_DECREF(res);
1572 return PyFloat_FromDouble(val);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001573 }
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001574 if (m && m->nb_index) {
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001575 PyObject *res = _PyNumber_Index(o);
Serhiy Storchakabdbad712019-06-02 00:05:48 +03001576 if (!res) {
1577 return NULL;
1578 }
1579 double val = PyLong_AsDouble(res);
1580 Py_DECREF(res);
1581 if (val == -1.0 && PyErr_Occurred()) {
1582 return NULL;
1583 }
1584 return PyFloat_FromDouble(val);
1585 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001586 if (PyFloat_Check(o)) { /* A float subclass with nb_float == NULL */
Serhiy Storchaka16931c32016-06-03 21:42:55 +03001587 return PyFloat_FromDouble(PyFloat_AS_DOUBLE(o));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001588 }
1589 return PyFloat_FromString(o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001590}
1591
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001592
1593PyObject *
1594PyNumber_ToBase(PyObject *n, int base)
1595{
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001596 if (!(base == 2 || base == 8 || base == 10 || base == 16)) {
1597 PyErr_SetString(PyExc_SystemError,
1598 "PyNumber_ToBase: base must be 2, 8, 10 or 16");
1599 return NULL;
1600 }
Serhiy Storchaka5f4b229d2020-05-28 10:33:45 +03001601 PyObject *index = _PyNumber_Index(n);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001602 if (!index)
1603 return NULL;
Serhiy Storchakae5ccc942020-03-09 20:03:38 +02001604 PyObject *res = _PyLong_Format(index, base);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001605 Py_DECREF(index);
1606 return res;
Guido van Rossumcd16bf62007-06-13 18:07:49 +00001607}
1608
1609
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001610/* Operations on sequences */
Guido van Rossume15dee51995-07-18 14:12:02 +00001611
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001612int
Fred Drake79912472000-07-09 04:06:11 +00001613PySequence_Check(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001614{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001615 if (PyDict_Check(s))
1616 return 0;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001617 return Py_TYPE(s)->tp_as_sequence &&
1618 Py_TYPE(s)->tp_as_sequence->sq_item != NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00001619}
1620
Martin v. Löwis18e16552006-02-15 17:27:45 +00001621Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00001622PySequence_Size(PyObject *s)
Guido van Rossume15dee51995-07-18 14:12:02 +00001623{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001624 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001625
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001626 if (s == NULL) {
1627 null_error();
1628 return -1;
1629 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001630
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001631 m = Py_TYPE(s)->tp_as_sequence;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001632 if (m && m->sq_length) {
1633 Py_ssize_t len = m->sq_length(s);
1634 assert(len >= 0 || PyErr_Occurred());
1635 return len;
1636 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001637
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001638 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001639 type_error("%.200s is not a sequence", s);
1640 return -1;
1641 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001642 type_error("object of type '%.200s' has no len()", s);
1643 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001644}
1645
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001646#undef PySequence_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00001647Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001648PySequence_Length(PyObject *s)
1649{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001650 return PySequence_Size(s);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00001651}
1652#define PySequence_Length PySequence_Size
1653
Guido van Rossume15dee51995-07-18 14:12:02 +00001654PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001655PySequence_Concat(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001656{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001657 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001658
Victor Stinner71aea8e2016-08-19 16:59:55 +02001659 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001660 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001661 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001662
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001663 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001664 if (m && m->sq_concat)
1665 return m->sq_concat(s, o);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001666
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001667 /* Instances of user classes defining an __add__() method only
1668 have an nb_add slot, not an sq_concat slot. So we fall back
1669 to nb_add if both arguments appear to be sequences. */
1670 if (PySequence_Check(s) && PySequence_Check(o)) {
1671 PyObject *result = binary_op1(s, o, NB_SLOT(nb_add));
1672 if (result != Py_NotImplemented)
1673 return result;
1674 Py_DECREF(result);
1675 }
1676 return type_error("'%.200s' object can't be concatenated", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001677}
1678
1679PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001680PySequence_Repeat(PyObject *o, Py_ssize_t count)
Guido van Rossume15dee51995-07-18 14:12:02 +00001681{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001682 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001683
Victor Stinner71aea8e2016-08-19 16:59:55 +02001684 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001685 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001686 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001687
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001688 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001689 if (m && m->sq_repeat)
1690 return m->sq_repeat(o, count);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001691
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001692 /* Instances of user classes defining a __mul__() method only
1693 have an nb_multiply slot, not an sq_repeat slot. so we fall back
1694 to nb_multiply if o appears to be a sequence. */
1695 if (PySequence_Check(o)) {
1696 PyObject *n, *result;
1697 n = PyLong_FromSsize_t(count);
1698 if (n == NULL)
1699 return NULL;
1700 result = binary_op1(o, n, NB_SLOT(nb_multiply));
1701 Py_DECREF(n);
1702 if (result != Py_NotImplemented)
1703 return result;
1704 Py_DECREF(result);
1705 }
1706 return type_error("'%.200s' object can't be repeated", o);
Guido van Rossume15dee51995-07-18 14:12:02 +00001707}
1708
1709PyObject *
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001710PySequence_InPlaceConcat(PyObject *s, PyObject *o)
1711{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001712 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001713
Victor Stinner71aea8e2016-08-19 16:59:55 +02001714 if (s == NULL || o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001715 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001716 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001717
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001718 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001719 if (m && m->sq_inplace_concat)
1720 return m->sq_inplace_concat(s, o);
1721 if (m && m->sq_concat)
1722 return m->sq_concat(s, o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001723
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001724 if (PySequence_Check(s) && PySequence_Check(o)) {
1725 PyObject *result = binary_iop1(s, o, NB_SLOT(nb_inplace_add),
1726 NB_SLOT(nb_add));
1727 if (result != Py_NotImplemented)
1728 return result;
1729 Py_DECREF(result);
1730 }
1731 return type_error("'%.200s' object can't be concatenated", s);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001732}
1733
1734PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001735PySequence_InPlaceRepeat(PyObject *o, Py_ssize_t count)
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001736{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001737 PySequenceMethods *m;
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001738
Victor Stinner71aea8e2016-08-19 16:59:55 +02001739 if (o == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001740 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001741 }
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001742
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001743 m = Py_TYPE(o)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001744 if (m && m->sq_inplace_repeat)
1745 return m->sq_inplace_repeat(o, count);
1746 if (m && m->sq_repeat)
1747 return m->sq_repeat(o, count);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001748
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001749 if (PySequence_Check(o)) {
1750 PyObject *n, *result;
1751 n = PyLong_FromSsize_t(count);
1752 if (n == NULL)
1753 return NULL;
1754 result = binary_iop1(o, n, NB_SLOT(nb_inplace_multiply),
1755 NB_SLOT(nb_multiply));
1756 Py_DECREF(n);
1757 if (result != Py_NotImplemented)
1758 return result;
1759 Py_DECREF(result);
1760 }
1761 return type_error("'%.200s' object can't be repeated", o);
Thomas Wouterse289e0b2000-08-24 20:08:19 +00001762}
1763
1764PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001765PySequence_GetItem(PyObject *s, Py_ssize_t i)
Guido van Rossume15dee51995-07-18 14:12:02 +00001766{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001767 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001768
Victor Stinner71aea8e2016-08-19 16:59:55 +02001769 if (s == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001770 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001771 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001772
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001773 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001774 if (m && m->sq_item) {
1775 if (i < 0) {
1776 if (m->sq_length) {
1777 Py_ssize_t l = (*m->sq_length)(s);
Victor Stinnere20310f2015-11-05 13:56:58 +01001778 if (l < 0) {
1779 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001780 return NULL;
Victor Stinnere20310f2015-11-05 13:56:58 +01001781 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001782 i += l;
1783 }
1784 }
1785 return m->sq_item(s, i);
1786 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001787
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001788 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001789 return type_error("%.200s is not a sequence", s);
1790 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001791 return type_error("'%.200s' object does not support indexing", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001792}
1793
1794PyObject *
Martin v. Löwis18e16552006-02-15 17:27:45 +00001795PySequence_GetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossume15dee51995-07-18 14:12:02 +00001796{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001797 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001798
Victor Stinner71aea8e2016-08-19 16:59:55 +02001799 if (!s) {
1800 return null_error();
1801 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001802
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001803 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001804 if (mp && mp->mp_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001805 PyObject *res;
1806 PyObject *slice = _PySlice_FromIndices(i1, i2);
1807 if (!slice)
1808 return NULL;
1809 res = mp->mp_subscript(s, slice);
1810 Py_DECREF(slice);
1811 return res;
1812 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001813
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001814 return type_error("'%.200s' object is unsliceable", s);
Guido van Rossume15dee51995-07-18 14:12:02 +00001815}
1816
1817int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001818PySequence_SetItem(PyObject *s, Py_ssize_t i, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001819{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001820 PySequenceMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00001821
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001822 if (s == NULL) {
1823 null_error();
1824 return -1;
1825 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001826
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001827 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001828 if (m && m->sq_ass_item) {
1829 if (i < 0) {
1830 if (m->sq_length) {
1831 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001832 if (l < 0) {
1833 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001834 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001835 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001836 i += l;
1837 }
1838 }
1839 return m->sq_ass_item(s, i, o);
1840 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001841
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001842 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001843 type_error("%.200s is not a sequence", s);
1844 return -1;
1845 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001846 type_error("'%.200s' object does not support item assignment", s);
1847 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001848}
1849
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001850int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001851PySequence_DelItem(PyObject *s, Py_ssize_t i)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001852{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001853 PySequenceMethods *m;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001854
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001855 if (s == NULL) {
1856 null_error();
1857 return -1;
1858 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001859
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001860 m = Py_TYPE(s)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001861 if (m && m->sq_ass_item) {
1862 if (i < 0) {
1863 if (m->sq_length) {
1864 Py_ssize_t l = (*m->sq_length)(s);
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001865 if (l < 0) {
1866 assert(PyErr_Occurred());
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001867 return -1;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03001868 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001869 i += l;
1870 }
1871 }
1872 return m->sq_ass_item(s, i, (PyObject *)NULL);
1873 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001874
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001875 if (Py_TYPE(s)->tp_as_mapping && Py_TYPE(s)->tp_as_mapping->mp_ass_subscript) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03001876 type_error("%.200s is not a sequence", s);
1877 return -1;
1878 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001879 type_error("'%.200s' object doesn't support item deletion", s);
1880 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001881}
1882
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001883int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001884PySequence_SetSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00001885{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001886 PyMappingMethods *mp;
Guido van Rossume15dee51995-07-18 14:12:02 +00001887
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001888 if (s == NULL) {
1889 null_error();
1890 return -1;
1891 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001892
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001893 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001894 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001895 int res;
1896 PyObject *slice = _PySlice_FromIndices(i1, i2);
1897 if (!slice)
1898 return -1;
1899 res = mp->mp_ass_subscript(s, slice, o);
1900 Py_DECREF(slice);
1901 return res;
1902 }
Thomas Wouters1d75a792000-08-17 22:37:32 +00001903
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001904 type_error("'%.200s' object doesn't support slice assignment", s);
1905 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00001906}
1907
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001908int
Martin v. Löwis18e16552006-02-15 17:27:45 +00001909PySequence_DelSlice(PyObject *s, Py_ssize_t i1, Py_ssize_t i2)
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001910{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001911 PyMappingMethods *mp;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001912
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001913 if (s == NULL) {
1914 null_error();
1915 return -1;
1916 }
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001917
Victor Stinner0d76d2b2020-02-07 01:53:23 +01001918 mp = Py_TYPE(s)->tp_as_mapping;
Benjamin Peterson568867a2010-09-11 16:02:03 +00001919 if (mp && mp->mp_ass_subscript) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001920 int res;
1921 PyObject *slice = _PySlice_FromIndices(i1, i2);
1922 if (!slice)
1923 return -1;
1924 res = mp->mp_ass_subscript(s, slice, NULL);
1925 Py_DECREF(slice);
1926 return res;
1927 }
1928 type_error("'%.200s' object doesn't support slice deletion", s);
1929 return -1;
Guido van Rossum6cdc6f41996-08-21 17:41:54 +00001930}
1931
Guido van Rossume15dee51995-07-18 14:12:02 +00001932PyObject *
Fred Drake79912472000-07-09 04:06:11 +00001933PySequence_Tuple(PyObject *v)
Guido van Rossume15dee51995-07-18 14:12:02 +00001934{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001935 PyObject *it; /* iter(v) */
1936 Py_ssize_t n; /* guess for result tuple size */
1937 PyObject *result = NULL;
1938 Py_ssize_t j;
Guido van Rossume15dee51995-07-18 14:12:02 +00001939
Victor Stinner71aea8e2016-08-19 16:59:55 +02001940 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001941 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02001942 }
Guido van Rossume15dee51995-07-18 14:12:02 +00001943
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001944 /* Special-case the common tuple and list cases, for efficiency. */
1945 if (PyTuple_CheckExact(v)) {
1946 /* Note that we can't know whether it's safe to return
1947 a tuple *subclass* instance as-is, hence the restriction
1948 to exact tuples here. In contrast, lists always make
1949 a copy, so there's no need for exactness below. */
1950 Py_INCREF(v);
1951 return v;
1952 }
Raymond Hettinger610a51f2015-05-17 14:45:58 -07001953 if (PyList_CheckExact(v))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001954 return PyList_AsTuple(v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001955
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001956 /* Get iterator. */
1957 it = PyObject_GetIter(v);
1958 if (it == NULL)
1959 return NULL;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00001960
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001961 /* Guess result size and allocate space. */
Armin Ronacheraa9a79d2012-10-06 14:03:24 +02001962 n = PyObject_LengthHint(v, 10);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001963 if (n == -1)
1964 goto Fail;
1965 result = PyTuple_New(n);
1966 if (result == NULL)
1967 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00001968
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001969 /* Fill the tuple. */
1970 for (j = 0; ; ++j) {
1971 PyObject *item = PyIter_Next(it);
1972 if (item == NULL) {
1973 if (PyErr_Occurred())
1974 goto Fail;
1975 break;
1976 }
1977 if (j >= n) {
Martin Pantere8db8612016-07-25 02:30:05 +00001978 size_t newn = (size_t)n;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001979 /* The over-allocation strategy can grow a bit faster
1980 than for lists because unlike lists the
1981 over-allocation isn't permanent -- we reclaim
1982 the excess before the end of this routine.
1983 So, grow by ten and then add 25%.
1984 */
Martin Pantere8db8612016-07-25 02:30:05 +00001985 newn += 10u;
1986 newn += newn >> 2;
1987 if (newn > PY_SSIZE_T_MAX) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001988 /* Check for overflow */
1989 PyErr_NoMemory();
1990 Py_DECREF(item);
1991 goto Fail;
1992 }
Martin Pantere8db8612016-07-25 02:30:05 +00001993 n = (Py_ssize_t)newn;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00001994 if (_PyTuple_Resize(&result, n) != 0) {
1995 Py_DECREF(item);
1996 goto Fail;
1997 }
1998 }
1999 PyTuple_SET_ITEM(result, j, item);
2000 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002001
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002002 /* Cut tuple back if guess was too large. */
2003 if (j < n &&
2004 _PyTuple_Resize(&result, j) != 0)
2005 goto Fail;
Tim Peters6912d4d2001-05-05 03:56:37 +00002006
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002007 Py_DECREF(it);
2008 return result;
Tim Peters6912d4d2001-05-05 03:56:37 +00002009
2010Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002011 Py_XDECREF(result);
2012 Py_DECREF(it);
2013 return NULL;
Guido van Rossume15dee51995-07-18 14:12:02 +00002014}
2015
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002016PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002017PySequence_List(PyObject *v)
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002018{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002019 PyObject *result; /* result list */
2020 PyObject *rv; /* return value from PyList_Extend */
Guido van Rossum4669fb41997-04-02 05:31:09 +00002021
Victor Stinner71aea8e2016-08-19 16:59:55 +02002022 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002023 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002024 }
Guido van Rossum5dba9e81998-07-10 18:03:50 +00002025
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002026 result = PyList_New(0);
2027 if (result == NULL)
2028 return NULL;
Tim Petersf553f892001-05-01 20:45:31 +00002029
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002030 rv = _PyList_Extend((PyListObject *)result, v);
2031 if (rv == NULL) {
2032 Py_DECREF(result);
2033 return NULL;
2034 }
2035 Py_DECREF(rv);
2036 return result;
Guido van Rossum3c5936a1996-12-05 21:51:24 +00002037}
2038
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002039PyObject *
Fred Drake79912472000-07-09 04:06:11 +00002040PySequence_Fast(PyObject *v, const char *m)
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002041{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002042 PyObject *it;
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002043
Victor Stinner71aea8e2016-08-19 16:59:55 +02002044 if (v == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002045 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002046 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002047
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002048 if (PyList_CheckExact(v) || PyTuple_CheckExact(v)) {
2049 Py_INCREF(v);
2050 return v;
2051 }
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002052
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002053 it = PyObject_GetIter(v);
2054 if (it == NULL) {
2055 if (PyErr_ExceptionMatches(PyExc_TypeError))
2056 PyErr_SetString(PyExc_TypeError, m);
2057 return NULL;
2058 }
Raymond Hettinger2fb70292004-01-11 23:26:51 +00002059
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002060 v = PySequence_List(it);
2061 Py_DECREF(it);
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002062
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002063 return v;
Andrew M. Kuchling74042d62000-06-18 18:43:14 +00002064}
2065
Tim Peters16a77ad2001-09-08 04:00:12 +00002066/* Iterate over seq. Result depends on the operation:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002067 PY_ITERSEARCH_COUNT: -1 if error, else # of times obj appears in seq.
2068 PY_ITERSEARCH_INDEX: 0-based index of first occurrence of obj in seq;
2069 set ValueError and return -1 if none found; also return -1 on error.
Tim Peters16a77ad2001-09-08 04:00:12 +00002070 Py_ITERSEARCH_CONTAINS: return 1 if obj in seq, else 0; -1 on error.
2071*/
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002072Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002073_PySequence_IterSearch(PyObject *seq, PyObject *obj, int operation)
Guido van Rossume15dee51995-07-18 14:12:02 +00002074{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002075 Py_ssize_t n;
2076 int wrapped; /* for PY_ITERSEARCH_INDEX, true iff n wrapped around */
2077 PyObject *it; /* iter(seq) */
Guido van Rossume15dee51995-07-18 14:12:02 +00002078
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002079 if (seq == NULL || obj == NULL) {
2080 null_error();
2081 return -1;
2082 }
Tim Peters75f8e352001-05-05 11:33:43 +00002083
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002084 it = PyObject_GetIter(seq);
2085 if (it == NULL) {
2086 type_error("argument of type '%.200s' is not iterable", seq);
2087 return -1;
2088 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002089
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002090 n = wrapped = 0;
2091 for (;;) {
2092 int cmp;
2093 PyObject *item = PyIter_Next(it);
2094 if (item == NULL) {
2095 if (PyErr_Occurred())
2096 goto Fail;
2097 break;
2098 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002099
Serhiy Storchaka18b711c2019-08-04 14:12:48 +03002100 cmp = PyObject_RichCompareBool(item, obj, Py_EQ);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002101 Py_DECREF(item);
2102 if (cmp < 0)
2103 goto Fail;
2104 if (cmp > 0) {
2105 switch (operation) {
2106 case PY_ITERSEARCH_COUNT:
2107 if (n == PY_SSIZE_T_MAX) {
2108 PyErr_SetString(PyExc_OverflowError,
2109 "count exceeds C integer size");
2110 goto Fail;
2111 }
2112 ++n;
2113 break;
Tim Peters16a77ad2001-09-08 04:00:12 +00002114
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002115 case PY_ITERSEARCH_INDEX:
2116 if (wrapped) {
2117 PyErr_SetString(PyExc_OverflowError,
2118 "index exceeds C integer size");
2119 goto Fail;
2120 }
2121 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002122
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002123 case PY_ITERSEARCH_CONTAINS:
2124 n = 1;
2125 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002126
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002127 default:
Barry Warsawb2e57942017-09-14 18:13:16 -07002128 Py_UNREACHABLE();
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002129 }
2130 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002131
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002132 if (operation == PY_ITERSEARCH_INDEX) {
2133 if (n == PY_SSIZE_T_MAX)
2134 wrapped = 1;
2135 ++n;
2136 }
2137 }
Tim Peters16a77ad2001-09-08 04:00:12 +00002138
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002139 if (operation != PY_ITERSEARCH_INDEX)
2140 goto Done;
Tim Peters16a77ad2001-09-08 04:00:12 +00002141
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002142 PyErr_SetString(PyExc_ValueError,
2143 "sequence.index(x): x not in sequence");
2144 /* fall into failure code */
Tim Peters16a77ad2001-09-08 04:00:12 +00002145Fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002146 n = -1;
2147 /* fall through */
Tim Peters16a77ad2001-09-08 04:00:12 +00002148Done:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002149 Py_DECREF(it);
2150 return n;
Tim Peters75f8e352001-05-05 11:33:43 +00002151
Guido van Rossume15dee51995-07-18 14:12:02 +00002152}
2153
Tim Peters16a77ad2001-09-08 04:00:12 +00002154/* Return # of times o appears in s. */
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002155Py_ssize_t
Tim Peters16a77ad2001-09-08 04:00:12 +00002156PySequence_Count(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002157{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002158 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_COUNT);
Guido van Rossume15dee51995-07-18 14:12:02 +00002159}
2160
Tim Peterscb8d3682001-05-05 21:05:01 +00002161/* Return -1 if error; 1 if ob in seq; 0 if ob not in seq.
Tim Peters16a77ad2001-09-08 04:00:12 +00002162 * Use sq_contains if possible, else defer to _PySequence_IterSearch().
Tim Peterscb8d3682001-05-05 21:05:01 +00002163 */
2164int
2165PySequence_Contains(PyObject *seq, PyObject *ob)
2166{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002167 Py_ssize_t result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002168 PySequenceMethods *sqm = Py_TYPE(seq)->tp_as_sequence;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002169 if (sqm != NULL && sqm->sq_contains != NULL)
2170 return (*sqm->sq_contains)(seq, ob);
2171 result = _PySequence_IterSearch(seq, ob, PY_ITERSEARCH_CONTAINS);
2172 return Py_SAFE_DOWNCAST(result, Py_ssize_t, int);
Tim Peterscb8d3682001-05-05 21:05:01 +00002173}
2174
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002175/* Backwards compatibility */
2176#undef PySequence_In
2177int
Fred Drake79912472000-07-09 04:06:11 +00002178PySequence_In(PyObject *w, PyObject *v)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002179{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002180 return PySequence_Contains(w, v);
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002181}
2182
Neal Norwitz1fc4b772006-03-04 18:49:58 +00002183Py_ssize_t
Fred Drake79912472000-07-09 04:06:11 +00002184PySequence_Index(PyObject *s, PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002185{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002186 return _PySequence_IterSearch(s, o, PY_ITERSEARCH_INDEX);
Guido van Rossume15dee51995-07-18 14:12:02 +00002187}
2188
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002189/* Operations on mappings */
2190
2191int
Fred Drake79912472000-07-09 04:06:11 +00002192PyMapping_Check(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002193{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002194 return o && Py_TYPE(o)->tp_as_mapping &&
2195 Py_TYPE(o)->tp_as_mapping->mp_subscript;
Guido van Rossume15dee51995-07-18 14:12:02 +00002196}
2197
Martin v. Löwis18e16552006-02-15 17:27:45 +00002198Py_ssize_t
Jeremy Hylton6253f832000-07-12 12:56:19 +00002199PyMapping_Size(PyObject *o)
Guido van Rossume15dee51995-07-18 14:12:02 +00002200{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002201 PyMappingMethods *m;
Guido van Rossume15dee51995-07-18 14:12:02 +00002202
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002203 if (o == NULL) {
2204 null_error();
2205 return -1;
2206 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002207
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002208 m = Py_TYPE(o)->tp_as_mapping;
Serhiy Storchaka813f9432017-04-16 09:21:44 +03002209 if (m && m->mp_length) {
2210 Py_ssize_t len = m->mp_length(o);
2211 assert(len >= 0 || PyErr_Occurred());
2212 return len;
2213 }
Guido van Rossume15dee51995-07-18 14:12:02 +00002214
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002215 if (Py_TYPE(o)->tp_as_sequence && Py_TYPE(o)->tp_as_sequence->sq_length) {
Serhiy Storchakaa6fdddb2018-07-23 23:43:42 +03002216 type_error("%.200s is not a mapping", o);
2217 return -1;
2218 }
2219 /* PyMapping_Size() can be called from PyObject_Size(). */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002220 type_error("object of type '%.200s' has no len()", o);
2221 return -1;
Guido van Rossume15dee51995-07-18 14:12:02 +00002222}
2223
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002224#undef PyMapping_Length
Martin v. Löwis18e16552006-02-15 17:27:45 +00002225Py_ssize_t
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002226PyMapping_Length(PyObject *o)
2227{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002228 return PyMapping_Size(o);
Marc-André Lemburgcf5f3582000-07-17 09:22:55 +00002229}
2230#define PyMapping_Length PyMapping_Size
2231
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002232PyObject *
Serhiy Storchakac6792272013-10-19 21:03:34 +03002233PyMapping_GetItemString(PyObject *o, const char *key)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002234{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002235 PyObject *okey, *r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002236
Victor Stinner71aea8e2016-08-19 16:59:55 +02002237 if (key == NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002238 return null_error();
Victor Stinner71aea8e2016-08-19 16:59:55 +02002239 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002240
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002241 okey = PyUnicode_FromString(key);
2242 if (okey == NULL)
2243 return NULL;
2244 r = PyObject_GetItem(o, okey);
2245 Py_DECREF(okey);
2246 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002247}
2248
2249int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002250PyMapping_SetItemString(PyObject *o, const char *key, PyObject *value)
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002251{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002252 PyObject *okey;
2253 int r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002254
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002255 if (key == NULL) {
2256 null_error();
2257 return -1;
2258 }
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002259
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002260 okey = PyUnicode_FromString(key);
2261 if (okey == NULL)
2262 return -1;
2263 r = PyObject_SetItem(o, okey, value);
2264 Py_DECREF(okey);
2265 return r;
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002266}
2267
2268int
Serhiy Storchakac6792272013-10-19 21:03:34 +03002269PyMapping_HasKeyString(PyObject *o, const char *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002270{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002271 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002272
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002273 v = PyMapping_GetItemString(o, key);
2274 if (v) {
2275 Py_DECREF(v);
2276 return 1;
2277 }
2278 PyErr_Clear();
2279 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002280}
2281
Guido van Rossumcea1c8c1998-05-22 00:47:05 +00002282int
Fred Drake79912472000-07-09 04:06:11 +00002283PyMapping_HasKey(PyObject *o, PyObject *key)
Guido van Rossume15dee51995-07-18 14:12:02 +00002284{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002285 PyObject *v;
Guido van Rossume15dee51995-07-18 14:12:02 +00002286
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002287 v = PyObject_GetItem(o, key);
2288 if (v) {
2289 Py_DECREF(v);
2290 return 1;
2291 }
2292 PyErr_Clear();
2293 return 0;
Guido van Rossume15dee51995-07-18 14:12:02 +00002294}
2295
Oren Milman0ccc0f62017-10-08 11:17:46 +03002296/* This function is quite similar to PySequence_Fast(), but specialized to be
2297 a helper for PyMapping_Keys(), PyMapping_Items() and PyMapping_Values().
2298 */
2299static PyObject *
2300method_output_as_list(PyObject *o, _Py_Identifier *meth_id)
2301{
2302 PyObject *it, *result, *meth_output;
2303
2304 assert(o != NULL);
Jeroen Demeyer762f93f2019-07-08 10:19:25 +02002305 meth_output = _PyObject_CallMethodIdNoArgs(o, meth_id);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002306 if (meth_output == NULL || PyList_CheckExact(meth_output)) {
2307 return meth_output;
2308 }
2309 it = PyObject_GetIter(meth_output);
2310 if (it == NULL) {
2311 if (PyErr_ExceptionMatches(PyExc_TypeError)) {
2312 PyErr_Format(PyExc_TypeError,
2313 "%.200s.%U() returned a non-iterable (type %.200s)",
2314 Py_TYPE(o)->tp_name,
Victor Stinner4804b5b2020-05-12 01:43:38 +02002315 _PyUnicode_FromId(meth_id),
Oren Milman0ccc0f62017-10-08 11:17:46 +03002316 Py_TYPE(meth_output)->tp_name);
2317 }
2318 Py_DECREF(meth_output);
2319 return NULL;
2320 }
2321 Py_DECREF(meth_output);
2322 result = PySequence_List(it);
2323 Py_DECREF(it);
2324 return result;
2325}
2326
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002327PyObject *
2328PyMapping_Keys(PyObject *o)
2329{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002330 _Py_IDENTIFIER(keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002331
Oren Milman0ccc0f62017-10-08 11:17:46 +03002332 if (o == NULL) {
2333 return null_error();
2334 }
2335 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002336 return PyDict_Keys(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002337 }
2338 return method_output_as_list(o, &PyId_keys);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002339}
2340
2341PyObject *
2342PyMapping_Items(PyObject *o)
2343{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002344 _Py_IDENTIFIER(items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002345
Oren Milman0ccc0f62017-10-08 11:17:46 +03002346 if (o == NULL) {
2347 return null_error();
2348 }
2349 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002350 return PyDict_Items(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002351 }
2352 return method_output_as_list(o, &PyId_items);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002353}
2354
2355PyObject *
2356PyMapping_Values(PyObject *o)
2357{
Martin v. Löwisbd928fe2011-10-14 10:20:37 +02002358 _Py_IDENTIFIER(values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002359
Oren Milman0ccc0f62017-10-08 11:17:46 +03002360 if (o == NULL) {
2361 return null_error();
2362 }
2363 if (PyDict_CheckExact(o)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002364 return PyDict_Values(o);
Oren Milman0ccc0f62017-10-08 11:17:46 +03002365 }
2366 return method_output_as_list(o, &PyId_values);
Guido van Rossumcc2b0162007-02-11 06:12:03 +00002367}
2368
Guido van Rossum823649d2001-03-21 18:40:58 +00002369/* isinstance(), issubclass() */
2370
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002371/* abstract_get_bases() has logically 4 return states:
Barry Warsawf16951c2002-04-23 22:45:44 +00002372 *
Barry Warsawf16951c2002-04-23 22:45:44 +00002373 * 1. getattr(cls, '__bases__') could raise an AttributeError
2374 * 2. getattr(cls, '__bases__') could raise some other exception
2375 * 3. getattr(cls, '__bases__') could return a tuple
2376 * 4. getattr(cls, '__bases__') could return something other than a tuple
2377 *
2378 * Only state #3 is a non-error state and only it returns a non-NULL object
2379 * (it returns the retrieved tuple).
2380 *
2381 * Any raised AttributeErrors are masked by clearing the exception and
2382 * returning NULL. If an object other than a tuple comes out of __bases__,
2383 * then again, the return value is NULL. So yes, these two situations
2384 * produce exactly the same results: NULL is returned and no error is set.
2385 *
2386 * If some exception other than AttributeError is raised, then NULL is also
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002387 * returned, but the exception is not cleared. That's because we want the
Barry Warsawf16951c2002-04-23 22:45:44 +00002388 * exception to be propagated along.
2389 *
2390 * Callers are expected to test for PyErr_Occurred() when the return value
2391 * is NULL to decide whether a valid exception should be propagated or not.
2392 * When there's no exception to propagate, it's customary for the caller to
2393 * set a TypeError.
2394 */
Neil Schemenauer6b471292001-10-18 03:18:43 +00002395static PyObject *
2396abstract_get_bases(PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002397{
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002398 _Py_IDENTIFIER(__bases__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002399 PyObject *bases;
Guido van Rossum823649d2001-03-21 18:40:58 +00002400
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002401 Py_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002402 (void)_PyObject_LookupAttrId(cls, &PyId___bases__, &bases);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002403 Py_END_ALLOW_RECURSION
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002404 if (bases != NULL && !PyTuple_Check(bases)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002405 Py_DECREF(bases);
2406 return NULL;
2407 }
2408 return bases;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002409}
2410
2411
2412static int
2413abstract_issubclass(PyObject *derived, PyObject *cls)
2414{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002415 PyObject *bases = NULL;
2416 Py_ssize_t i, n;
2417 int r = 0;
Neil Schemenauer6b471292001-10-18 03:18:43 +00002418
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002419 while (1) {
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002420 if (derived == cls) {
2421 Py_XDECREF(bases); /* See below comment */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002422 return 1;
Yonatan Goldschmidt1c56f8f2020-02-22 15:11:48 +02002423 }
2424 /* Use XSETREF to drop bases reference *after* finishing with
2425 derived; bases might be the only reference to it.
2426 XSETREF is used instead of SETREF, because bases is NULL on the
2427 first iteration of the loop.
2428 */
2429 Py_XSETREF(bases, abstract_get_bases(derived));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002430 if (bases == NULL) {
2431 if (PyErr_Occurred())
2432 return -1;
2433 return 0;
2434 }
2435 n = PyTuple_GET_SIZE(bases);
2436 if (n == 0) {
2437 Py_DECREF(bases);
2438 return 0;
2439 }
2440 /* Avoid recursivity in the single inheritance case */
2441 if (n == 1) {
2442 derived = PyTuple_GET_ITEM(bases, 0);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002443 continue;
2444 }
2445 for (i = 0; i < n; i++) {
2446 r = abstract_issubclass(PyTuple_GET_ITEM(bases, i), cls);
2447 if (r != 0)
2448 break;
2449 }
2450 Py_DECREF(bases);
2451 return r;
2452 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002453}
2454
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002455static int
2456check_class(PyObject *cls, const char *error)
2457{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002458 PyObject *bases = abstract_get_bases(cls);
2459 if (bases == NULL) {
2460 /* Do not mask errors. */
2461 if (!PyErr_Occurred())
2462 PyErr_SetString(PyExc_TypeError, error);
2463 return 0;
2464 }
2465 Py_DECREF(bases);
2466 return -1;
Walter Dörwaldd9a6ad32002-12-12 16:41:44 +00002467}
2468
Brett Cannon4f653312004-03-20 22:52:14 +00002469static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002470object_isinstance(PyObject *inst, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002471{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002472 PyObject *icls;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002473 int retval;
Benjamin Peterson9fc9bf42012-03-20 23:26:41 -04002474 _Py_IDENTIFIER(__class__);
Guido van Rossum03bc7d32003-02-12 03:32:58 +00002475
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002476 if (PyType_Check(cls)) {
2477 retval = PyObject_TypeCheck(inst, (PyTypeObject *)cls);
2478 if (retval == 0) {
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002479 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2480 if (icls != NULL) {
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002481 if (icls != (PyObject *)(Py_TYPE(inst)) && PyType_Check(icls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002482 retval = PyType_IsSubtype(
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002483 (PyTypeObject *)icls,
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002484 (PyTypeObject *)cls);
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002485 }
2486 else {
2487 retval = 0;
2488 }
2489 Py_DECREF(icls);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002490 }
2491 }
2492 }
2493 else {
2494 if (!check_class(cls,
Benjamin Petersone893af52010-06-28 19:43:42 +00002495 "isinstance() arg 2 must be a type or tuple of types"))
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002496 return -1;
Serhiy Storchakaf320be72018-01-25 10:49:40 +02002497 retval = _PyObject_LookupAttrId(inst, &PyId___class__, &icls);
2498 if (icls != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002499 retval = abstract_issubclass(icls, cls);
2500 Py_DECREF(icls);
2501 }
2502 }
Guido van Rossum823649d2001-03-21 18:40:58 +00002503
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002504 return retval;
Guido van Rossum823649d2001-03-21 18:40:58 +00002505}
2506
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002507static int
Victor Stinner850a4bd2020-02-04 13:42:13 +01002508object_recursive_isinstance(PyThreadState *tstate, PyObject *inst, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002509{
Benjamin Petersonce798522012-01-22 11:24:29 -05002510 _Py_IDENTIFIER(__instancecheck__);
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002511
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002512 /* Quick test for an exact match */
Andy Lesterdffe4c02020-03-04 07:15:20 -06002513 if (Py_IS_TYPE(inst, (PyTypeObject *)cls)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002514 return 1;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002515 }
Christian Heimesd5e2b6f2008-03-19 21:50:51 +00002516
Georg Brandl72b8a802014-10-03 09:26:37 +02002517 /* We know what type's __instancecheck__ does. */
2518 if (PyType_CheckExact(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002519 return object_isinstance(inst, cls);
Georg Brandl72b8a802014-10-03 09:26:37 +02002520 }
2521
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002522 if (PyTuple_Check(cls)) {
Victor Stinner850a4bd2020-02-04 13:42:13 +01002523 /* Not a general sequence -- that opens up the road to
2524 recursion and stack overflow. */
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002525 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002526 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002527 }
2528 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2529 int r = 0;
2530 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002531 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002532 r = object_recursive_isinstance(tstate, inst, item);
2533 if (r != 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002534 /* either found it, or got an error */
2535 break;
Victor Stinner850a4bd2020-02-04 13:42:13 +01002536 }
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002537 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002538 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002539 return r;
2540 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002541
Victor Stinner850a4bd2020-02-04 13:42:13 +01002542 PyObject *checker = _PyObject_LookupSpecial(cls, &PyId___instancecheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002543 if (checker != NULL) {
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002544 if (_Py_EnterRecursiveCall(tstate, " in __instancecheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002545 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002546 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002547 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002548
Petr Viktorinffd97532020-02-11 17:46:57 +01002549 PyObject *res = PyObject_CallOneArg(checker, inst);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002550 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002551 Py_DECREF(checker);
Victor Stinner850a4bd2020-02-04 13:42:13 +01002552
2553 if (res == NULL) {
2554 return -1;
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002555 }
Victor Stinner850a4bd2020-02-04 13:42:13 +01002556 int ok = PyObject_IsTrue(res);
2557 Py_DECREF(res);
2558
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002559 return ok;
2560 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002561 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002562 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002563 }
2564
Victor Stinner850a4bd2020-02-04 13:42:13 +01002565 /* cls has no __instancecheck__() method */
2566 return object_isinstance(inst, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002567}
2568
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002569
2570int
2571PyObject_IsInstance(PyObject *inst, PyObject *cls)
2572{
2573 PyThreadState *tstate = _PyThreadState_GET();
Victor Stinner850a4bd2020-02-04 13:42:13 +01002574 return object_recursive_isinstance(tstate, inst, cls);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002575}
2576
2577
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002578static int
Antoine Pitrouec569b72008-08-26 22:40:48 +00002579recursive_issubclass(PyObject *derived, PyObject *cls)
Guido van Rossum823649d2001-03-21 18:40:58 +00002580{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002581 if (PyType_Check(cls) && PyType_Check(derived)) {
2582 /* Fast path (non-recursive) */
2583 return PyType_IsSubtype((PyTypeObject *)derived, (PyTypeObject *)cls);
2584 }
2585 if (!check_class(derived,
2586 "issubclass() arg 1 must be a class"))
2587 return -1;
2588 if (!check_class(cls,
2589 "issubclass() arg 2 must be a class"
2590 " or tuple of classes"))
2591 return -1;
Guido van Rossum823649d2001-03-21 18:40:58 +00002592
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002593 return abstract_issubclass(derived, cls);
Guido van Rossum823649d2001-03-21 18:40:58 +00002594}
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002595
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002596static int
2597object_issubclass(PyThreadState *tstate, PyObject *derived, PyObject *cls)
Brett Cannon4f653312004-03-20 22:52:14 +00002598{
Benjamin Petersonce798522012-01-22 11:24:29 -05002599 _Py_IDENTIFIER(__subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002600 PyObject *checker;
Georg Brandldcfe8e42009-05-17 08:22:45 +00002601
Georg Brandl72b8a802014-10-03 09:26:37 +02002602 /* We know what type's __subclasscheck__ does. */
2603 if (PyType_CheckExact(cls)) {
2604 /* Quick test for an exact match */
2605 if (derived == cls)
2606 return 1;
2607 return recursive_issubclass(derived, cls);
2608 }
2609
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002610 if (PyTuple_Check(cls)) {
Antoine Pitrouec569b72008-08-26 22:40:48 +00002611
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002612 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002613 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002614 }
2615 Py_ssize_t n = PyTuple_GET_SIZE(cls);
2616 int r = 0;
2617 for (Py_ssize_t i = 0; i < n; ++i) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002618 PyObject *item = PyTuple_GET_ITEM(cls, i);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002619 r = object_issubclass(tstate, derived, item);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002620 if (r != 0)
2621 /* either found it, or got an error */
2622 break;
2623 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002624 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002625 return r;
2626 }
Benjamin Peterson88fe5f92009-05-16 21:55:24 +00002627
Benjamin Petersonce798522012-01-22 11:24:29 -05002628 checker = _PyObject_LookupSpecial(cls, &PyId___subclasscheck__);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002629 if (checker != NULL) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002630 int ok = -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002631 if (_Py_EnterRecursiveCall(tstate, " in __subclasscheck__")) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002632 Py_DECREF(checker);
2633 return ok;
2634 }
Petr Viktorinffd97532020-02-11 17:46:57 +01002635 PyObject *res = PyObject_CallOneArg(checker, derived);
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002636 _Py_LeaveRecursiveCall(tstate);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002637 Py_DECREF(checker);
2638 if (res != NULL) {
2639 ok = PyObject_IsTrue(res);
2640 Py_DECREF(res);
2641 }
2642 return ok;
2643 }
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002644 else if (_PyErr_Occurred(tstate)) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002645 return -1;
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002646 }
2647
Georg Brandl72b8a802014-10-03 09:26:37 +02002648 /* Probably never reached anymore. */
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002649 return recursive_issubclass(derived, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002650}
2651
Victor Stinnerbe434dc2019-11-05 00:51:22 +01002652
2653int
2654PyObject_IsSubclass(PyObject *derived, PyObject *cls)
2655{
2656 PyThreadState *tstate = _PyThreadState_GET();
2657 return object_issubclass(tstate, derived, cls);
2658}
2659
2660
Antoine Pitrouec569b72008-08-26 22:40:48 +00002661int
2662_PyObject_RealIsInstance(PyObject *inst, PyObject *cls)
2663{
Victor Stinner850a4bd2020-02-04 13:42:13 +01002664 return object_isinstance(inst, cls);
Antoine Pitrouec569b72008-08-26 22:40:48 +00002665}
2666
2667int
2668_PyObject_RealIsSubclass(PyObject *derived, PyObject *cls)
2669{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002670 return recursive_issubclass(derived, cls);
Brett Cannon4f653312004-03-20 22:52:14 +00002671}
2672
2673
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002674PyObject *
2675PyObject_GetIter(PyObject *o)
2676{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002677 PyTypeObject *t = Py_TYPE(o);
Victor Stinner14e6d092016-12-09 17:08:59 +01002678 getiterfunc f;
2679
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002680 f = t->tp_iter;
2681 if (f == NULL) {
2682 if (PySequence_Check(o))
2683 return PySeqIter_New(o);
2684 return type_error("'%.200s' object is not iterable", o);
2685 }
2686 else {
2687 PyObject *res = (*f)(o);
2688 if (res != NULL && !PyIter_Check(res)) {
2689 PyErr_Format(PyExc_TypeError,
2690 "iter() returned non-iterator "
2691 "of type '%.100s'",
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002692 Py_TYPE(res)->tp_name);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002693 Py_DECREF(res);
2694 res = NULL;
2695 }
2696 return res;
2697 }
Guido van Rossum213c7a62001-04-23 14:08:49 +00002698}
2699
Christian Tismerea62ce72018-06-09 20:32:25 +02002700#undef PyIter_Check
Christian Tismer83987132018-06-11 00:48:28 +02002701
Christian Tismerea62ce72018-06-09 20:32:25 +02002702int PyIter_Check(PyObject *obj)
2703{
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002704 return Py_TYPE(obj)->tp_iternext != NULL &&
2705 Py_TYPE(obj)->tp_iternext != &_PyObject_NextNotImplemented;
Christian Tismerea62ce72018-06-09 20:32:25 +02002706}
2707
Tim Petersf4848da2001-05-05 00:14:56 +00002708/* Return next item.
2709 * If an error occurs, return NULL. PyErr_Occurred() will be true.
2710 * If the iteration terminates normally, return NULL and clear the
2711 * PyExc_StopIteration exception (if it was set). PyErr_Occurred()
2712 * will be false.
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002713 * Else return the next object. PyErr_Occurred() will be false.
Tim Petersf4848da2001-05-05 00:14:56 +00002714 */
Guido van Rossum213c7a62001-04-23 14:08:49 +00002715PyObject *
2716PyIter_Next(PyObject *iter)
2717{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002718 PyObject *result;
Victor Stinner0d76d2b2020-02-07 01:53:23 +01002719 result = (*Py_TYPE(iter)->tp_iternext)(iter);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002720 if (result == NULL &&
2721 PyErr_Occurred() &&
2722 PyErr_ExceptionMatches(PyExc_StopIteration))
2723 PyErr_Clear();
2724 return result;
Guido van Rossum59d1d2b2001-04-20 19:13:02 +00002725}
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002726
2727
2728/*
2729 * Flatten a sequence of bytes() objects into a C array of
2730 * NULL terminated string pointers with a NULL char* terminating the array.
2731 * (ie: an argv or env list)
2732 *
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002733 * Memory allocated for the returned list is allocated using PyMem_Malloc()
2734 * and MUST be freed by _Py_FreeCharPArray().
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002735 */
2736char *const *
2737_PySequence_BytesToCharpArray(PyObject* self)
2738{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002739 char **array;
2740 Py_ssize_t i, argc;
2741 PyObject *item = NULL;
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002742 Py_ssize_t size;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002743
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002744 argc = PySequence_Size(self);
2745 if (argc == -1)
2746 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002747
Stefan Krah7cacd2e2012-08-21 08:16:09 +02002748 assert(argc >= 0);
2749
2750 if ((size_t)argc > (PY_SSIZE_T_MAX-sizeof(char *)) / sizeof(char *)) {
2751 PyErr_NoMemory();
2752 return NULL;
2753 }
2754
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002755 array = PyMem_Malloc((argc + 1) * sizeof(char *));
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002756 if (array == NULL) {
2757 PyErr_NoMemory();
2758 return NULL;
2759 }
2760 for (i = 0; i < argc; ++i) {
2761 char *data;
2762 item = PySequence_GetItem(self, i);
Stefan Krahfd24f9e2012-08-20 11:04:24 +02002763 if (item == NULL) {
2764 /* NULL terminate before freeing. */
2765 array[i] = NULL;
2766 goto fail;
2767 }
Serhiy Storchakad174d242017-06-23 19:39:27 +03002768 /* check for embedded null bytes */
2769 if (PyBytes_AsStringAndSize(item, &data, NULL) < 0) {
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002770 /* NULL terminate before freeing. */
2771 array[i] = NULL;
2772 goto fail;
2773 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002774 size = PyBytes_GET_SIZE(item) + 1;
2775 array[i] = PyMem_Malloc(size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002776 if (!array[i]) {
2777 PyErr_NoMemory();
2778 goto fail;
2779 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002780 memcpy(array[i], data, size);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002781 Py_DECREF(item);
2782 }
2783 array[argc] = NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002784
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002785 return array;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002786
2787fail:
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002788 Py_XDECREF(item);
2789 _Py_FreeCharPArray(array);
2790 return NULL;
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002791}
2792
2793
2794/* Free's a NULL terminated char** array of C strings. */
2795void
2796_Py_FreeCharPArray(char *const array[])
2797{
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002798 Py_ssize_t i;
2799 for (i = 0; array[i] != NULL; ++i) {
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002800 PyMem_Free(array[i]);
Antoine Pitrouf95a1b32010-05-09 15:52:27 +00002801 }
Victor Stinner0e2d3cf2013-07-07 17:22:41 +02002802 PyMem_Free((void*)array);
Gregory P. Smithfb94c5f2010-03-14 06:49:55 +00002803}