Skip to content

Commit 12da87b

Browse files
authored
[lldb] Use Python Bytes instead of Buffer for Binary I/O (NFC) (#152031)
Binary I/O (also called buffered I/O) expects bytes-like objects and produces bytes objects [1]. Switch from using a Python buffer to using Python bytes to read the data. This eliminates calls to functions that aren't part of the Python stable C API. [1] https://docs.python.org/3/library/io.html#binary-i-o
1 parent bb3c060 commit 12da87b

File tree

1 file changed

+6
-40
lines changed

1 file changed

+6
-40
lines changed

lldb/source/Plugins/ScriptInterpreter/Python/PythonDataObjects.cpp

Lines changed: 6 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -1093,40 +1093,6 @@ class SimplePythonFile : public OwnedPythonFile<NativeFile> {
10931093
char SimplePythonFile::ID = 0;
10941094
} // namespace
10951095

1096-
namespace {
1097-
class PythonBuffer {
1098-
public:
1099-
PythonBuffer &operator=(const PythonBuffer &) = delete;
1100-
PythonBuffer(const PythonBuffer &) = delete;
1101-
1102-
static Expected<PythonBuffer> Create(PythonObject &obj,
1103-
int flags = PyBUF_SIMPLE) {
1104-
Py_buffer py_buffer = {};
1105-
PyObject_GetBuffer(obj.get(), &py_buffer, flags);
1106-
if (!py_buffer.obj)
1107-
return llvm::make_error<PythonException>();
1108-
return PythonBuffer(py_buffer);
1109-
}
1110-
1111-
PythonBuffer(PythonBuffer &&other) {
1112-
m_buffer = other.m_buffer;
1113-
other.m_buffer.obj = nullptr;
1114-
}
1115-
1116-
~PythonBuffer() {
1117-
if (m_buffer.obj)
1118-
PyBuffer_Release(&m_buffer);
1119-
}
1120-
1121-
Py_buffer &get() { return m_buffer; }
1122-
1123-
private:
1124-
// takes ownership of the buffer.
1125-
PythonBuffer(const Py_buffer &py_buffer) : m_buffer(py_buffer) {}
1126-
Py_buffer m_buffer;
1127-
};
1128-
} // namespace
1129-
11301096
// Shared methods between TextPythonFile and BinaryPythonFile
11311097
namespace {
11321098
class PythonIOFile : public OwnedPythonFile<File> {
@@ -1220,12 +1186,12 @@ class BinaryPythonFile : public PythonIOFile {
12201186
num_bytes = 0;
12211187
return Status();
12221188
}
1223-
auto pybuffer = PythonBuffer::Create(pybuffer_obj.get());
1224-
if (!pybuffer)
1225-
// Cloning since the wrapped exception may still reference the PyThread.
1226-
return Status::FromError(pybuffer.takeError()).Clone();
1227-
memcpy(buf, pybuffer.get().get().buf, pybuffer.get().get().len);
1228-
num_bytes = pybuffer.get().get().len;
1189+
PythonBytes pybytes(PyRefType::Borrowed, pybuffer_obj->get());
1190+
if (!pybytes)
1191+
return Status::FromError(llvm::make_error<PythonException>());
1192+
llvm::ArrayRef<uint8_t> bytes = pybytes.GetBytes();
1193+
memcpy(buf, bytes.begin(), bytes.size());
1194+
num_bytes = bytes.size();
12291195
return Status();
12301196
}
12311197
};

0 commit comments

Comments
 (0)