Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Simplify python sequence marshaling #2912

Open
pepone opened this issue Oct 17, 2024 · 0 comments
Open

Simplify python sequence marshaling #2912

pepone opened this issue Oct 17, 2024 · 0 comments
Milestone

Comments

@pepone
Copy link
Member

pepone commented Oct 17, 2024

I think we can simplify the implementation of IcePy::SequenceInfo::marshal by computing the size of the optionals sequences, when we are about to marshal it and not up front.

We currently do it here:

if (optional)
{
if (elementType->variableLength())
{
sizePos = os->startSize();
}
else if (elementType->wireSize() > 1)
{
//
// Determine the sequence size.
//
Py_ssize_t sz = 0;
if (p != Py_None)
{
Py_buffer pybuf;
if (pi && PyObject_GetBuffer(p, &pybuf, PyBUF_SIMPLE | PyBUF_FORMAT) == 0)
{
// Strings are handled as variable length types above.
assert(pi->kind != PrimitiveInfo::KindString);
sz = pybuf.len;
PyBuffer_Release(&pybuf);
}
else
{
PyErr_Clear(); // PyObject_GetBuffer sets an exception on failure.
PyObjectHandle fs;
if (pi)
{
fs = PyObjectHandle{getSequence(pi, p)};
}
else
{
fs = PyObjectHandle{PySequence_Fast(p, "expected a sequence value")};
}
if (!fs.get())
{
assert(PyErr_Occurred());
return;
}
sz = PySequence_Fast_GET_SIZE(fs.get());
}
}
const int32_t isz = static_cast<int32_t>(sz);
os->writeSize(isz == 0 ? 1 : isz * elementType->wireSize() + (isz > 254 ? 5 : 1));
}
}

But seems it would be simpler to move this logic to:

if (p == Py_None)
{
os->writeSize(0);
}
else if (pi)
{
marshalPrimitiveSequence(pi, p, os);
}
else
{
PyObjectHandle fastSeq{PySequence_Fast(p, "expected a sequence value")};
if (!fastSeq.get())
{
return;
}
Py_ssize_t sz = PySequence_Fast_GET_SIZE(fastSeq.get());
os->writeSize(static_cast<int>(sz));
for (Py_ssize_t i = 0; i < sz; ++i)
{
PyObject* item = PySequence_Fast_GET_ITEM(fastSeq.get(), i);
if (!item)
{
assert(PyErr_Occurred());
throw AbortMarshaling();
}
if (!elementType->validate(item))
{
PyErr_Format(
PyExc_ValueError,
"invalid value for element %d of '%s'",
static_cast<int>(i),
const_cast<char*>(id.c_str()));
throw AbortMarshaling();
}
elementType->marshal(item, os, objectMap, false);
}
}

This would avoid creating the sequence handlers twice.

@pepone pepone added this to the 3.8.0 milestone Oct 17, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant