A common interface to a Python file-like object. Must acquire GIL before calling any methods
| 43 | // A common interface to a Python file-like object. Must acquire GIL before |
| 44 | // calling any methods |
| 45 | class PythonFile { |
| 46 | public: |
| 47 | explicit PythonFile(PyObject* file) : file_(file), checked_read_buffer_(false) { |
| 48 | Py_INCREF(file); |
| 49 | } |
| 50 | |
| 51 | Status CheckClosed() const { |
| 52 | if (!file_) { |
| 53 | return Status::Invalid("operation on closed Python file"); |
| 54 | } |
| 55 | return Status::OK(); |
| 56 | } |
| 57 | |
| 58 | Status Close() { |
| 59 | if (file_) { |
| 60 | PyObject* result = cpp_PyObject_CallMethod(file_.obj(), "close", "()"); |
| 61 | Py_XDECREF(result); |
| 62 | file_.reset(); |
| 63 | PY_RETURN_IF_ERROR(StatusCode::IOError); |
| 64 | } |
| 65 | return Status::OK(); |
| 66 | } |
| 67 | |
| 68 | Status Abort() { |
| 69 | file_.reset(); |
| 70 | return Status::OK(); |
| 71 | } |
| 72 | |
| 73 | bool closed() const { |
| 74 | if (!file_) { |
| 75 | return true; |
| 76 | } |
| 77 | PyObject* result = PyObject_GetAttrString(file_.obj(), "closed"); |
| 78 | if (result == NULL) { |
| 79 | // Can't propagate the error, so write it out and return an arbitrary value |
| 80 | PyErr_WriteUnraisable(NULL); |
| 81 | return true; |
| 82 | } |
| 83 | int ret = PyObject_IsTrue(result); |
| 84 | Py_XDECREF(result); |
| 85 | if (ret < 0) { |
| 86 | PyErr_WriteUnraisable(NULL); |
| 87 | return true; |
| 88 | } |
| 89 | return ret != 0; |
| 90 | } |
| 91 | |
| 92 | Status Seek(int64_t position, int whence) { |
| 93 | RETURN_NOT_OK(CheckClosed()); |
| 94 | |
| 95 | // NOTE: `long long` is at least 64 bits in the C standard, the cast below is |
| 96 | // therefore safe. |
| 97 | |
| 98 | // whence: 0 for relative to start of file, 2 for end of file |
| 99 | PyObject* result = cpp_PyObject_CallMethod(file_.obj(), "seek", "(Li)", |
| 100 | static_cast<long long>(position), whence); |
| 101 | Py_XDECREF(result); |
| 102 | PY_RETURN_IF_ERROR(StatusCode::IOError); |
no outgoing calls
no test coverage detected