bytesio.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133
  1. #include "Python.h"
  2. #include "pycore_object.h"
  3. #include <stddef.h> // offsetof()
  4. #include "_iomodule.h"
  5. /*[clinic input]
  6. module _io
  7. class _io.BytesIO "bytesio *" "clinic_state()->PyBytesIO_Type"
  8. [clinic start generated code]*/
  9. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=48ede2f330f847c3]*/
  10. typedef struct {
  11. PyObject_HEAD
  12. PyObject *buf;
  13. Py_ssize_t pos;
  14. Py_ssize_t string_size;
  15. PyObject *dict;
  16. PyObject *weakreflist;
  17. Py_ssize_t exports;
  18. } bytesio;
  19. typedef struct {
  20. PyObject_HEAD
  21. bytesio *source;
  22. } bytesiobuf;
  23. /* The bytesio object can be in three states:
  24. * Py_REFCNT(buf) == 1, exports == 0.
  25. * Py_REFCNT(buf) > 1. exports == 0,
  26. first modification or export causes the internal buffer copying.
  27. * exports > 0. Py_REFCNT(buf) == 1, any modifications are forbidden.
  28. */
  29. static int
  30. check_closed(bytesio *self)
  31. {
  32. if (self->buf == NULL) {
  33. PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
  34. return 1;
  35. }
  36. return 0;
  37. }
  38. static int
  39. check_exports(bytesio *self)
  40. {
  41. if (self->exports > 0) {
  42. PyErr_SetString(PyExc_BufferError,
  43. "Existing exports of data: object cannot be re-sized");
  44. return 1;
  45. }
  46. return 0;
  47. }
  48. #define CHECK_CLOSED(self) \
  49. if (check_closed(self)) { \
  50. return NULL; \
  51. }
  52. #define CHECK_EXPORTS(self) \
  53. if (check_exports(self)) { \
  54. return NULL; \
  55. }
  56. #define SHARED_BUF(self) (Py_REFCNT((self)->buf) > 1)
  57. /* Internal routine to get a line from the buffer of a BytesIO
  58. object. Returns the length between the current position to the
  59. next newline character. */
  60. static Py_ssize_t
  61. scan_eol(bytesio *self, Py_ssize_t len)
  62. {
  63. const char *start, *n;
  64. Py_ssize_t maxlen;
  65. assert(self->buf != NULL);
  66. assert(self->pos >= 0);
  67. if (self->pos >= self->string_size)
  68. return 0;
  69. /* Move to the end of the line, up to the end of the string, s. */
  70. maxlen = self->string_size - self->pos;
  71. if (len < 0 || len > maxlen)
  72. len = maxlen;
  73. if (len) {
  74. start = PyBytes_AS_STRING(self->buf) + self->pos;
  75. n = memchr(start, '\n', len);
  76. if (n)
  77. /* Get the length from the current position to the end of
  78. the line. */
  79. len = n - start + 1;
  80. }
  81. assert(len >= 0);
  82. assert(self->pos < PY_SSIZE_T_MAX - len);
  83. return len;
  84. }
  85. /* Internal routine for detaching the shared buffer of BytesIO objects.
  86. The caller should ensure that the 'size' argument is non-negative and
  87. not lesser than self->string_size. Returns 0 on success, -1 otherwise. */
  88. static int
  89. unshare_buffer(bytesio *self, size_t size)
  90. {
  91. PyObject *new_buf;
  92. assert(SHARED_BUF(self));
  93. assert(self->exports == 0);
  94. assert(size >= (size_t)self->string_size);
  95. new_buf = PyBytes_FromStringAndSize(NULL, size);
  96. if (new_buf == NULL)
  97. return -1;
  98. memcpy(PyBytes_AS_STRING(new_buf), PyBytes_AS_STRING(self->buf),
  99. self->string_size);
  100. Py_SETREF(self->buf, new_buf);
  101. return 0;
  102. }
  103. /* Internal routine for changing the size of the buffer of BytesIO objects.
  104. The caller should ensure that the 'size' argument is non-negative. Returns
  105. 0 on success, -1 otherwise. */
  106. static int
  107. resize_buffer(bytesio *self, size_t size)
  108. {
  109. assert(self->buf != NULL);
  110. assert(self->exports == 0);
  111. /* Here, unsigned types are used to avoid dealing with signed integer
  112. overflow, which is undefined in C. */
  113. size_t alloc = PyBytes_GET_SIZE(self->buf);
  114. /* For simplicity, stay in the range of the signed type. Anyway, Python
  115. doesn't allow strings to be longer than this. */
  116. if (size > PY_SSIZE_T_MAX)
  117. goto overflow;
  118. if (size < alloc / 2) {
  119. /* Major downsize; resize down to exact size. */
  120. alloc = size + 1;
  121. }
  122. else if (size < alloc) {
  123. /* Within allocated size; quick exit */
  124. return 0;
  125. }
  126. else if (size <= alloc * 1.125) {
  127. /* Moderate upsize; overallocate similar to list_resize() */
  128. alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
  129. }
  130. else {
  131. /* Major upsize; resize up to exact size */
  132. alloc = size + 1;
  133. }
  134. if (alloc > ((size_t)-1) / sizeof(char))
  135. goto overflow;
  136. if (SHARED_BUF(self)) {
  137. if (unshare_buffer(self, alloc) < 0)
  138. return -1;
  139. }
  140. else {
  141. if (_PyBytes_Resize(&self->buf, alloc) < 0)
  142. return -1;
  143. }
  144. return 0;
  145. overflow:
  146. PyErr_SetString(PyExc_OverflowError,
  147. "new buffer size too large");
  148. return -1;
  149. }
  150. /* Internal routine for writing a string of bytes to the buffer of a BytesIO
  151. object. Returns the number of bytes written, or -1 on error.
  152. Inlining is disabled because it's significantly decreases performance
  153. of writelines() in PGO build. */
  154. Py_NO_INLINE static Py_ssize_t
  155. write_bytes(bytesio *self, PyObject *b)
  156. {
  157. if (check_closed(self)) {
  158. return -1;
  159. }
  160. if (check_exports(self)) {
  161. return -1;
  162. }
  163. Py_buffer buf;
  164. if (PyObject_GetBuffer(b, &buf, PyBUF_CONTIG_RO) < 0) {
  165. return -1;
  166. }
  167. Py_ssize_t len = buf.len;
  168. if (len == 0) {
  169. goto done;
  170. }
  171. assert(self->pos >= 0);
  172. size_t endpos = (size_t)self->pos + len;
  173. if (endpos > (size_t)PyBytes_GET_SIZE(self->buf)) {
  174. if (resize_buffer(self, endpos) < 0) {
  175. len = -1;
  176. goto done;
  177. }
  178. }
  179. else if (SHARED_BUF(self)) {
  180. if (unshare_buffer(self, Py_MAX(endpos, (size_t)self->string_size)) < 0) {
  181. len = -1;
  182. goto done;
  183. }
  184. }
  185. if (self->pos > self->string_size) {
  186. /* In case of overseek, pad with null bytes the buffer region between
  187. the end of stream and the current position.
  188. 0 lo string_size hi
  189. | |<---used--->|<----------available----------->|
  190. | | <--to pad-->|<---to write---> |
  191. 0 buf position
  192. */
  193. memset(PyBytes_AS_STRING(self->buf) + self->string_size, '\0',
  194. (self->pos - self->string_size) * sizeof(char));
  195. }
  196. /* Copy the data to the internal buffer, overwriting some of the existing
  197. data if self->pos < self->string_size. */
  198. memcpy(PyBytes_AS_STRING(self->buf) + self->pos, buf.buf, len);
  199. self->pos = endpos;
  200. /* Set the new length of the internal string if it has changed. */
  201. if ((size_t)self->string_size < endpos) {
  202. self->string_size = endpos;
  203. }
  204. done:
  205. PyBuffer_Release(&buf);
  206. return len;
  207. }
  208. static PyObject *
  209. bytesio_get_closed(bytesio *self, void *Py_UNUSED(ignored))
  210. {
  211. if (self->buf == NULL) {
  212. Py_RETURN_TRUE;
  213. }
  214. else {
  215. Py_RETURN_FALSE;
  216. }
  217. }
  218. /*[clinic input]
  219. _io.BytesIO.readable
  220. Returns True if the IO object can be read.
  221. [clinic start generated code]*/
  222. static PyObject *
  223. _io_BytesIO_readable_impl(bytesio *self)
  224. /*[clinic end generated code: output=4e93822ad5b62263 input=96c5d0cccfb29f5c]*/
  225. {
  226. CHECK_CLOSED(self);
  227. Py_RETURN_TRUE;
  228. }
  229. /*[clinic input]
  230. _io.BytesIO.writable
  231. Returns True if the IO object can be written.
  232. [clinic start generated code]*/
  233. static PyObject *
  234. _io_BytesIO_writable_impl(bytesio *self)
  235. /*[clinic end generated code: output=64ff6a254b1150b8 input=700eed808277560a]*/
  236. {
  237. CHECK_CLOSED(self);
  238. Py_RETURN_TRUE;
  239. }
  240. /*[clinic input]
  241. _io.BytesIO.seekable
  242. Returns True if the IO object can be seeked.
  243. [clinic start generated code]*/
  244. static PyObject *
  245. _io_BytesIO_seekable_impl(bytesio *self)
  246. /*[clinic end generated code: output=6b417f46dcc09b56 input=9421f65627a344dd]*/
  247. {
  248. CHECK_CLOSED(self);
  249. Py_RETURN_TRUE;
  250. }
  251. /*[clinic input]
  252. _io.BytesIO.flush
  253. Does nothing.
  254. [clinic start generated code]*/
  255. static PyObject *
  256. _io_BytesIO_flush_impl(bytesio *self)
  257. /*[clinic end generated code: output=187e3d781ca134a0 input=561ea490be4581a7]*/
  258. {
  259. CHECK_CLOSED(self);
  260. Py_RETURN_NONE;
  261. }
  262. /*[clinic input]
  263. _io.BytesIO.getbuffer
  264. cls: defining_class
  265. /
  266. Get a read-write view over the contents of the BytesIO object.
  267. [clinic start generated code]*/
  268. static PyObject *
  269. _io_BytesIO_getbuffer_impl(bytesio *self, PyTypeObject *cls)
  270. /*[clinic end generated code: output=045091d7ce87fe4e input=0668fbb48f95dffa]*/
  271. {
  272. _PyIO_State *state = get_io_state_by_cls(cls);
  273. PyTypeObject *type = state->PyBytesIOBuffer_Type;
  274. bytesiobuf *buf;
  275. PyObject *view;
  276. CHECK_CLOSED(self);
  277. buf = (bytesiobuf *) type->tp_alloc(type, 0);
  278. if (buf == NULL)
  279. return NULL;
  280. buf->source = (bytesio*)Py_NewRef(self);
  281. view = PyMemoryView_FromObject((PyObject *) buf);
  282. Py_DECREF(buf);
  283. return view;
  284. }
  285. /*[clinic input]
  286. _io.BytesIO.getvalue
  287. Retrieve the entire contents of the BytesIO object.
  288. [clinic start generated code]*/
  289. static PyObject *
  290. _io_BytesIO_getvalue_impl(bytesio *self)
  291. /*[clinic end generated code: output=b3f6a3233c8fd628 input=4b403ac0af3973ed]*/
  292. {
  293. CHECK_CLOSED(self);
  294. if (self->string_size <= 1 || self->exports > 0)
  295. return PyBytes_FromStringAndSize(PyBytes_AS_STRING(self->buf),
  296. self->string_size);
  297. if (self->string_size != PyBytes_GET_SIZE(self->buf)) {
  298. if (SHARED_BUF(self)) {
  299. if (unshare_buffer(self, self->string_size) < 0)
  300. return NULL;
  301. }
  302. else {
  303. if (_PyBytes_Resize(&self->buf, self->string_size) < 0)
  304. return NULL;
  305. }
  306. }
  307. return Py_NewRef(self->buf);
  308. }
  309. /*[clinic input]
  310. _io.BytesIO.isatty
  311. Always returns False.
  312. BytesIO objects are not connected to a TTY-like device.
  313. [clinic start generated code]*/
  314. static PyObject *
  315. _io_BytesIO_isatty_impl(bytesio *self)
  316. /*[clinic end generated code: output=df67712e669f6c8f input=6f97f0985d13f827]*/
  317. {
  318. CHECK_CLOSED(self);
  319. Py_RETURN_FALSE;
  320. }
  321. /*[clinic input]
  322. _io.BytesIO.tell
  323. Current file position, an integer.
  324. [clinic start generated code]*/
  325. static PyObject *
  326. _io_BytesIO_tell_impl(bytesio *self)
  327. /*[clinic end generated code: output=b54b0f93cd0e5e1d input=b106adf099cb3657]*/
  328. {
  329. CHECK_CLOSED(self);
  330. return PyLong_FromSsize_t(self->pos);
  331. }
  332. static PyObject *
  333. read_bytes(bytesio *self, Py_ssize_t size)
  334. {
  335. const char *output;
  336. assert(self->buf != NULL);
  337. assert(size <= self->string_size);
  338. if (size > 1 &&
  339. self->pos == 0 && size == PyBytes_GET_SIZE(self->buf) &&
  340. self->exports == 0) {
  341. self->pos += size;
  342. return Py_NewRef(self->buf);
  343. }
  344. output = PyBytes_AS_STRING(self->buf) + self->pos;
  345. self->pos += size;
  346. return PyBytes_FromStringAndSize(output, size);
  347. }
  348. /*[clinic input]
  349. _io.BytesIO.read
  350. size: Py_ssize_t(accept={int, NoneType}) = -1
  351. /
  352. Read at most size bytes, returned as a bytes object.
  353. If the size argument is negative, read until EOF is reached.
  354. Return an empty bytes object at EOF.
  355. [clinic start generated code]*/
  356. static PyObject *
  357. _io_BytesIO_read_impl(bytesio *self, Py_ssize_t size)
  358. /*[clinic end generated code: output=9cc025f21c75bdd2 input=74344a39f431c3d7]*/
  359. {
  360. Py_ssize_t n;
  361. CHECK_CLOSED(self);
  362. /* adjust invalid sizes */
  363. n = self->string_size - self->pos;
  364. if (size < 0 || size > n) {
  365. size = n;
  366. if (size < 0)
  367. size = 0;
  368. }
  369. return read_bytes(self, size);
  370. }
  371. /*[clinic input]
  372. _io.BytesIO.read1
  373. size: Py_ssize_t(accept={int, NoneType}) = -1
  374. /
  375. Read at most size bytes, returned as a bytes object.
  376. If the size argument is negative or omitted, read until EOF is reached.
  377. Return an empty bytes object at EOF.
  378. [clinic start generated code]*/
  379. static PyObject *
  380. _io_BytesIO_read1_impl(bytesio *self, Py_ssize_t size)
  381. /*[clinic end generated code: output=d0f843285aa95f1c input=440a395bf9129ef5]*/
  382. {
  383. return _io_BytesIO_read_impl(self, size);
  384. }
  385. /*[clinic input]
  386. _io.BytesIO.readline
  387. size: Py_ssize_t(accept={int, NoneType}) = -1
  388. /
  389. Next line from the file, as a bytes object.
  390. Retain newline. A non-negative size argument limits the maximum
  391. number of bytes to return (an incomplete line may be returned then).
  392. Return an empty bytes object at EOF.
  393. [clinic start generated code]*/
  394. static PyObject *
  395. _io_BytesIO_readline_impl(bytesio *self, Py_ssize_t size)
  396. /*[clinic end generated code: output=4bff3c251df8ffcd input=e7c3fbd1744e2783]*/
  397. {
  398. Py_ssize_t n;
  399. CHECK_CLOSED(self);
  400. n = scan_eol(self, size);
  401. return read_bytes(self, n);
  402. }
  403. /*[clinic input]
  404. _io.BytesIO.readlines
  405. size as arg: object = None
  406. /
  407. List of bytes objects, each a line from the file.
  408. Call readline() repeatedly and return a list of the lines so read.
  409. The optional size argument, if given, is an approximate bound on the
  410. total number of bytes in the lines returned.
  411. [clinic start generated code]*/
  412. static PyObject *
  413. _io_BytesIO_readlines_impl(bytesio *self, PyObject *arg)
  414. /*[clinic end generated code: output=09b8e34c880808ff input=691aa1314f2c2a87]*/
  415. {
  416. Py_ssize_t maxsize, size, n;
  417. PyObject *result, *line;
  418. const char *output;
  419. CHECK_CLOSED(self);
  420. if (PyLong_Check(arg)) {
  421. maxsize = PyLong_AsSsize_t(arg);
  422. if (maxsize == -1 && PyErr_Occurred())
  423. return NULL;
  424. }
  425. else if (arg == Py_None) {
  426. /* No size limit, by default. */
  427. maxsize = -1;
  428. }
  429. else {
  430. PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
  431. Py_TYPE(arg)->tp_name);
  432. return NULL;
  433. }
  434. size = 0;
  435. result = PyList_New(0);
  436. if (!result)
  437. return NULL;
  438. output = PyBytes_AS_STRING(self->buf) + self->pos;
  439. while ((n = scan_eol(self, -1)) != 0) {
  440. self->pos += n;
  441. line = PyBytes_FromStringAndSize(output, n);
  442. if (!line)
  443. goto on_error;
  444. if (PyList_Append(result, line) == -1) {
  445. Py_DECREF(line);
  446. goto on_error;
  447. }
  448. Py_DECREF(line);
  449. size += n;
  450. if (maxsize > 0 && size >= maxsize)
  451. break;
  452. output += n;
  453. }
  454. return result;
  455. on_error:
  456. Py_DECREF(result);
  457. return NULL;
  458. }
  459. /*[clinic input]
  460. _io.BytesIO.readinto
  461. buffer: Py_buffer(accept={rwbuffer})
  462. /
  463. Read bytes into buffer.
  464. Returns number of bytes read (0 for EOF), or None if the object
  465. is set not to block and has no data to read.
  466. [clinic start generated code]*/
  467. static PyObject *
  468. _io_BytesIO_readinto_impl(bytesio *self, Py_buffer *buffer)
  469. /*[clinic end generated code: output=a5d407217dcf0639 input=1424d0fdce857919]*/
  470. {
  471. Py_ssize_t len, n;
  472. CHECK_CLOSED(self);
  473. /* adjust invalid sizes */
  474. len = buffer->len;
  475. n = self->string_size - self->pos;
  476. if (len > n) {
  477. len = n;
  478. if (len < 0)
  479. len = 0;
  480. }
  481. memcpy(buffer->buf, PyBytes_AS_STRING(self->buf) + self->pos, len);
  482. assert(self->pos + len < PY_SSIZE_T_MAX);
  483. assert(len >= 0);
  484. self->pos += len;
  485. return PyLong_FromSsize_t(len);
  486. }
  487. /*[clinic input]
  488. _io.BytesIO.truncate
  489. size: Py_ssize_t(accept={int, NoneType}, c_default="self->pos") = None
  490. /
  491. Truncate the file to at most size bytes.
  492. Size defaults to the current file position, as returned by tell().
  493. The current file position is unchanged. Returns the new size.
  494. [clinic start generated code]*/
  495. static PyObject *
  496. _io_BytesIO_truncate_impl(bytesio *self, Py_ssize_t size)
  497. /*[clinic end generated code: output=9ad17650c15fa09b input=423759dd42d2f7c1]*/
  498. {
  499. CHECK_CLOSED(self);
  500. CHECK_EXPORTS(self);
  501. if (size < 0) {
  502. PyErr_Format(PyExc_ValueError,
  503. "negative size value %zd", size);
  504. return NULL;
  505. }
  506. if (size < self->string_size) {
  507. self->string_size = size;
  508. if (resize_buffer(self, size) < 0)
  509. return NULL;
  510. }
  511. return PyLong_FromSsize_t(size);
  512. }
  513. static PyObject *
  514. bytesio_iternext(bytesio *self)
  515. {
  516. Py_ssize_t n;
  517. CHECK_CLOSED(self);
  518. n = scan_eol(self, -1);
  519. if (n == 0)
  520. return NULL;
  521. return read_bytes(self, n);
  522. }
  523. /*[clinic input]
  524. _io.BytesIO.seek
  525. pos: Py_ssize_t
  526. whence: int = 0
  527. /
  528. Change stream position.
  529. Seek to byte offset pos relative to position indicated by whence:
  530. 0 Start of stream (the default). pos should be >= 0;
  531. 1 Current position - pos may be negative;
  532. 2 End of stream - pos usually negative.
  533. Returns the new absolute position.
  534. [clinic start generated code]*/
  535. static PyObject *
  536. _io_BytesIO_seek_impl(bytesio *self, Py_ssize_t pos, int whence)
  537. /*[clinic end generated code: output=c26204a68e9190e4 input=1e875e6ebc652948]*/
  538. {
  539. CHECK_CLOSED(self);
  540. if (pos < 0 && whence == 0) {
  541. PyErr_Format(PyExc_ValueError,
  542. "negative seek value %zd", pos);
  543. return NULL;
  544. }
  545. /* whence = 0: offset relative to beginning of the string.
  546. whence = 1: offset relative to current position.
  547. whence = 2: offset relative the end of the string. */
  548. if (whence == 1) {
  549. if (pos > PY_SSIZE_T_MAX - self->pos) {
  550. PyErr_SetString(PyExc_OverflowError,
  551. "new position too large");
  552. return NULL;
  553. }
  554. pos += self->pos;
  555. }
  556. else if (whence == 2) {
  557. if (pos > PY_SSIZE_T_MAX - self->string_size) {
  558. PyErr_SetString(PyExc_OverflowError,
  559. "new position too large");
  560. return NULL;
  561. }
  562. pos += self->string_size;
  563. }
  564. else if (whence != 0) {
  565. PyErr_Format(PyExc_ValueError,
  566. "invalid whence (%i, should be 0, 1 or 2)", whence);
  567. return NULL;
  568. }
  569. if (pos < 0)
  570. pos = 0;
  571. self->pos = pos;
  572. return PyLong_FromSsize_t(self->pos);
  573. }
  574. /*[clinic input]
  575. _io.BytesIO.write
  576. b: object
  577. /
  578. Write bytes to file.
  579. Return the number of bytes written.
  580. [clinic start generated code]*/
  581. static PyObject *
  582. _io_BytesIO_write(bytesio *self, PyObject *b)
  583. /*[clinic end generated code: output=53316d99800a0b95 input=f5ec7c8c64ed720a]*/
  584. {
  585. Py_ssize_t n = write_bytes(self, b);
  586. return n >= 0 ? PyLong_FromSsize_t(n) : NULL;
  587. }
  588. /*[clinic input]
  589. _io.BytesIO.writelines
  590. lines: object
  591. /
  592. Write lines to the file.
  593. Note that newlines are not added. lines can be any iterable object
  594. producing bytes-like objects. This is equivalent to calling write() for
  595. each element.
  596. [clinic start generated code]*/
  597. static PyObject *
  598. _io_BytesIO_writelines(bytesio *self, PyObject *lines)
  599. /*[clinic end generated code: output=7f33aa3271c91752 input=e972539176fc8fc1]*/
  600. {
  601. PyObject *it, *item;
  602. CHECK_CLOSED(self);
  603. it = PyObject_GetIter(lines);
  604. if (it == NULL)
  605. return NULL;
  606. while ((item = PyIter_Next(it)) != NULL) {
  607. Py_ssize_t ret = write_bytes(self, item);
  608. Py_DECREF(item);
  609. if (ret < 0) {
  610. Py_DECREF(it);
  611. return NULL;
  612. }
  613. }
  614. Py_DECREF(it);
  615. /* See if PyIter_Next failed */
  616. if (PyErr_Occurred())
  617. return NULL;
  618. Py_RETURN_NONE;
  619. }
  620. /*[clinic input]
  621. _io.BytesIO.close
  622. Disable all I/O operations.
  623. [clinic start generated code]*/
  624. static PyObject *
  625. _io_BytesIO_close_impl(bytesio *self)
  626. /*[clinic end generated code: output=1471bb9411af84a0 input=37e1f55556e61f60]*/
  627. {
  628. CHECK_EXPORTS(self);
  629. Py_CLEAR(self->buf);
  630. Py_RETURN_NONE;
  631. }
  632. /* Pickling support.
  633. Note that only pickle protocol 2 and onward are supported since we use
  634. extended __reduce__ API of PEP 307 to make BytesIO instances picklable.
  635. Providing support for protocol < 2 would require the __reduce_ex__ method
  636. which is notably long-winded when defined properly.
  637. For BytesIO, the implementation would similar to one coded for
  638. object.__reduce_ex__, but slightly less general. To be more specific, we
  639. could call bytesio_getstate directly and avoid checking for the presence of
  640. a fallback __reduce__ method. However, we would still need a __newobj__
  641. function to use the efficient instance representation of PEP 307.
  642. */
  643. static PyObject *
  644. bytesio_getstate(bytesio *self, PyObject *Py_UNUSED(ignored))
  645. {
  646. PyObject *initvalue = _io_BytesIO_getvalue_impl(self);
  647. PyObject *dict;
  648. PyObject *state;
  649. if (initvalue == NULL)
  650. return NULL;
  651. if (self->dict == NULL) {
  652. dict = Py_NewRef(Py_None);
  653. }
  654. else {
  655. dict = PyDict_Copy(self->dict);
  656. if (dict == NULL) {
  657. Py_DECREF(initvalue);
  658. return NULL;
  659. }
  660. }
  661. state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);
  662. Py_DECREF(initvalue);
  663. return state;
  664. }
  665. static PyObject *
  666. bytesio_setstate(bytesio *self, PyObject *state)
  667. {
  668. PyObject *result;
  669. PyObject *position_obj;
  670. PyObject *dict;
  671. Py_ssize_t pos;
  672. assert(state != NULL);
  673. /* We allow the state tuple to be longer than 3, because we may need
  674. someday to extend the object's state without breaking
  675. backward-compatibility. */
  676. if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) < 3) {
  677. PyErr_Format(PyExc_TypeError,
  678. "%.200s.__setstate__ argument should be 3-tuple, got %.200s",
  679. Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
  680. return NULL;
  681. }
  682. CHECK_EXPORTS(self);
  683. /* Reset the object to its default state. This is only needed to handle
  684. the case of repeated calls to __setstate__. */
  685. self->string_size = 0;
  686. self->pos = 0;
  687. /* Set the value of the internal buffer. If state[0] does not support the
  688. buffer protocol, bytesio_write will raise the appropriate TypeError. */
  689. result = _io_BytesIO_write(self, PyTuple_GET_ITEM(state, 0));
  690. if (result == NULL)
  691. return NULL;
  692. Py_DECREF(result);
  693. /* Set carefully the position value. Alternatively, we could use the seek
  694. method instead of modifying self->pos directly to better protect the
  695. object internal state against erroneous (or malicious) inputs. */
  696. position_obj = PyTuple_GET_ITEM(state, 1);
  697. if (!PyLong_Check(position_obj)) {
  698. PyErr_Format(PyExc_TypeError,
  699. "second item of state must be an integer, not %.200s",
  700. Py_TYPE(position_obj)->tp_name);
  701. return NULL;
  702. }
  703. pos = PyLong_AsSsize_t(position_obj);
  704. if (pos == -1 && PyErr_Occurred())
  705. return NULL;
  706. if (pos < 0) {
  707. PyErr_SetString(PyExc_ValueError,
  708. "position value cannot be negative");
  709. return NULL;
  710. }
  711. self->pos = pos;
  712. /* Set the dictionary of the instance variables. */
  713. dict = PyTuple_GET_ITEM(state, 2);
  714. if (dict != Py_None) {
  715. if (!PyDict_Check(dict)) {
  716. PyErr_Format(PyExc_TypeError,
  717. "third item of state should be a dict, got a %.200s",
  718. Py_TYPE(dict)->tp_name);
  719. return NULL;
  720. }
  721. if (self->dict) {
  722. /* Alternatively, we could replace the internal dictionary
  723. completely. However, it seems more practical to just update it. */
  724. if (PyDict_Update(self->dict, dict) < 0)
  725. return NULL;
  726. }
  727. else {
  728. self->dict = Py_NewRef(dict);
  729. }
  730. }
  731. Py_RETURN_NONE;
  732. }
  733. static void
  734. bytesio_dealloc(bytesio *self)
  735. {
  736. PyTypeObject *tp = Py_TYPE(self);
  737. _PyObject_GC_UNTRACK(self);
  738. if (self->exports > 0) {
  739. PyErr_SetString(PyExc_SystemError,
  740. "deallocated BytesIO object has exported buffers");
  741. PyErr_Print();
  742. }
  743. Py_CLEAR(self->buf);
  744. Py_CLEAR(self->dict);
  745. if (self->weakreflist != NULL)
  746. PyObject_ClearWeakRefs((PyObject *) self);
  747. tp->tp_free(self);
  748. Py_DECREF(tp);
  749. }
  750. static PyObject *
  751. bytesio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  752. {
  753. bytesio *self;
  754. assert(type != NULL && type->tp_alloc != NULL);
  755. self = (bytesio *)type->tp_alloc(type, 0);
  756. if (self == NULL)
  757. return NULL;
  758. /* tp_alloc initializes all the fields to zero. So we don't have to
  759. initialize them here. */
  760. self->buf = PyBytes_FromStringAndSize(NULL, 0);
  761. if (self->buf == NULL) {
  762. Py_DECREF(self);
  763. return PyErr_NoMemory();
  764. }
  765. return (PyObject *)self;
  766. }
  767. /*[clinic input]
  768. _io.BytesIO.__init__
  769. initial_bytes as initvalue: object(c_default="NULL") = b''
  770. Buffered I/O implementation using an in-memory bytes buffer.
  771. [clinic start generated code]*/
  772. static int
  773. _io_BytesIO___init___impl(bytesio *self, PyObject *initvalue)
  774. /*[clinic end generated code: output=65c0c51e24c5b621 input=aac7f31b67bf0fb6]*/
  775. {
  776. /* In case, __init__ is called multiple times. */
  777. self->string_size = 0;
  778. self->pos = 0;
  779. if (self->exports > 0) {
  780. PyErr_SetString(PyExc_BufferError,
  781. "Existing exports of data: object cannot be re-sized");
  782. return -1;
  783. }
  784. if (initvalue && initvalue != Py_None) {
  785. if (PyBytes_CheckExact(initvalue)) {
  786. Py_XSETREF(self->buf, Py_NewRef(initvalue));
  787. self->string_size = PyBytes_GET_SIZE(initvalue);
  788. }
  789. else {
  790. PyObject *res;
  791. res = _io_BytesIO_write(self, initvalue);
  792. if (res == NULL)
  793. return -1;
  794. Py_DECREF(res);
  795. self->pos = 0;
  796. }
  797. }
  798. return 0;
  799. }
  800. static PyObject *
  801. bytesio_sizeof(bytesio *self, void *unused)
  802. {
  803. size_t res = _PyObject_SIZE(Py_TYPE(self));
  804. if (self->buf && !SHARED_BUF(self)) {
  805. size_t s = _PySys_GetSizeOf(self->buf);
  806. if (s == (size_t)-1) {
  807. return NULL;
  808. }
  809. res += s;
  810. }
  811. return PyLong_FromSize_t(res);
  812. }
  813. static int
  814. bytesio_traverse(bytesio *self, visitproc visit, void *arg)
  815. {
  816. Py_VISIT(Py_TYPE(self));
  817. Py_VISIT(self->dict);
  818. Py_VISIT(self->buf);
  819. return 0;
  820. }
  821. static int
  822. bytesio_clear(bytesio *self)
  823. {
  824. Py_CLEAR(self->dict);
  825. if (self->exports == 0) {
  826. Py_CLEAR(self->buf);
  827. }
  828. return 0;
  829. }
  830. #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
  831. #include "clinic/bytesio.c.h"
  832. #undef clinic_state
  833. static PyGetSetDef bytesio_getsetlist[] = {
  834. {"closed", (getter)bytesio_get_closed, NULL,
  835. "True if the file is closed."},
  836. {NULL}, /* sentinel */
  837. };
  838. static struct PyMethodDef bytesio_methods[] = {
  839. _IO_BYTESIO_READABLE_METHODDEF
  840. _IO_BYTESIO_SEEKABLE_METHODDEF
  841. _IO_BYTESIO_WRITABLE_METHODDEF
  842. _IO_BYTESIO_CLOSE_METHODDEF
  843. _IO_BYTESIO_FLUSH_METHODDEF
  844. _IO_BYTESIO_ISATTY_METHODDEF
  845. _IO_BYTESIO_TELL_METHODDEF
  846. _IO_BYTESIO_WRITE_METHODDEF
  847. _IO_BYTESIO_WRITELINES_METHODDEF
  848. _IO_BYTESIO_READ1_METHODDEF
  849. _IO_BYTESIO_READINTO_METHODDEF
  850. _IO_BYTESIO_READLINE_METHODDEF
  851. _IO_BYTESIO_READLINES_METHODDEF
  852. _IO_BYTESIO_READ_METHODDEF
  853. _IO_BYTESIO_GETBUFFER_METHODDEF
  854. _IO_BYTESIO_GETVALUE_METHODDEF
  855. _IO_BYTESIO_SEEK_METHODDEF
  856. _IO_BYTESIO_TRUNCATE_METHODDEF
  857. {"__getstate__", (PyCFunction)bytesio_getstate, METH_NOARGS, NULL},
  858. {"__setstate__", (PyCFunction)bytesio_setstate, METH_O, NULL},
  859. {"__sizeof__", (PyCFunction)bytesio_sizeof, METH_NOARGS, NULL},
  860. {NULL, NULL} /* sentinel */
  861. };
  862. static PyMemberDef bytesio_members[] = {
  863. {"__weaklistoffset__", T_PYSSIZET, offsetof(bytesio, weakreflist), READONLY},
  864. {"__dictoffset__", T_PYSSIZET, offsetof(bytesio, dict), READONLY},
  865. {NULL}
  866. };
  867. static PyType_Slot bytesio_slots[] = {
  868. {Py_tp_dealloc, bytesio_dealloc},
  869. {Py_tp_doc, (void *)_io_BytesIO___init____doc__},
  870. {Py_tp_traverse, bytesio_traverse},
  871. {Py_tp_clear, bytesio_clear},
  872. {Py_tp_iter, PyObject_SelfIter},
  873. {Py_tp_iternext, bytesio_iternext},
  874. {Py_tp_methods, bytesio_methods},
  875. {Py_tp_members, bytesio_members},
  876. {Py_tp_getset, bytesio_getsetlist},
  877. {Py_tp_init, _io_BytesIO___init__},
  878. {Py_tp_new, bytesio_new},
  879. {0, NULL},
  880. };
  881. PyType_Spec bytesio_spec = {
  882. .name = "_io.BytesIO",
  883. .basicsize = sizeof(bytesio),
  884. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  885. Py_TPFLAGS_IMMUTABLETYPE),
  886. .slots = bytesio_slots,
  887. };
  888. /*
  889. * Implementation of the small intermediate object used by getbuffer().
  890. * getbuffer() returns a memoryview over this object, which should make it
  891. * invisible from Python code.
  892. */
  893. static int
  894. bytesiobuf_getbuffer(bytesiobuf *obj, Py_buffer *view, int flags)
  895. {
  896. bytesio *b = (bytesio *) obj->source;
  897. if (view == NULL) {
  898. PyErr_SetString(PyExc_BufferError,
  899. "bytesiobuf_getbuffer: view==NULL argument is obsolete");
  900. return -1;
  901. }
  902. if (b->exports == 0 && SHARED_BUF(b)) {
  903. if (unshare_buffer(b, b->string_size) < 0)
  904. return -1;
  905. }
  906. /* cannot fail if view != NULL and readonly == 0 */
  907. (void)PyBuffer_FillInfo(view, (PyObject*)obj,
  908. PyBytes_AS_STRING(b->buf), b->string_size,
  909. 0, flags);
  910. b->exports++;
  911. return 0;
  912. }
  913. static void
  914. bytesiobuf_releasebuffer(bytesiobuf *obj, Py_buffer *view)
  915. {
  916. bytesio *b = (bytesio *) obj->source;
  917. b->exports--;
  918. }
  919. static int
  920. bytesiobuf_traverse(bytesiobuf *self, visitproc visit, void *arg)
  921. {
  922. Py_VISIT(Py_TYPE(self));
  923. Py_VISIT(self->source);
  924. return 0;
  925. }
  926. static void
  927. bytesiobuf_dealloc(bytesiobuf *self)
  928. {
  929. PyTypeObject *tp = Py_TYPE(self);
  930. /* bpo-31095: UnTrack is needed before calling any callbacks */
  931. PyObject_GC_UnTrack(self);
  932. Py_CLEAR(self->source);
  933. tp->tp_free(self);
  934. Py_DECREF(tp);
  935. }
  936. static PyType_Slot bytesiobuf_slots[] = {
  937. {Py_tp_dealloc, bytesiobuf_dealloc},
  938. {Py_tp_traverse, bytesiobuf_traverse},
  939. // Buffer protocol
  940. {Py_bf_getbuffer, bytesiobuf_getbuffer},
  941. {Py_bf_releasebuffer, bytesiobuf_releasebuffer},
  942. {0, NULL},
  943. };
  944. PyType_Spec bytesiobuf_spec = {
  945. .name = "_io._BytesIOBuffer",
  946. .basicsize = sizeof(bytesiobuf),
  947. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_HAVE_GC |
  948. Py_TPFLAGS_IMMUTABLETYPE | Py_TPFLAGS_DISALLOW_INSTANTIATION),
  949. .slots = bytesiobuf_slots,
  950. };