| 57 | } |
| 58 | |
| 59 | PyObject* PersistencePy::dumpContent(PyObject* args, PyObject* kwds) const |
| 60 | { |
| 61 | int compression = 3; |
| 62 | static const std::array<const char*, 2> kwds_def {"Compression", nullptr}; |
| 63 | PyErr_Clear(); |
| 64 | if (!Wrapped_ParseTupleAndKeywords(args, kwds, "|i", kwds_def, &compression)) { |
| 65 | return nullptr; |
| 66 | } |
| 67 | |
| 68 | // setup the stream. the in flag is needed to make "read" work |
| 69 | std::stringstream stream( |
| 70 | std::stringstream::out | std::stringstream::in | std::stringstream::binary |
| 71 | ); |
| 72 | try { |
| 73 | getPersistencePtr()->dumpToStream(stream, compression); |
| 74 | } |
| 75 | catch (NotImplementedError&) { |
| 76 | PyErr_SetString( |
| 77 | PyExc_NotImplementedError, |
| 78 | "Dumping content of this object type is not implemented" |
| 79 | ); |
| 80 | return nullptr; |
| 81 | } |
| 82 | catch (...) { |
| 83 | PyErr_SetString(PyExc_IOError, "Unable to parse content into binary representation"); |
| 84 | return nullptr; |
| 85 | } |
| 86 | |
| 87 | // build the byte array with correct size |
| 88 | if (!stream.seekp(0, std::stringstream::end)) { |
| 89 | PyErr_SetString(PyExc_IOError, "Unable to find end of stream"); |
| 90 | return nullptr; |
| 91 | } |
| 92 | |
| 93 | std::stringstream::pos_type offset = stream.tellp(); |
| 94 | if (!stream.seekg(0, std::stringstream::beg)) { |
| 95 | PyErr_SetString(PyExc_IOError, "Unable to find begin of stream"); |
| 96 | return nullptr; |
| 97 | } |
| 98 | |
| 99 | PyObject* ba = PyByteArray_FromStringAndSize(nullptr, offset); |
| 100 | |
| 101 | // use the buffer protocol to access the underlying array and write into it |
| 102 | Py_buffer buf = Py_buffer(); |
| 103 | PyObject_GetBuffer(ba, &buf, PyBUF_WRITABLE); |
| 104 | try { |
| 105 | if (!stream.read((char*)buf.buf, offset)) { |
| 106 | PyErr_SetString(PyExc_IOError, "Error copying data into byte array"); |
| 107 | return nullptr; |
| 108 | } |
| 109 | PyBuffer_Release(&buf); |
| 110 | } |
| 111 | catch (...) { |
| 112 | PyBuffer_Release(&buf); |
| 113 | PyErr_SetString(PyExc_IOError, "Error copying data into byte array"); |
| 114 | return nullptr; |
| 115 | } |
| 116 | |