stringio.c 29 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037
  1. #define PY_SSIZE_T_CLEAN
  2. #include "Python.h"
  3. #include <stddef.h> // offsetof()
  4. #include "pycore_object.h"
  5. #include "_iomodule.h"
  6. /* Implementation note: the buffer is always at least one character longer
  7. than the enclosed string, for proper functioning of _PyIO_find_line_ending.
  8. */
  9. #define STATE_REALIZED 1
  10. #define STATE_ACCUMULATING 2
  11. /*[clinic input]
  12. module _io
  13. class _io.StringIO "stringio *" "clinic_state()->PyStringIO_Type"
  14. [clinic start generated code]*/
  15. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=2693eada0658d470]*/
  16. typedef struct {
  17. PyObject_HEAD
  18. Py_UCS4 *buf;
  19. Py_ssize_t pos;
  20. Py_ssize_t string_size;
  21. size_t buf_size;
  22. /* The stringio object can be in two states: accumulating or realized.
  23. In accumulating state, the internal buffer contains nothing and
  24. the contents are given by the embedded _PyUnicodeWriter structure.
  25. In realized state, the internal buffer is meaningful and the
  26. _PyUnicodeWriter is destroyed.
  27. */
  28. int state;
  29. _PyUnicodeWriter writer;
  30. char ok; /* initialized? */
  31. char closed;
  32. char readuniversal;
  33. char readtranslate;
  34. PyObject *decoder;
  35. PyObject *readnl;
  36. PyObject *writenl;
  37. PyObject *dict;
  38. PyObject *weakreflist;
  39. _PyIO_State *module_state;
  40. } stringio;
  41. static int _io_StringIO___init__(PyObject *self, PyObject *args, PyObject *kwargs);
  42. #define CHECK_INITIALIZED(self) \
  43. if (self->ok <= 0) { \
  44. PyErr_SetString(PyExc_ValueError, \
  45. "I/O operation on uninitialized object"); \
  46. return NULL; \
  47. }
  48. #define CHECK_CLOSED(self) \
  49. if (self->closed) { \
  50. PyErr_SetString(PyExc_ValueError, \
  51. "I/O operation on closed file"); \
  52. return NULL; \
  53. }
  54. #define ENSURE_REALIZED(self) \
  55. if (realize(self) < 0) { \
  56. return NULL; \
  57. }
  58. /* Internal routine for changing the size, in terms of characters, of the
  59. buffer of StringIO objects. The caller should ensure that the 'size'
  60. argument is non-negative. Returns 0 on success, -1 otherwise. */
  61. static int
  62. resize_buffer(stringio *self, size_t size)
  63. {
  64. /* Here, unsigned types are used to avoid dealing with signed integer
  65. overflow, which is undefined in C. */
  66. size_t alloc = self->buf_size;
  67. Py_UCS4 *new_buf = NULL;
  68. assert(self->buf != NULL);
  69. /* Reserve one more char for line ending detection. */
  70. size = size + 1;
  71. /* For simplicity, stay in the range of the signed type. Anyway, Python
  72. doesn't allow strings to be longer than this. */
  73. if (size > PY_SSIZE_T_MAX)
  74. goto overflow;
  75. if (size < alloc / 2) {
  76. /* Major downsize; resize down to exact size. */
  77. alloc = size + 1;
  78. }
  79. else if (size < alloc) {
  80. /* Within allocated size; quick exit */
  81. return 0;
  82. }
  83. else if (size <= alloc * 1.125) {
  84. /* Moderate upsize; overallocate similar to list_resize() */
  85. alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
  86. }
  87. else {
  88. /* Major upsize; resize up to exact size */
  89. alloc = size + 1;
  90. }
  91. if (alloc > PY_SIZE_MAX / sizeof(Py_UCS4))
  92. goto overflow;
  93. new_buf = (Py_UCS4 *)PyMem_Realloc(self->buf, alloc * sizeof(Py_UCS4));
  94. if (new_buf == NULL) {
  95. PyErr_NoMemory();
  96. return -1;
  97. }
  98. self->buf_size = alloc;
  99. self->buf = new_buf;
  100. return 0;
  101. overflow:
  102. PyErr_SetString(PyExc_OverflowError,
  103. "new buffer size too large");
  104. return -1;
  105. }
  106. static PyObject *
  107. make_intermediate(stringio *self)
  108. {
  109. PyObject *intermediate = _PyUnicodeWriter_Finish(&self->writer);
  110. self->state = STATE_REALIZED;
  111. if (intermediate == NULL)
  112. return NULL;
  113. _PyUnicodeWriter_Init(&self->writer);
  114. self->writer.overallocate = 1;
  115. if (_PyUnicodeWriter_WriteStr(&self->writer, intermediate)) {
  116. Py_DECREF(intermediate);
  117. return NULL;
  118. }
  119. self->state = STATE_ACCUMULATING;
  120. return intermediate;
  121. }
  122. static int
  123. realize(stringio *self)
  124. {
  125. Py_ssize_t len;
  126. PyObject *intermediate;
  127. if (self->state == STATE_REALIZED)
  128. return 0;
  129. assert(self->state == STATE_ACCUMULATING);
  130. self->state = STATE_REALIZED;
  131. intermediate = _PyUnicodeWriter_Finish(&self->writer);
  132. if (intermediate == NULL)
  133. return -1;
  134. /* Append the intermediate string to the internal buffer.
  135. The length should be equal to the current cursor position.
  136. */
  137. len = PyUnicode_GET_LENGTH(intermediate);
  138. if (resize_buffer(self, len) < 0) {
  139. Py_DECREF(intermediate);
  140. return -1;
  141. }
  142. if (!PyUnicode_AsUCS4(intermediate, self->buf, len, 0)) {
  143. Py_DECREF(intermediate);
  144. return -1;
  145. }
  146. Py_DECREF(intermediate);
  147. return 0;
  148. }
  149. /* Internal routine for writing a whole PyUnicode object to the buffer of a
  150. StringIO object. Returns 0 on success, or -1 on error. */
  151. static Py_ssize_t
  152. write_str(stringio *self, PyObject *obj)
  153. {
  154. Py_ssize_t len;
  155. PyObject *decoded = NULL;
  156. assert(self->buf != NULL);
  157. assert(self->pos >= 0);
  158. if (self->decoder != NULL) {
  159. decoded = _PyIncrementalNewlineDecoder_decode(
  160. self->decoder, obj, 1 /* always final */);
  161. }
  162. else {
  163. decoded = Py_NewRef(obj);
  164. }
  165. if (self->writenl) {
  166. PyObject *translated = PyUnicode_Replace(
  167. decoded, &_Py_STR(newline), self->writenl, -1);
  168. Py_SETREF(decoded, translated);
  169. }
  170. if (decoded == NULL)
  171. return -1;
  172. assert(PyUnicode_Check(decoded));
  173. if (PyUnicode_READY(decoded)) {
  174. Py_DECREF(decoded);
  175. return -1;
  176. }
  177. len = PyUnicode_GET_LENGTH(decoded);
  178. assert(len >= 0);
  179. /* This overflow check is not strictly necessary. However, it avoids us to
  180. deal with funky things like comparing an unsigned and a signed
  181. integer. */
  182. if (self->pos > PY_SSIZE_T_MAX - len) {
  183. PyErr_SetString(PyExc_OverflowError,
  184. "new position too large");
  185. goto fail;
  186. }
  187. if (self->state == STATE_ACCUMULATING) {
  188. if (self->string_size == self->pos) {
  189. if (_PyUnicodeWriter_WriteStr(&self->writer, decoded))
  190. goto fail;
  191. goto success;
  192. }
  193. if (realize(self))
  194. goto fail;
  195. }
  196. if (self->pos + len > self->string_size) {
  197. if (resize_buffer(self, self->pos + len) < 0)
  198. goto fail;
  199. }
  200. if (self->pos > self->string_size) {
  201. /* In case of overseek, pad with null bytes the buffer region between
  202. the end of stream and the current position.
  203. 0 lo string_size hi
  204. | |<---used--->|<----------available----------->|
  205. | | <--to pad-->|<---to write---> |
  206. 0 buf position
  207. */
  208. memset(self->buf + self->string_size, '\0',
  209. (self->pos - self->string_size) * sizeof(Py_UCS4));
  210. }
  211. /* Copy the data to the internal buffer, overwriting some of the
  212. existing data if self->pos < self->string_size. */
  213. if (!PyUnicode_AsUCS4(decoded,
  214. self->buf + self->pos,
  215. self->buf_size - self->pos,
  216. 0))
  217. goto fail;
  218. success:
  219. /* Set the new length of the internal string if it has changed. */
  220. self->pos += len;
  221. if (self->string_size < self->pos)
  222. self->string_size = self->pos;
  223. Py_DECREF(decoded);
  224. return 0;
  225. fail:
  226. Py_XDECREF(decoded);
  227. return -1;
  228. }
  229. /*[clinic input]
  230. _io.StringIO.getvalue
  231. Retrieve the entire contents of the object.
  232. [clinic start generated code]*/
  233. static PyObject *
  234. _io_StringIO_getvalue_impl(stringio *self)
  235. /*[clinic end generated code: output=27b6a7bfeaebce01 input=d23cb81d6791cf88]*/
  236. {
  237. CHECK_INITIALIZED(self);
  238. CHECK_CLOSED(self);
  239. if (self->state == STATE_ACCUMULATING)
  240. return make_intermediate(self);
  241. return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, self->buf,
  242. self->string_size);
  243. }
  244. /*[clinic input]
  245. _io.StringIO.tell
  246. Tell the current file position.
  247. [clinic start generated code]*/
  248. static PyObject *
  249. _io_StringIO_tell_impl(stringio *self)
  250. /*[clinic end generated code: output=2e87ac67b116c77b input=ec866ebaff02f405]*/
  251. {
  252. CHECK_INITIALIZED(self);
  253. CHECK_CLOSED(self);
  254. return PyLong_FromSsize_t(self->pos);
  255. }
  256. /*[clinic input]
  257. _io.StringIO.read
  258. size: Py_ssize_t(accept={int, NoneType}) = -1
  259. /
  260. Read at most size characters, returned as a string.
  261. If the argument is negative or omitted, read until EOF
  262. is reached. Return an empty string at EOF.
  263. [clinic start generated code]*/
  264. static PyObject *
  265. _io_StringIO_read_impl(stringio *self, Py_ssize_t size)
  266. /*[clinic end generated code: output=ae8cf6002f71626c input=0921093383dfb92d]*/
  267. {
  268. Py_ssize_t n;
  269. Py_UCS4 *output;
  270. CHECK_INITIALIZED(self);
  271. CHECK_CLOSED(self);
  272. /* adjust invalid sizes */
  273. n = self->string_size - self->pos;
  274. if (size < 0 || size > n) {
  275. size = n;
  276. if (size < 0)
  277. size = 0;
  278. }
  279. /* Optimization for seek(0); read() */
  280. if (self->state == STATE_ACCUMULATING && self->pos == 0 && size == n) {
  281. PyObject *result = make_intermediate(self);
  282. self->pos = self->string_size;
  283. return result;
  284. }
  285. ENSURE_REALIZED(self);
  286. output = self->buf + self->pos;
  287. self->pos += size;
  288. return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, output, size);
  289. }
  290. /* Internal helper, used by stringio_readline and stringio_iternext */
  291. static PyObject *
  292. _stringio_readline(stringio *self, Py_ssize_t limit)
  293. {
  294. Py_UCS4 *start, *end, old_char;
  295. Py_ssize_t len, consumed;
  296. /* In case of overseek, return the empty string */
  297. if (self->pos >= self->string_size)
  298. return PyUnicode_New(0, 0);
  299. start = self->buf + self->pos;
  300. if (limit < 0 || limit > self->string_size - self->pos)
  301. limit = self->string_size - self->pos;
  302. end = start + limit;
  303. old_char = *end;
  304. *end = '\0';
  305. len = _PyIO_find_line_ending(
  306. self->readtranslate, self->readuniversal, self->readnl,
  307. PyUnicode_4BYTE_KIND, (char*)start, (char*)end, &consumed);
  308. *end = old_char;
  309. /* If we haven't found any line ending, we just return everything
  310. (`consumed` is ignored). */
  311. if (len < 0)
  312. len = limit;
  313. self->pos += len;
  314. return PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND, start, len);
  315. }
  316. /*[clinic input]
  317. _io.StringIO.readline
  318. size: Py_ssize_t(accept={int, NoneType}) = -1
  319. /
  320. Read until newline or EOF.
  321. Returns an empty string if EOF is hit immediately.
  322. [clinic start generated code]*/
  323. static PyObject *
  324. _io_StringIO_readline_impl(stringio *self, Py_ssize_t size)
  325. /*[clinic end generated code: output=cabd6452f1b7e85d input=a5bd70bf682aa276]*/
  326. {
  327. CHECK_INITIALIZED(self);
  328. CHECK_CLOSED(self);
  329. ENSURE_REALIZED(self);
  330. return _stringio_readline(self, size);
  331. }
  332. static PyObject *
  333. stringio_iternext(stringio *self)
  334. {
  335. PyObject *line;
  336. CHECK_INITIALIZED(self);
  337. CHECK_CLOSED(self);
  338. ENSURE_REALIZED(self);
  339. if (Py_IS_TYPE(self, self->module_state->PyStringIO_Type)) {
  340. /* Skip method call overhead for speed */
  341. line = _stringio_readline(self, -1);
  342. }
  343. else {
  344. /* XXX is subclassing StringIO really supported? */
  345. line = PyObject_CallMethodNoArgs((PyObject *)self,
  346. &_Py_ID(readline));
  347. if (line && !PyUnicode_Check(line)) {
  348. PyErr_Format(PyExc_OSError,
  349. "readline() should have returned a str object, "
  350. "not '%.200s'", Py_TYPE(line)->tp_name);
  351. Py_DECREF(line);
  352. return NULL;
  353. }
  354. }
  355. if (line == NULL)
  356. return NULL;
  357. if (PyUnicode_GET_LENGTH(line) == 0) {
  358. /* Reached EOF */
  359. Py_DECREF(line);
  360. return NULL;
  361. }
  362. return line;
  363. }
  364. /*[clinic input]
  365. _io.StringIO.truncate
  366. pos as size: Py_ssize_t(accept={int, NoneType}, c_default="self->pos") = None
  367. /
  368. Truncate size to pos.
  369. The pos argument defaults to the current file position, as
  370. returned by tell(). The current file position is unchanged.
  371. Returns the new absolute position.
  372. [clinic start generated code]*/
  373. static PyObject *
  374. _io_StringIO_truncate_impl(stringio *self, Py_ssize_t size)
  375. /*[clinic end generated code: output=eb3aef8e06701365 input=5505cff90ca48b96]*/
  376. {
  377. CHECK_INITIALIZED(self);
  378. CHECK_CLOSED(self);
  379. if (size < 0) {
  380. PyErr_Format(PyExc_ValueError,
  381. "Negative size value %zd", size);
  382. return NULL;
  383. }
  384. if (size < self->string_size) {
  385. ENSURE_REALIZED(self);
  386. if (resize_buffer(self, size) < 0)
  387. return NULL;
  388. self->string_size = size;
  389. }
  390. return PyLong_FromSsize_t(size);
  391. }
  392. /*[clinic input]
  393. _io.StringIO.seek
  394. pos: Py_ssize_t
  395. whence: int = 0
  396. /
  397. Change stream position.
  398. Seek to character offset pos relative to position indicated by whence:
  399. 0 Start of stream (the default). pos should be >= 0;
  400. 1 Current position - pos must be 0;
  401. 2 End of stream - pos must be 0.
  402. Returns the new absolute position.
  403. [clinic start generated code]*/
  404. static PyObject *
  405. _io_StringIO_seek_impl(stringio *self, Py_ssize_t pos, int whence)
  406. /*[clinic end generated code: output=e9e0ac9a8ae71c25 input=e3855b24e7cae06a]*/
  407. {
  408. CHECK_INITIALIZED(self);
  409. CHECK_CLOSED(self);
  410. if (whence != 0 && whence != 1 && whence != 2) {
  411. PyErr_Format(PyExc_ValueError,
  412. "Invalid whence (%i, should be 0, 1 or 2)", whence);
  413. return NULL;
  414. }
  415. else if (pos < 0 && whence == 0) {
  416. PyErr_Format(PyExc_ValueError,
  417. "Negative seek position %zd", pos);
  418. return NULL;
  419. }
  420. else if (whence != 0 && pos != 0) {
  421. PyErr_SetString(PyExc_OSError,
  422. "Can't do nonzero cur-relative seeks");
  423. return NULL;
  424. }
  425. /* whence = 0: offset relative to beginning of the string.
  426. whence = 1: no change to current position.
  427. whence = 2: change position to end of file. */
  428. if (whence == 1) {
  429. pos = self->pos;
  430. }
  431. else if (whence == 2) {
  432. pos = self->string_size;
  433. }
  434. self->pos = pos;
  435. return PyLong_FromSsize_t(self->pos);
  436. }
  437. /*[clinic input]
  438. _io.StringIO.write
  439. s as obj: object
  440. /
  441. Write string to file.
  442. Returns the number of characters written, which is always equal to
  443. the length of the string.
  444. [clinic start generated code]*/
  445. static PyObject *
  446. _io_StringIO_write(stringio *self, PyObject *obj)
  447. /*[clinic end generated code: output=0deaba91a15b94da input=cf96f3b16586e669]*/
  448. {
  449. Py_ssize_t size;
  450. CHECK_INITIALIZED(self);
  451. if (!PyUnicode_Check(obj)) {
  452. PyErr_Format(PyExc_TypeError, "string argument expected, got '%s'",
  453. Py_TYPE(obj)->tp_name);
  454. return NULL;
  455. }
  456. if (PyUnicode_READY(obj))
  457. return NULL;
  458. CHECK_CLOSED(self);
  459. size = PyUnicode_GET_LENGTH(obj);
  460. if (size > 0 && write_str(self, obj) < 0)
  461. return NULL;
  462. return PyLong_FromSsize_t(size);
  463. }
  464. /*[clinic input]
  465. _io.StringIO.close
  466. Close the IO object.
  467. Attempting any further operation after the object is closed
  468. will raise a ValueError.
  469. This method has no effect if the file is already closed.
  470. [clinic start generated code]*/
  471. static PyObject *
  472. _io_StringIO_close_impl(stringio *self)
  473. /*[clinic end generated code: output=04399355cbe518f1 input=cbc10b45f35d6d46]*/
  474. {
  475. self->closed = 1;
  476. /* Free up some memory */
  477. if (resize_buffer(self, 0) < 0)
  478. return NULL;
  479. _PyUnicodeWriter_Dealloc(&self->writer);
  480. Py_CLEAR(self->readnl);
  481. Py_CLEAR(self->writenl);
  482. Py_CLEAR(self->decoder);
  483. Py_RETURN_NONE;
  484. }
  485. static int
  486. stringio_traverse(stringio *self, visitproc visit, void *arg)
  487. {
  488. Py_VISIT(Py_TYPE(self));
  489. Py_VISIT(self->readnl);
  490. Py_VISIT(self->writenl);
  491. Py_VISIT(self->decoder);
  492. Py_VISIT(self->dict);
  493. return 0;
  494. }
  495. static int
  496. stringio_clear(stringio *self)
  497. {
  498. Py_CLEAR(self->readnl);
  499. Py_CLEAR(self->writenl);
  500. Py_CLEAR(self->decoder);
  501. Py_CLEAR(self->dict);
  502. return 0;
  503. }
  504. static void
  505. stringio_dealloc(stringio *self)
  506. {
  507. PyTypeObject *tp = Py_TYPE(self);
  508. _PyObject_GC_UNTRACK(self);
  509. self->ok = 0;
  510. if (self->buf) {
  511. PyMem_Free(self->buf);
  512. self->buf = NULL;
  513. }
  514. _PyUnicodeWriter_Dealloc(&self->writer);
  515. (void)stringio_clear(self);
  516. if (self->weakreflist != NULL) {
  517. PyObject_ClearWeakRefs((PyObject *) self);
  518. }
  519. tp->tp_free(self);
  520. Py_DECREF(tp);
  521. }
  522. static PyObject *
  523. stringio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
  524. {
  525. stringio *self;
  526. assert(type != NULL && type->tp_alloc != NULL);
  527. self = (stringio *)type->tp_alloc(type, 0);
  528. if (self == NULL)
  529. return NULL;
  530. /* tp_alloc initializes all the fields to zero. So we don't have to
  531. initialize them here. */
  532. self->buf = (Py_UCS4 *)PyMem_Malloc(0);
  533. if (self->buf == NULL) {
  534. Py_DECREF(self);
  535. return PyErr_NoMemory();
  536. }
  537. return (PyObject *)self;
  538. }
  539. /*[clinic input]
  540. _io.StringIO.__init__
  541. initial_value as value: object(c_default="NULL") = ''
  542. newline as newline_obj: object(c_default="NULL") = '\n'
  543. Text I/O implementation using an in-memory buffer.
  544. The initial_value argument sets the value of object. The newline
  545. argument is like the one of TextIOWrapper's constructor.
  546. [clinic start generated code]*/
  547. static int
  548. _io_StringIO___init___impl(stringio *self, PyObject *value,
  549. PyObject *newline_obj)
  550. /*[clinic end generated code: output=a421ea023b22ef4e input=cee2d9181b2577a3]*/
  551. {
  552. const char *newline = "\n";
  553. Py_ssize_t value_len;
  554. /* Parse the newline argument. We only want to allow unicode objects or
  555. None. */
  556. if (newline_obj == Py_None) {
  557. newline = NULL;
  558. }
  559. else if (newline_obj) {
  560. if (!PyUnicode_Check(newline_obj)) {
  561. PyErr_Format(PyExc_TypeError,
  562. "newline must be str or None, not %.200s",
  563. Py_TYPE(newline_obj)->tp_name);
  564. return -1;
  565. }
  566. newline = PyUnicode_AsUTF8(newline_obj);
  567. if (newline == NULL)
  568. return -1;
  569. }
  570. if (newline && newline[0] != '\0'
  571. && !(newline[0] == '\n' && newline[1] == '\0')
  572. && !(newline[0] == '\r' && newline[1] == '\0')
  573. && !(newline[0] == '\r' && newline[1] == '\n' && newline[2] == '\0')) {
  574. PyErr_Format(PyExc_ValueError,
  575. "illegal newline value: %R", newline_obj);
  576. return -1;
  577. }
  578. if (value && value != Py_None && !PyUnicode_Check(value)) {
  579. PyErr_Format(PyExc_TypeError,
  580. "initial_value must be str or None, not %.200s",
  581. Py_TYPE(value)->tp_name);
  582. return -1;
  583. }
  584. self->ok = 0;
  585. _PyUnicodeWriter_Dealloc(&self->writer);
  586. Py_CLEAR(self->readnl);
  587. Py_CLEAR(self->writenl);
  588. Py_CLEAR(self->decoder);
  589. assert((newline != NULL && newline_obj != Py_None) ||
  590. (newline == NULL && newline_obj == Py_None));
  591. if (newline) {
  592. self->readnl = PyUnicode_FromString(newline);
  593. if (self->readnl == NULL)
  594. return -1;
  595. }
  596. self->readuniversal = (newline == NULL || newline[0] == '\0');
  597. self->readtranslate = (newline == NULL);
  598. /* If newline == "", we don't translate anything.
  599. If newline == "\n" or newline == None, we translate to "\n", which is
  600. a no-op.
  601. (for newline == None, TextIOWrapper translates to os.linesep, but it
  602. is pointless for StringIO)
  603. */
  604. if (newline != NULL && newline[0] == '\r') {
  605. self->writenl = Py_NewRef(self->readnl);
  606. }
  607. _PyIO_State *module_state = find_io_state_by_def(Py_TYPE(self));
  608. if (self->readuniversal) {
  609. self->decoder = PyObject_CallFunctionObjArgs(
  610. (PyObject *)module_state->PyIncrementalNewlineDecoder_Type,
  611. Py_None, self->readtranslate ? Py_True : Py_False, NULL);
  612. if (self->decoder == NULL)
  613. return -1;
  614. }
  615. /* Now everything is set up, resize buffer to size of initial value,
  616. and copy it */
  617. self->string_size = 0;
  618. if (value && value != Py_None)
  619. value_len = PyUnicode_GetLength(value);
  620. else
  621. value_len = 0;
  622. if (value_len > 0) {
  623. /* This is a heuristic, for newline translation might change
  624. the string length. */
  625. if (resize_buffer(self, 0) < 0)
  626. return -1;
  627. self->state = STATE_REALIZED;
  628. self->pos = 0;
  629. if (write_str(self, value) < 0)
  630. return -1;
  631. }
  632. else {
  633. /* Empty stringio object, we can start by accumulating */
  634. if (resize_buffer(self, 0) < 0)
  635. return -1;
  636. _PyUnicodeWriter_Init(&self->writer);
  637. self->writer.overallocate = 1;
  638. self->state = STATE_ACCUMULATING;
  639. }
  640. self->pos = 0;
  641. self->module_state = module_state;
  642. self->closed = 0;
  643. self->ok = 1;
  644. return 0;
  645. }
  646. /* Properties and pseudo-properties */
  647. /*[clinic input]
  648. _io.StringIO.readable
  649. Returns True if the IO object can be read.
  650. [clinic start generated code]*/
  651. static PyObject *
  652. _io_StringIO_readable_impl(stringio *self)
  653. /*[clinic end generated code: output=b19d44dd8b1ceb99 input=39ce068b224c21ad]*/
  654. {
  655. CHECK_INITIALIZED(self);
  656. CHECK_CLOSED(self);
  657. Py_RETURN_TRUE;
  658. }
  659. /*[clinic input]
  660. _io.StringIO.writable
  661. Returns True if the IO object can be written.
  662. [clinic start generated code]*/
  663. static PyObject *
  664. _io_StringIO_writable_impl(stringio *self)
  665. /*[clinic end generated code: output=13e4dd77187074ca input=7a691353aac38835]*/
  666. {
  667. CHECK_INITIALIZED(self);
  668. CHECK_CLOSED(self);
  669. Py_RETURN_TRUE;
  670. }
  671. /*[clinic input]
  672. _io.StringIO.seekable
  673. Returns True if the IO object can be seeked.
  674. [clinic start generated code]*/
  675. static PyObject *
  676. _io_StringIO_seekable_impl(stringio *self)
  677. /*[clinic end generated code: output=4d20b4641c756879 input=4c606d05b32952e6]*/
  678. {
  679. CHECK_INITIALIZED(self);
  680. CHECK_CLOSED(self);
  681. Py_RETURN_TRUE;
  682. }
  683. /* Pickling support.
  684. The implementation of __getstate__ is similar to the one for BytesIO,
  685. except that we also save the newline parameter. For __setstate__ and unlike
  686. BytesIO, we call __init__ to restore the object's state. Doing so allows us
  687. to avoid decoding the complex newline state while keeping the object
  688. representation compact.
  689. See comment in bytesio.c regarding why only pickle protocols and onward are
  690. supported.
  691. */
  692. static PyObject *
  693. stringio_getstate(stringio *self, PyObject *Py_UNUSED(ignored))
  694. {
  695. PyObject *initvalue = _io_StringIO_getvalue_impl(self);
  696. PyObject *dict;
  697. PyObject *state;
  698. if (initvalue == NULL)
  699. return NULL;
  700. if (self->dict == NULL) {
  701. dict = Py_NewRef(Py_None);
  702. }
  703. else {
  704. dict = PyDict_Copy(self->dict);
  705. if (dict == NULL) {
  706. Py_DECREF(initvalue);
  707. return NULL;
  708. }
  709. }
  710. state = Py_BuildValue("(OOnN)", initvalue,
  711. self->readnl ? self->readnl : Py_None,
  712. self->pos, dict);
  713. Py_DECREF(initvalue);
  714. return state;
  715. }
  716. static PyObject *
  717. stringio_setstate(stringio *self, PyObject *state)
  718. {
  719. PyObject *initarg;
  720. PyObject *position_obj;
  721. PyObject *dict;
  722. Py_ssize_t pos;
  723. assert(state != NULL);
  724. CHECK_CLOSED(self);
  725. /* We allow the state tuple to be longer than 4, because we may need
  726. someday to extend the object's state without breaking
  727. backward-compatibility. */
  728. if (!PyTuple_Check(state) || PyTuple_GET_SIZE(state) < 4) {
  729. PyErr_Format(PyExc_TypeError,
  730. "%.200s.__setstate__ argument should be 4-tuple, got %.200s",
  731. Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
  732. return NULL;
  733. }
  734. /* Initialize the object's state. */
  735. initarg = PyTuple_GetSlice(state, 0, 2);
  736. if (initarg == NULL)
  737. return NULL;
  738. if (_io_StringIO___init__((PyObject *)self, initarg, NULL) < 0) {
  739. Py_DECREF(initarg);
  740. return NULL;
  741. }
  742. Py_DECREF(initarg);
  743. /* Restore the buffer state. Even if __init__ did initialize the buffer,
  744. we have to initialize it again since __init__ may translate the
  745. newlines in the initial_value string. We clearly do not want that
  746. because the string value in the state tuple has already been translated
  747. once by __init__. So we do not take any chance and replace object's
  748. buffer completely. */
  749. {
  750. PyObject *item;
  751. Py_UCS4 *buf;
  752. Py_ssize_t bufsize;
  753. item = PyTuple_GET_ITEM(state, 0);
  754. buf = PyUnicode_AsUCS4Copy(item);
  755. if (buf == NULL)
  756. return NULL;
  757. bufsize = PyUnicode_GET_LENGTH(item);
  758. if (resize_buffer(self, bufsize) < 0) {
  759. PyMem_Free(buf);
  760. return NULL;
  761. }
  762. memcpy(self->buf, buf, bufsize * sizeof(Py_UCS4));
  763. PyMem_Free(buf);
  764. self->string_size = bufsize;
  765. }
  766. /* Set carefully the position value. Alternatively, we could use the seek
  767. method instead of modifying self->pos directly to better protect the
  768. object internal state against erroneous (or malicious) inputs. */
  769. position_obj = PyTuple_GET_ITEM(state, 2);
  770. if (!PyLong_Check(position_obj)) {
  771. PyErr_Format(PyExc_TypeError,
  772. "third item of state must be an integer, got %.200s",
  773. Py_TYPE(position_obj)->tp_name);
  774. return NULL;
  775. }
  776. pos = PyLong_AsSsize_t(position_obj);
  777. if (pos == -1 && PyErr_Occurred())
  778. return NULL;
  779. if (pos < 0) {
  780. PyErr_SetString(PyExc_ValueError,
  781. "position value cannot be negative");
  782. return NULL;
  783. }
  784. self->pos = pos;
  785. /* Set the dictionary of the instance variables. */
  786. dict = PyTuple_GET_ITEM(state, 3);
  787. if (dict != Py_None) {
  788. if (!PyDict_Check(dict)) {
  789. PyErr_Format(PyExc_TypeError,
  790. "fourth item of state should be a dict, got a %.200s",
  791. Py_TYPE(dict)->tp_name);
  792. return NULL;
  793. }
  794. if (self->dict) {
  795. /* Alternatively, we could replace the internal dictionary
  796. completely. However, it seems more practical to just update it. */
  797. if (PyDict_Update(self->dict, dict) < 0)
  798. return NULL;
  799. }
  800. else {
  801. self->dict = Py_NewRef(dict);
  802. }
  803. }
  804. Py_RETURN_NONE;
  805. }
  806. static PyObject *
  807. stringio_closed(stringio *self, void *context)
  808. {
  809. CHECK_INITIALIZED(self);
  810. return PyBool_FromLong(self->closed);
  811. }
  812. static PyObject *
  813. stringio_line_buffering(stringio *self, void *context)
  814. {
  815. CHECK_INITIALIZED(self);
  816. CHECK_CLOSED(self);
  817. Py_RETURN_FALSE;
  818. }
  819. static PyObject *
  820. stringio_newlines(stringio *self, void *context)
  821. {
  822. CHECK_INITIALIZED(self);
  823. CHECK_CLOSED(self);
  824. if (self->decoder == NULL)
  825. Py_RETURN_NONE;
  826. return PyObject_GetAttr(self->decoder, &_Py_ID(newlines));
  827. }
  828. #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
  829. #include "clinic/stringio.c.h"
  830. #undef clinic_state
  831. static struct PyMethodDef stringio_methods[] = {
  832. _IO_STRINGIO_CLOSE_METHODDEF
  833. _IO_STRINGIO_GETVALUE_METHODDEF
  834. _IO_STRINGIO_READ_METHODDEF
  835. _IO_STRINGIO_READLINE_METHODDEF
  836. _IO_STRINGIO_TELL_METHODDEF
  837. _IO_STRINGIO_TRUNCATE_METHODDEF
  838. _IO_STRINGIO_SEEK_METHODDEF
  839. _IO_STRINGIO_WRITE_METHODDEF
  840. _IO_STRINGIO_SEEKABLE_METHODDEF
  841. _IO_STRINGIO_READABLE_METHODDEF
  842. _IO_STRINGIO_WRITABLE_METHODDEF
  843. {"__getstate__", (PyCFunction)stringio_getstate, METH_NOARGS},
  844. {"__setstate__", (PyCFunction)stringio_setstate, METH_O},
  845. {NULL, NULL} /* sentinel */
  846. };
  847. static PyGetSetDef stringio_getset[] = {
  848. {"closed", (getter)stringio_closed, NULL, NULL},
  849. {"newlines", (getter)stringio_newlines, NULL, NULL},
  850. /* (following comments straight off of the original Python wrapper:)
  851. XXX Cruft to support the TextIOWrapper API. This would only
  852. be meaningful if StringIO supported the buffer attribute.
  853. Hopefully, a better solution, than adding these pseudo-attributes,
  854. will be found.
  855. */
  856. {"line_buffering", (getter)stringio_line_buffering, NULL, NULL},
  857. {NULL}
  858. };
  859. static struct PyMemberDef stringio_members[] = {
  860. {"__weaklistoffset__", T_PYSSIZET, offsetof(stringio, weakreflist), READONLY},
  861. {"__dictoffset__", T_PYSSIZET, offsetof(stringio, dict), READONLY},
  862. {NULL},
  863. };
  864. static PyType_Slot stringio_slots[] = {
  865. {Py_tp_dealloc, stringio_dealloc},
  866. {Py_tp_doc, (void *)_io_StringIO___init____doc__},
  867. {Py_tp_traverse, stringio_traverse},
  868. {Py_tp_clear, stringio_clear},
  869. {Py_tp_iternext, stringio_iternext},
  870. {Py_tp_methods, stringio_methods},
  871. {Py_tp_members, stringio_members},
  872. {Py_tp_getset, stringio_getset},
  873. {Py_tp_init, _io_StringIO___init__},
  874. {Py_tp_new, stringio_new},
  875. {0, NULL},
  876. };
  877. PyType_Spec stringio_spec = {
  878. .name = "_io.StringIO",
  879. .basicsize = sizeof(stringio),
  880. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  881. Py_TPFLAGS_IMMUTABLETYPE),
  882. .slots = stringio_slots,
  883. };