Skip to content

Commit f2d3ab8

Browse files
Add initial version of _PyTuple_FromPair
1 parent 4401f23 commit f2d3ab8

2 files changed

Lines changed: 56 additions & 0 deletions

File tree

Include/internal/pycore_tuple.h

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,9 @@ extern PyStatus _PyTuple_InitGlobalObjects(PyInterpreterState *);
2626
PyAPI_FUNC(PyObject *)_PyTuple_FromStackRefStealOnSuccess(const union _PyStackRef *, Py_ssize_t);
2727
PyAPI_FUNC(PyObject *)_PyTuple_FromArraySteal(PyObject *const *, Py_ssize_t);
2828

29+
PyAPI_FUNC(PyObject *)_PyTuple_FromPair(PyObject *, PyObject *);
30+
PyAPI_FUNC(PyObject *)_PyTuple_FromPairSteal(PyObject *, PyObject *);
31+
2932
typedef struct {
3033
PyObject_HEAD
3134
Py_ssize_t it_index;

Objects/tupleobject.c

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -202,6 +202,59 @@ PyTuple_Pack(Py_ssize_t n, ...)
202202
return (PyObject *)result;
203203
}
204204

205+
static PyTupleObject *
206+
tuple_alloc_2()
207+
{
208+
Py_ssize_t size = 2;
209+
Py_ssize_t index = size - 1;
210+
assert(index < PyTuple_MAXSAVESIZE);
211+
PyTupleObject *result = _Py_FREELIST_POP(PyTupleObject, tuples[index]);
212+
if (result == NULL) {
213+
result = PyObject_GC_NewVar(PyTupleObject, &PyTuple_Type, size);
214+
}
215+
if (result != NULL) {
216+
_PyTuple_RESET_HASH_CACHE(result);
217+
}
218+
return result;
219+
}
220+
221+
PyObject *
222+
_PyTuple_FromPair(PyObject *one, PyObject *two)
223+
{
224+
assert (one != NULL);
225+
assert (two != NULL);
226+
227+
PyTupleObject *op = tuple_alloc_2();
228+
if (op == NULL) {
229+
return NULL;
230+
}
231+
op->ob_item[0] = Py_NewRef(one);
232+
op->ob_item[1] = Py_NewRef(two);
233+
if (maybe_tracked(one) || maybe_tracked(two)) {
234+
_PyObject_GC_TRACK(op);
235+
}
236+
return (PyObject *)op;
237+
}
238+
239+
PyObject *
240+
_PyTuple_FromPairSteal(PyObject *one, PyObject *two)
241+
{
242+
assert (one != NULL);
243+
assert (two != NULL);
244+
245+
PyTupleObject *op = tuple_alloc_2();
246+
if (op == NULL) {
247+
Py_DECREF(one);
248+
Py_DECREF(two);
249+
return NULL;
250+
}
251+
op->ob_item[0] = one;
252+
op->ob_item[1] = two;
253+
if (maybe_tracked(one) || maybe_tracked(two)) {
254+
_PyObject_GC_TRACK(op);
255+
}
256+
return (PyObject *)op;
257+
}
205258

206259
/* Methods */
207260

0 commit comments

Comments
 (0)