python_streambuf.hpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343
  1. #pragma once
  2. #include <cassert>
  3. #include <stdexcept>
  4. #include <iostream>
  5. #include <pybind11/pybind11.h>
  6. namespace xlnt {
  7. class python_streambuf : public std::basic_streambuf<char>
  8. {
  9. private:
  10. typedef std::basic_streambuf<char> base_t;
  11. public:
  12. /* The syntax
  13. using base_t::char_type;
  14. would be nicer but Visual Studio C++ 8 chokes on it
  15. */
  16. typedef base_t::char_type char_type;
  17. typedef base_t::int_type int_type;
  18. typedef base_t::pos_type pos_type;
  19. typedef base_t::off_type off_type;
  20. typedef base_t::traits_type traits_type;
  21. // work around Visual C++ 7.1 problem
  22. inline static int traits_type_eof()
  23. {
  24. return traits_type::eof();
  25. }
  26. /// The default size of the read and write buffer.
  27. /** They are respectively used to buffer data read from and data written to
  28. the Python file object. It can be modified from Python.
  29. */
  30. static std::size_t default_buffer_size;
  31. /// Construct from a Python file object
  32. /** if buffer_size is 0 the current default_buffer_size is used.
  33. */
  34. python_streambuf(
  35. pybind11::object python_file_obj,
  36. std::size_t buffer_size_ = 0)
  37. :
  38. py_read(python_file_obj.attr("read").cast<pybind11::function>()),
  39. py_write(python_file_obj.attr("write").cast<pybind11::function>()),
  40. py_seek(python_file_obj.attr("seek").cast<pybind11::function>()),
  41. py_tell(python_file_obj.attr("tell").cast<pybind11::function>()),
  42. buffer_size(buffer_size_ != 0 ? buffer_size_ : default_buffer_size),
  43. write_buffer(0),
  44. pos_of_read_buffer_end_in_py_file(0),
  45. pos_of_write_buffer_end_in_py_file(buffer_size),
  46. farthest_pptr(0)
  47. {
  48. assert(buffer_size != 0);
  49. /* Some Python file objects (e.g. sys.stdout and sys.stdin)
  50. have non-functional seek and tell. If so, assign None to
  51. py_tell and py_seek.
  52. */
  53. if (!py_tell.is_none())
  54. {
  55. try
  56. {
  57. py_tell();
  58. }
  59. catch(...)
  60. {
  61. py_tell = pybind11::none();
  62. }
  63. }
  64. if (!py_write.is_none())
  65. {
  66. // C-like string to make debugging easier
  67. write_buffer = new char[buffer_size + 1];
  68. write_buffer[buffer_size] = '\0';
  69. setp(write_buffer, write_buffer + buffer_size); // 27.5.2.4.5 (5)
  70. farthest_pptr = pptr();
  71. }
  72. else
  73. {
  74. // The first attempt at output will result in a call to overflow
  75. setp(0, 0);
  76. }
  77. if (!py_tell.is_none())
  78. {
  79. auto py_pos = py_tell().cast<pybind11::int_>();
  80. pos_of_read_buffer_end_in_py_file = py_pos;
  81. pos_of_write_buffer_end_in_py_file = py_pos;
  82. }
  83. }
  84. /// Mundane destructor freeing the allocated resources
  85. virtual ~python_streambuf() {
  86. if (write_buffer) delete[] write_buffer;
  87. }
  88. /// C.f. C++ standard section 27.5.2.4.3
  89. /** It is essential to override this virtual function for the stream
  90. member function readsome to work correctly (c.f. 27.6.1.3, alinea 30)
  91. */
  92. virtual std::streamsize showmanyc() {
  93. int_type const failure = traits_type::eof();
  94. int_type status = underflow();
  95. if (status == failure) return -1;
  96. return egptr() - gptr();
  97. }
  98. /// C.f. C++ standard section 27.5.2.4.3
  99. virtual int_type underflow() {
  100. int_type const failure = traits_type::eof();
  101. if (py_read.is_none()) {
  102. throw std::invalid_argument(
  103. "That Python file object has no 'read' attribute");
  104. }
  105. read_buffer = py_read(buffer_size).cast<pybind11::bytes>();
  106. char *read_buffer_data = nullptr;
  107. Py_ssize_t py_n_read = 0;
  108. if (PyBytes_AsStringAndSize(read_buffer.ptr(), &read_buffer_data, &py_n_read) == -1) {
  109. setg(0, 0, 0);
  110. throw std::invalid_argument(
  111. "The method 'read' of the Python file object "
  112. "did not return a string.");
  113. }
  114. auto n_read = (off_type)py_n_read;
  115. pos_of_read_buffer_end_in_py_file += n_read;
  116. setg(read_buffer_data, read_buffer_data, read_buffer_data + n_read);
  117. // ^^^27.5.2.3.1 (4)
  118. if (n_read == 0) return failure;
  119. return traits_type::to_int_type(read_buffer_data[0]);
  120. }
  121. /// C.f. C++ standard section 27.5.2.4.5
  122. virtual int_type overflow(int_type c=traits_type_eof()) {
  123. if (py_write.is_none()) {
  124. throw std::invalid_argument(
  125. "That Python file object has no 'write' attribute");
  126. }
  127. farthest_pptr = std::max(farthest_pptr, pptr());
  128. auto n_written = (off_type)(farthest_pptr - pbase());
  129. auto chunk = PyBytes_FromStringAndSize(pbase(), farthest_pptr - pbase());
  130. py_write(chunk);
  131. if (!traits_type::eq_int_type(c, traits_type::eof())) {
  132. auto ch = traits_type::to_char_type(c);
  133. py_write(reinterpret_cast<char *>(&ch), 1);
  134. n_written++;
  135. }
  136. if (n_written) {
  137. pos_of_write_buffer_end_in_py_file += n_written;
  138. setp(pbase(), epptr());
  139. // ^^^ 27.5.2.4.5 (5)
  140. farthest_pptr = pptr();
  141. }
  142. return traits_type::eq_int_type(
  143. c, traits_type::eof()) ? traits_type::not_eof(c) : c;
  144. }
  145. /// Update the python file to reflect the state of this stream buffer
  146. /** Empty the write buffer into the Python file object and set the seek
  147. position of the latter accordingly (C++ standard section 27.5.2.4.2).
  148. If there is no write buffer or it is empty, but there is a non-empty
  149. read buffer, set the Python file object seek position to the
  150. seek position in that read buffer.
  151. */
  152. virtual int sync() {
  153. int result = 0;
  154. farthest_pptr = std::max(farthest_pptr, pptr());
  155. if (farthest_pptr && farthest_pptr > pbase()) {
  156. off_type delta = pptr() - farthest_pptr;
  157. int_type status = overflow();
  158. if (traits_type::eq_int_type(status, traits_type::eof())) result = -1;
  159. if (!py_seek.is_none())
  160. {
  161. py_seek(delta);
  162. }
  163. }
  164. else if (gptr() && gptr() < egptr()) {
  165. if (!py_seek.is_none())
  166. {
  167. py_seek(gptr() - egptr(), 1);
  168. }
  169. }
  170. return result;
  171. }
  172. /// C.f. C++ standard section 27.5.2.4.2
  173. /** This implementation is optimised to look whether the position is within
  174. the buffers, so as to avoid calling Python seek or tell. It is
  175. important for many applications that the overhead of calling into Python
  176. is avoided as much as possible (e.g. parsers which may do a lot of
  177. backtracking)
  178. */
  179. virtual
  180. pos_type seekoff(off_type off, std::ios_base::seekdir way,
  181. std::ios_base::openmode which= std::ios_base::in
  182. | std::ios_base::out)
  183. {
  184. /* In practice, "which" is either std::ios_base::in or out
  185. since we end up here because either seekp or seekg was called
  186. on the stream using this buffer. That simplifies the code
  187. in a few places.
  188. */
  189. int const failure = off_type(-1);
  190. if (py_seek.is_none()) {
  191. throw std::invalid_argument(
  192. "That Python file object has no 'seek' attribute");
  193. }
  194. // we need the read buffer to contain something!
  195. if (which == std::ios_base::in && !gptr()) {
  196. if (traits_type::eq_int_type(underflow(), traits_type::eof())) {
  197. return failure;
  198. }
  199. }
  200. // compute the whence parameter for Python seek
  201. int whence;
  202. switch (way) {
  203. case std::ios_base::beg:
  204. whence = 0;
  205. break;
  206. case std::ios_base::cur:
  207. whence = 1;
  208. break;
  209. case std::ios_base::end:
  210. whence = 2;
  211. break;
  212. default:
  213. return failure;
  214. }
  215. // Let's have a go
  216. auto result = seekoff_without_calling_python(off, way, which);
  217. if (!result.second) {
  218. // we need to call Python
  219. if (which == std::ios_base::out) overflow();
  220. if (way == std::ios_base::cur) {
  221. if (which == std::ios_base::in) off -= egptr() - gptr();
  222. else if (which == std::ios_base::out) off += pptr() - pbase();
  223. }
  224. py_seek(off, whence);
  225. result.first = py_tell().cast<pybind11::int_>();
  226. if (which == std::ios_base::in) underflow();
  227. }
  228. return result.first;
  229. }
  230. /// C.f. C++ standard section 27.5.2.4.2
  231. virtual
  232. pos_type seekpos(pos_type sp,
  233. std::ios_base::openmode which= std::ios_base::in
  234. | std::ios_base::out)
  235. {
  236. return python_streambuf::seekoff(sp, std::ios_base::beg, which);
  237. }
  238. private:
  239. pybind11::function py_read;
  240. pybind11::function py_write;
  241. pybind11::function py_seek;
  242. pybind11::function py_tell;
  243. std::size_t buffer_size;
  244. /* This is actually a Python string and the actual read buffer is
  245. its internal data, i.e. an array of characters. We use a Boost.Python
  246. object so as to hold on it: as a result, the actual buffer can't
  247. go away.
  248. */
  249. pybind11::bytes read_buffer;
  250. /* A mere array of char's allocated on the heap at construction time and
  251. de-allocated only at destruction time.
  252. */
  253. char *write_buffer = nullptr;
  254. off_type pos_of_read_buffer_end_in_py_file,
  255. pos_of_write_buffer_end_in_py_file;
  256. // the farthest place the buffer has been written into
  257. char *farthest_pptr = nullptr;
  258. std::pair<off_type, bool> seekoff_without_calling_python(
  259. off_type off,
  260. std::ios_base::seekdir way,
  261. std::ios_base::openmode which)
  262. {
  263. const auto failure = std::make_pair<off_type, bool>(off_type(), false);
  264. // Buffer range and current position
  265. off_type buf_begin, buf_end, buf_cur, upper_bound;
  266. off_type pos_of_buffer_end_in_py_file;
  267. if (which == std::ios_base::in) {
  268. pos_of_buffer_end_in_py_file = pos_of_read_buffer_end_in_py_file;
  269. buf_begin = reinterpret_cast<std::streamsize>(eback());
  270. buf_cur = reinterpret_cast<std::streamsize>(gptr());
  271. buf_end = reinterpret_cast<std::streamsize>(egptr());
  272. upper_bound = buf_end;
  273. }
  274. else if (which == std::ios_base::out) {
  275. pos_of_buffer_end_in_py_file = pos_of_write_buffer_end_in_py_file;
  276. buf_begin = reinterpret_cast<std::streamsize>(pbase());
  277. buf_cur = reinterpret_cast<std::streamsize>(pptr());
  278. buf_end = reinterpret_cast<std::streamsize>(epptr());
  279. farthest_pptr = std::max(farthest_pptr, pptr());
  280. upper_bound = reinterpret_cast<std::streamsize>(farthest_pptr) + 1;
  281. }
  282. else {
  283. throw xlnt::exception("unreachable");
  284. }
  285. // Sought position in "buffer coordinate"
  286. off_type buf_sought;
  287. if (way == std::ios_base::cur) {
  288. buf_sought = buf_cur + off;
  289. }
  290. else if (way == std::ios_base::beg) {
  291. buf_sought = buf_end + (off - pos_of_buffer_end_in_py_file);
  292. }
  293. else if (way == std::ios_base::end) {
  294. return failure;
  295. }
  296. else {
  297. throw xlnt::exception("unreachable");
  298. }
  299. // if the sought position is not in the buffer, give up
  300. if (buf_sought < buf_begin || buf_sought >= upper_bound) return failure;
  301. // we are in wonderland
  302. if (which == std::ios_base::in) gbump(static_cast<int>(buf_sought - buf_cur));
  303. else if (which == std::ios_base::out) pbump(static_cast<int>(buf_sought - buf_cur));
  304. return std::make_pair<off_type, bool>(pos_of_buffer_end_in_py_file + (buf_sought - buf_end), true);
  305. }
  306. };
  307. std::size_t python_streambuf::default_buffer_size = 1024;
  308. } // namespace xlnt