bufferedio.c 76 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711
  1. /*
  2. An implementation of Buffered I/O as defined by PEP 3116 - "New I/O"
  3. Classes defined here: BufferedIOBase, BufferedReader, BufferedWriter,
  4. BufferedRandom.
  5. Written by Amaury Forgeot d'Arc and Antoine Pitrou
  6. */
  7. #define PY_SSIZE_T_CLEAN
  8. #include "Python.h"
  9. #include "pycore_call.h" // _PyObject_CallNoArgs()
  10. #include "pycore_object.h"
  11. #include "structmember.h" // PyMemberDef
  12. #include "_iomodule.h"
  13. /*[clinic input]
  14. module _io
  15. class _io._BufferedIOBase "PyObject *" "clinic_state()->PyBufferedIOBase_Type"
  16. class _io._Buffered "buffered *" "clinic_state()->PyBufferedIOBase_Type"
  17. class _io.BufferedReader "buffered *" "clinic_state()->PyBufferedReader_Type"
  18. class _io.BufferedWriter "buffered *" "clinic_state()->PyBufferedWriter_Type"
  19. class _io.BufferedRWPair "rwpair *" "clinic_state()->PyBufferedRWPair_Type"
  20. class _io.BufferedRandom "buffered *" "clinic_state()->PyBufferedRandom_Type"
  21. [clinic start generated code]*/
  22. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=3b3ef9cbbbad4590]*/
  23. /*
  24. * BufferedIOBase class, inherits from IOBase.
  25. */
  26. PyDoc_STRVAR(bufferediobase_doc,
  27. "Base class for buffered IO objects.\n"
  28. "\n"
  29. "The main difference with RawIOBase is that the read() method\n"
  30. "supports omitting the size argument, and does not have a default\n"
  31. "implementation that defers to readinto().\n"
  32. "\n"
  33. "In addition, read(), readinto() and write() may raise\n"
  34. "BlockingIOError if the underlying raw stream is in non-blocking\n"
  35. "mode and not ready; unlike their raw counterparts, they will never\n"
  36. "return None.\n"
  37. "\n"
  38. "A typical implementation should not inherit from a RawIOBase\n"
  39. "implementation, but wrap one.\n"
  40. );
  41. static PyObject *
  42. _bufferediobase_readinto_generic(PyObject *self, Py_buffer *buffer, char readinto1)
  43. {
  44. Py_ssize_t len;
  45. PyObject *data;
  46. PyObject *attr = readinto1
  47. ? &_Py_ID(read1)
  48. : &_Py_ID(read);
  49. data = _PyObject_CallMethod(self, attr, "n", buffer->len);
  50. if (data == NULL)
  51. return NULL;
  52. if (!PyBytes_Check(data)) {
  53. Py_DECREF(data);
  54. PyErr_SetString(PyExc_TypeError, "read() should return bytes");
  55. return NULL;
  56. }
  57. len = PyBytes_GET_SIZE(data);
  58. if (len > buffer->len) {
  59. PyErr_Format(PyExc_ValueError,
  60. "read() returned too much data: "
  61. "%zd bytes requested, %zd returned",
  62. buffer->len, len);
  63. Py_DECREF(data);
  64. return NULL;
  65. }
  66. memcpy(buffer->buf, PyBytes_AS_STRING(data), len);
  67. Py_DECREF(data);
  68. return PyLong_FromSsize_t(len);
  69. }
  70. /*[clinic input]
  71. _io._BufferedIOBase.readinto
  72. buffer: Py_buffer(accept={rwbuffer})
  73. /
  74. [clinic start generated code]*/
  75. static PyObject *
  76. _io__BufferedIOBase_readinto_impl(PyObject *self, Py_buffer *buffer)
  77. /*[clinic end generated code: output=8c8cda6684af8038 input=00a6b9a38f29830a]*/
  78. {
  79. return _bufferediobase_readinto_generic(self, buffer, 0);
  80. }
  81. /*[clinic input]
  82. _io._BufferedIOBase.readinto1
  83. buffer: Py_buffer(accept={rwbuffer})
  84. /
  85. [clinic start generated code]*/
  86. static PyObject *
  87. _io__BufferedIOBase_readinto1_impl(PyObject *self, Py_buffer *buffer)
  88. /*[clinic end generated code: output=358623e4fd2b69d3 input=ebad75b4aadfb9be]*/
  89. {
  90. return _bufferediobase_readinto_generic(self, buffer, 1);
  91. }
  92. static PyObject *
  93. bufferediobase_unsupported(_PyIO_State *state, const char *message)
  94. {
  95. PyErr_SetString(state->unsupported_operation, message);
  96. return NULL;
  97. }
  98. /*[clinic input]
  99. _io._BufferedIOBase.detach
  100. cls: defining_class
  101. /
  102. Disconnect this buffer from its underlying raw stream and return it.
  103. After the raw stream has been detached, the buffer is in an unusable
  104. state.
  105. [clinic start generated code]*/
  106. static PyObject *
  107. _io__BufferedIOBase_detach_impl(PyObject *self, PyTypeObject *cls)
  108. /*[clinic end generated code: output=b87b135d67cd4448 input=0b61a7b4357c1ea7]*/
  109. {
  110. _PyIO_State *state = get_io_state_by_cls(cls);
  111. return bufferediobase_unsupported(state, "detach");
  112. }
  113. /*[clinic input]
  114. _io._BufferedIOBase.read
  115. cls: defining_class
  116. size: int(unused=True) = -1
  117. /
  118. Read and return up to n bytes.
  119. If the size argument is omitted, None, or negative, read and
  120. return all data until EOF.
  121. If the size argument is positive, and the underlying raw stream is
  122. not 'interactive', multiple raw reads may be issued to satisfy
  123. the byte count (unless EOF is reached first).
  124. However, for interactive raw streams (as well as sockets and pipes),
  125. at most one raw read will be issued, and a short result does not
  126. imply that EOF is imminent.
  127. Return an empty bytes object on EOF.
  128. Return None if the underlying raw stream was open in non-blocking
  129. mode and no data is available at the moment.
  130. [clinic start generated code]*/
  131. static PyObject *
  132. _io__BufferedIOBase_read_impl(PyObject *self, PyTypeObject *cls,
  133. int Py_UNUSED(size))
  134. /*[clinic end generated code: output=aceb2765587b0a29 input=824f6f910465e61a]*/
  135. {
  136. _PyIO_State *state = get_io_state_by_cls(cls);
  137. return bufferediobase_unsupported(state, "read");
  138. }
  139. /*[clinic input]
  140. _io._BufferedIOBase.read1
  141. cls: defining_class
  142. size: int(unused=True) = -1
  143. /
  144. Read and return up to size bytes, with at most one read() call to the underlying raw stream.
  145. Return an empty bytes object on EOF.
  146. A short result does not imply that EOF is imminent.
  147. [clinic start generated code]*/
  148. static PyObject *
  149. _io__BufferedIOBase_read1_impl(PyObject *self, PyTypeObject *cls,
  150. int Py_UNUSED(size))
  151. /*[clinic end generated code: output=2e7fc62972487eaa input=af76380e020fd9e6]*/
  152. {
  153. _PyIO_State *state = get_io_state_by_cls(cls);
  154. return bufferediobase_unsupported(state, "read1");
  155. }
  156. /*[clinic input]
  157. _io._BufferedIOBase.write
  158. cls: defining_class
  159. b: object(unused=True)
  160. /
  161. Write buffer b to the IO stream.
  162. Return the number of bytes written, which is always
  163. the length of b in bytes.
  164. Raise BlockingIOError if the buffer is full and the
  165. underlying raw stream cannot accept more data at the moment.
  166. [clinic start generated code]*/
  167. static PyObject *
  168. _io__BufferedIOBase_write_impl(PyObject *self, PyTypeObject *cls,
  169. PyObject *Py_UNUSED(b))
  170. /*[clinic end generated code: output=712c635246bf2306 input=9793f5c8f71029ad]*/
  171. {
  172. _PyIO_State *state = get_io_state_by_cls(cls);
  173. return bufferediobase_unsupported(state, "write");
  174. }
  175. typedef struct {
  176. PyObject_HEAD
  177. PyObject *raw;
  178. int ok; /* Initialized? */
  179. int detached;
  180. int readable;
  181. int writable;
  182. char finalizing;
  183. /* True if this is a vanilla Buffered object (rather than a user derived
  184. class) *and* the raw stream is a vanilla FileIO object. */
  185. int fast_closed_checks;
  186. /* Absolute position inside the raw stream (-1 if unknown). */
  187. Py_off_t abs_pos;
  188. /* A static buffer of size `buffer_size` */
  189. char *buffer;
  190. /* Current logical position in the buffer. */
  191. Py_off_t pos;
  192. /* Position of the raw stream in the buffer. */
  193. Py_off_t raw_pos;
  194. /* Just after the last buffered byte in the buffer, or -1 if the buffer
  195. isn't ready for reading. */
  196. Py_off_t read_end;
  197. /* Just after the last byte actually written */
  198. Py_off_t write_pos;
  199. /* Just after the last byte waiting to be written, or -1 if the buffer
  200. isn't ready for writing. */
  201. Py_off_t write_end;
  202. PyThread_type_lock lock;
  203. volatile unsigned long owner;
  204. Py_ssize_t buffer_size;
  205. Py_ssize_t buffer_mask;
  206. PyObject *dict;
  207. PyObject *weakreflist;
  208. } buffered;
  209. /*
  210. Implementation notes:
  211. * BufferedReader, BufferedWriter and BufferedRandom try to share most
  212. methods (this is helped by the members `readable` and `writable`, which
  213. are initialized in the respective constructors)
  214. * They also share a single buffer for reading and writing. This enables
  215. interleaved reads and writes without flushing. It also makes the logic
  216. a bit trickier to get right.
  217. * The absolute position of the raw stream is cached, if possible, in the
  218. `abs_pos` member. It must be updated every time an operation is done
  219. on the raw stream. If not sure, it can be reinitialized by calling
  220. _buffered_raw_tell(), which queries the raw stream (_buffered_raw_seek()
  221. also does it). To read it, use RAW_TELL().
  222. * Three helpers, _bufferedreader_raw_read, _bufferedwriter_raw_write and
  223. _bufferedwriter_flush_unlocked do a lot of useful housekeeping.
  224. NOTE: we should try to maintain block alignment of reads and writes to the
  225. raw stream (according to the buffer size), but for now it is only done
  226. in read() and friends.
  227. */
  228. /* These macros protect the buffered object against concurrent operations. */
  229. static int
  230. _enter_buffered_busy(buffered *self)
  231. {
  232. int relax_locking;
  233. PyLockStatus st;
  234. if (self->owner == PyThread_get_thread_ident()) {
  235. PyErr_Format(PyExc_RuntimeError,
  236. "reentrant call inside %R", self);
  237. return 0;
  238. }
  239. PyInterpreterState *interp = PyInterpreterState_Get();
  240. relax_locking = _Py_IsInterpreterFinalizing(interp);
  241. Py_BEGIN_ALLOW_THREADS
  242. if (!relax_locking)
  243. st = PyThread_acquire_lock(self->lock, 1);
  244. else {
  245. /* When finalizing, we don't want a deadlock to happen with daemon
  246. * threads abruptly shut down while they owned the lock.
  247. * Therefore, only wait for a grace period (1 s.).
  248. * Note that non-daemon threads have already exited here, so this
  249. * shouldn't affect carefully written threaded I/O code.
  250. */
  251. st = PyThread_acquire_lock_timed(self->lock, (PY_TIMEOUT_T)1e6, 0);
  252. }
  253. Py_END_ALLOW_THREADS
  254. if (relax_locking && st != PY_LOCK_ACQUIRED) {
  255. PyObject *ascii = PyObject_ASCII((PyObject*)self);
  256. _Py_FatalErrorFormat(__func__,
  257. "could not acquire lock for %s at interpreter "
  258. "shutdown, possibly due to daemon threads",
  259. ascii ? PyUnicode_AsUTF8(ascii) : "<ascii(self) failed>");
  260. }
  261. return 1;
  262. }
  263. #define ENTER_BUFFERED(self) \
  264. ( (PyThread_acquire_lock(self->lock, 0) ? \
  265. 1 : _enter_buffered_busy(self)) \
  266. && (self->owner = PyThread_get_thread_ident(), 1) )
  267. #define LEAVE_BUFFERED(self) \
  268. do { \
  269. self->owner = 0; \
  270. PyThread_release_lock(self->lock); \
  271. } while(0);
  272. #define CHECK_INITIALIZED(self) \
  273. if (self->ok <= 0) { \
  274. if (self->detached) { \
  275. PyErr_SetString(PyExc_ValueError, \
  276. "raw stream has been detached"); \
  277. } else { \
  278. PyErr_SetString(PyExc_ValueError, \
  279. "I/O operation on uninitialized object"); \
  280. } \
  281. return NULL; \
  282. }
  283. #define CHECK_INITIALIZED_INT(self) \
  284. if (self->ok <= 0) { \
  285. if (self->detached) { \
  286. PyErr_SetString(PyExc_ValueError, \
  287. "raw stream has been detached"); \
  288. } else { \
  289. PyErr_SetString(PyExc_ValueError, \
  290. "I/O operation on uninitialized object"); \
  291. } \
  292. return -1; \
  293. }
  294. #define IS_CLOSED(self) \
  295. (!self->buffer || \
  296. (self->fast_closed_checks \
  297. ? _PyFileIO_closed(self->raw) \
  298. : buffered_closed(self)))
  299. #define CHECK_CLOSED(self, error_msg) \
  300. if (IS_CLOSED(self) && (Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t) == 0)) { \
  301. PyErr_SetString(PyExc_ValueError, error_msg); \
  302. return NULL; \
  303. } \
  304. #define VALID_READ_BUFFER(self) \
  305. (self->readable && self->read_end != -1)
  306. #define VALID_WRITE_BUFFER(self) \
  307. (self->writable && self->write_end != -1)
  308. #define ADJUST_POSITION(self, _new_pos) \
  309. do { \
  310. self->pos = _new_pos; \
  311. if (VALID_READ_BUFFER(self) && self->read_end < self->pos) \
  312. self->read_end = self->pos; \
  313. } while(0)
  314. #define READAHEAD(self) \
  315. ((self->readable && VALID_READ_BUFFER(self)) \
  316. ? (self->read_end - self->pos) : 0)
  317. #define RAW_OFFSET(self) \
  318. (((VALID_READ_BUFFER(self) || VALID_WRITE_BUFFER(self)) \
  319. && self->raw_pos >= 0) ? self->raw_pos - self->pos : 0)
  320. #define RAW_TELL(self) \
  321. (self->abs_pos != -1 ? self->abs_pos : _buffered_raw_tell(self))
  322. #define MINUS_LAST_BLOCK(self, size) \
  323. (self->buffer_mask ? \
  324. (size & ~self->buffer_mask) : \
  325. (self->buffer_size * (size / self->buffer_size)))
  326. static int
  327. buffered_clear(buffered *self)
  328. {
  329. self->ok = 0;
  330. Py_CLEAR(self->raw);
  331. Py_CLEAR(self->dict);
  332. return 0;
  333. }
  334. static void
  335. buffered_dealloc(buffered *self)
  336. {
  337. PyTypeObject *tp = Py_TYPE(self);
  338. self->finalizing = 1;
  339. if (_PyIOBase_finalize((PyObject *) self) < 0)
  340. return;
  341. _PyObject_GC_UNTRACK(self);
  342. self->ok = 0;
  343. if (self->weakreflist != NULL)
  344. PyObject_ClearWeakRefs((PyObject *)self);
  345. if (self->buffer) {
  346. PyMem_Free(self->buffer);
  347. self->buffer = NULL;
  348. }
  349. if (self->lock) {
  350. PyThread_free_lock(self->lock);
  351. self->lock = NULL;
  352. }
  353. (void)buffered_clear(self);
  354. tp->tp_free((PyObject *)self);
  355. Py_DECREF(tp);
  356. }
  357. /*[clinic input]
  358. _io._Buffered.__sizeof__
  359. [clinic start generated code]*/
  360. static PyObject *
  361. _io__Buffered___sizeof___impl(buffered *self)
  362. /*[clinic end generated code: output=0231ef7f5053134e input=753c782d808d34df]*/
  363. {
  364. size_t res = _PyObject_SIZE(Py_TYPE(self));
  365. if (self->buffer) {
  366. res += (size_t)self->buffer_size;
  367. }
  368. return PyLong_FromSize_t(res);
  369. }
  370. static int
  371. buffered_traverse(buffered *self, visitproc visit, void *arg)
  372. {
  373. Py_VISIT(Py_TYPE(self));
  374. Py_VISIT(self->raw);
  375. Py_VISIT(self->dict);
  376. return 0;
  377. }
  378. /* Because this can call arbitrary code, it shouldn't be called when
  379. the refcount is 0 (that is, not directly from tp_dealloc unless
  380. the refcount has been temporarily re-incremented). */
  381. /*[clinic input]
  382. _io._Buffered._dealloc_warn
  383. source: object
  384. /
  385. [clinic start generated code]*/
  386. static PyObject *
  387. _io__Buffered__dealloc_warn(buffered *self, PyObject *source)
  388. /*[clinic end generated code: output=690dcc3df8967162 input=8f845f2a4786391c]*/
  389. {
  390. if (self->ok && self->raw) {
  391. PyObject *r;
  392. r = PyObject_CallMethodOneArg(self->raw, &_Py_ID(_dealloc_warn), source);
  393. if (r)
  394. Py_DECREF(r);
  395. else
  396. PyErr_Clear();
  397. }
  398. Py_RETURN_NONE;
  399. }
  400. /*
  401. * _BufferedIOMixin methods
  402. * This is not a class, just a collection of methods that will be reused
  403. * by BufferedReader and BufferedWriter
  404. */
  405. /* Flush and close */
  406. /*[clinic input]
  407. _io._Buffered.flush as _io__Buffered_simple_flush
  408. [clinic start generated code]*/
  409. static PyObject *
  410. _io__Buffered_simple_flush_impl(buffered *self)
  411. /*[clinic end generated code: output=29ebb3820db1bdfd input=f33ef045e7250767]*/
  412. {
  413. CHECK_INITIALIZED(self)
  414. return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(flush));
  415. }
  416. static int
  417. buffered_closed(buffered *self)
  418. {
  419. int closed;
  420. PyObject *res;
  421. CHECK_INITIALIZED_INT(self)
  422. res = PyObject_GetAttr(self->raw, &_Py_ID(closed));
  423. if (res == NULL)
  424. return -1;
  425. closed = PyObject_IsTrue(res);
  426. Py_DECREF(res);
  427. return closed;
  428. }
  429. static PyObject *
  430. buffered_closed_get(buffered *self, void *context)
  431. {
  432. CHECK_INITIALIZED(self)
  433. return PyObject_GetAttr(self->raw, &_Py_ID(closed));
  434. }
  435. /*[clinic input]
  436. _io._Buffered.close
  437. [clinic start generated code]*/
  438. static PyObject *
  439. _io__Buffered_close_impl(buffered *self)
  440. /*[clinic end generated code: output=7280b7b42033be0c input=d20b83d1ddd7d805]*/
  441. {
  442. PyObject *res = NULL;
  443. int r;
  444. CHECK_INITIALIZED(self)
  445. if (!ENTER_BUFFERED(self)) {
  446. return NULL;
  447. }
  448. r = buffered_closed(self);
  449. if (r < 0)
  450. goto end;
  451. if (r > 0) {
  452. res = Py_NewRef(Py_None);
  453. goto end;
  454. }
  455. if (self->finalizing) {
  456. PyObject *r = _io__Buffered__dealloc_warn(self, (PyObject *) self);
  457. if (r)
  458. Py_DECREF(r);
  459. else
  460. PyErr_Clear();
  461. }
  462. /* flush() will most probably re-take the lock, so drop it first */
  463. LEAVE_BUFFERED(self)
  464. res = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(flush));
  465. if (!ENTER_BUFFERED(self)) {
  466. return NULL;
  467. }
  468. PyObject *exc = NULL;
  469. if (res == NULL) {
  470. exc = PyErr_GetRaisedException();
  471. }
  472. else {
  473. Py_DECREF(res);
  474. }
  475. res = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(close));
  476. if (self->buffer) {
  477. PyMem_Free(self->buffer);
  478. self->buffer = NULL;
  479. }
  480. if (exc != NULL) {
  481. _PyErr_ChainExceptions1(exc);
  482. Py_CLEAR(res);
  483. }
  484. self->read_end = 0;
  485. self->pos = 0;
  486. end:
  487. LEAVE_BUFFERED(self)
  488. return res;
  489. }
  490. /*[clinic input]
  491. _io._Buffered.detach
  492. [clinic start generated code]*/
  493. static PyObject *
  494. _io__Buffered_detach_impl(buffered *self)
  495. /*[clinic end generated code: output=dd0fc057b8b779f7 input=482762a345cc9f44]*/
  496. {
  497. PyObject *raw, *res;
  498. CHECK_INITIALIZED(self)
  499. res = PyObject_CallMethodNoArgs((PyObject *)self, &_Py_ID(flush));
  500. if (res == NULL)
  501. return NULL;
  502. Py_DECREF(res);
  503. raw = self->raw;
  504. self->raw = NULL;
  505. self->detached = 1;
  506. self->ok = 0;
  507. return raw;
  508. }
  509. /* Inquiries */
  510. /*[clinic input]
  511. _io._Buffered.seekable
  512. [clinic start generated code]*/
  513. static PyObject *
  514. _io__Buffered_seekable_impl(buffered *self)
  515. /*[clinic end generated code: output=90172abb5ceb6e8f input=7d35764f5fb5262b]*/
  516. {
  517. CHECK_INITIALIZED(self)
  518. return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(seekable));
  519. }
  520. /*[clinic input]
  521. _io._Buffered.readable
  522. [clinic start generated code]*/
  523. static PyObject *
  524. _io__Buffered_readable_impl(buffered *self)
  525. /*[clinic end generated code: output=92afa07661ecb698 input=640619addb513b8b]*/
  526. {
  527. CHECK_INITIALIZED(self)
  528. return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(readable));
  529. }
  530. /*[clinic input]
  531. _io._Buffered.writable
  532. [clinic start generated code]*/
  533. static PyObject *
  534. _io__Buffered_writable_impl(buffered *self)
  535. /*[clinic end generated code: output=4e3eee8d6f9d8552 input=b35ea396b2201554]*/
  536. {
  537. CHECK_INITIALIZED(self)
  538. return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(writable));
  539. }
  540. static PyObject *
  541. buffered_name_get(buffered *self, void *context)
  542. {
  543. CHECK_INITIALIZED(self)
  544. return PyObject_GetAttr(self->raw, &_Py_ID(name));
  545. }
  546. static PyObject *
  547. buffered_mode_get(buffered *self, void *context)
  548. {
  549. CHECK_INITIALIZED(self)
  550. return PyObject_GetAttr(self->raw, &_Py_ID(mode));
  551. }
  552. /* Lower-level APIs */
  553. /*[clinic input]
  554. _io._Buffered.fileno
  555. [clinic start generated code]*/
  556. static PyObject *
  557. _io__Buffered_fileno_impl(buffered *self)
  558. /*[clinic end generated code: output=b717648d58a95ee3 input=768ea30b3f6314a7]*/
  559. {
  560. CHECK_INITIALIZED(self)
  561. return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(fileno));
  562. }
  563. /*[clinic input]
  564. _io._Buffered.isatty
  565. [clinic start generated code]*/
  566. static PyObject *
  567. _io__Buffered_isatty_impl(buffered *self)
  568. /*[clinic end generated code: output=c20e55caae67baea input=9ea007b11559bee4]*/
  569. {
  570. CHECK_INITIALIZED(self)
  571. return PyObject_CallMethodNoArgs(self->raw, &_Py_ID(isatty));
  572. }
  573. /* Forward decls */
  574. static PyObject *
  575. _bufferedwriter_flush_unlocked(buffered *);
  576. static Py_ssize_t
  577. _bufferedreader_fill_buffer(buffered *self);
  578. static void
  579. _bufferedreader_reset_buf(buffered *self);
  580. static void
  581. _bufferedwriter_reset_buf(buffered *self);
  582. static PyObject *
  583. _bufferedreader_peek_unlocked(buffered *self);
  584. static PyObject *
  585. _bufferedreader_read_all(buffered *self);
  586. static PyObject *
  587. _bufferedreader_read_fast(buffered *self, Py_ssize_t);
  588. static PyObject *
  589. _bufferedreader_read_generic(buffered *self, Py_ssize_t);
  590. static Py_ssize_t
  591. _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len);
  592. /*
  593. * Helpers
  594. */
  595. /* Sets the current error to BlockingIOError */
  596. static void
  597. _set_BlockingIOError(const char *msg, Py_ssize_t written)
  598. {
  599. PyObject *err;
  600. PyErr_Clear();
  601. err = PyObject_CallFunction(PyExc_BlockingIOError, "isn",
  602. errno, msg, written);
  603. if (err)
  604. PyErr_SetObject(PyExc_BlockingIOError, err);
  605. Py_XDECREF(err);
  606. }
  607. /* Returns the address of the `written` member if a BlockingIOError was
  608. raised, NULL otherwise. The error is always re-raised. */
  609. static Py_ssize_t *
  610. _buffered_check_blocking_error(void)
  611. {
  612. PyObject *exc = PyErr_GetRaisedException();
  613. if (exc == NULL || !PyErr_GivenExceptionMatches(exc, PyExc_BlockingIOError)) {
  614. PyErr_SetRaisedException(exc);
  615. return NULL;
  616. }
  617. PyOSErrorObject *err = (PyOSErrorObject *)exc;
  618. /* TODO: sanity check (err->written >= 0) */
  619. PyErr_SetRaisedException(exc);
  620. return &err->written;
  621. }
  622. static Py_off_t
  623. _buffered_raw_tell(buffered *self)
  624. {
  625. Py_off_t n;
  626. PyObject *res;
  627. res = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(tell));
  628. if (res == NULL)
  629. return -1;
  630. n = PyNumber_AsOff_t(res, PyExc_ValueError);
  631. Py_DECREF(res);
  632. if (n < 0) {
  633. if (!PyErr_Occurred())
  634. PyErr_Format(PyExc_OSError,
  635. "Raw stream returned invalid position %" PY_PRIdOFF,
  636. (PY_OFF_T_COMPAT)n);
  637. return -1;
  638. }
  639. self->abs_pos = n;
  640. return n;
  641. }
  642. static Py_off_t
  643. _buffered_raw_seek(buffered *self, Py_off_t target, int whence)
  644. {
  645. PyObject *res, *posobj, *whenceobj;
  646. Py_off_t n;
  647. posobj = PyLong_FromOff_t(target);
  648. if (posobj == NULL)
  649. return -1;
  650. whenceobj = PyLong_FromLong(whence);
  651. if (whenceobj == NULL) {
  652. Py_DECREF(posobj);
  653. return -1;
  654. }
  655. res = PyObject_CallMethodObjArgs(self->raw, &_Py_ID(seek),
  656. posobj, whenceobj, NULL);
  657. Py_DECREF(posobj);
  658. Py_DECREF(whenceobj);
  659. if (res == NULL)
  660. return -1;
  661. n = PyNumber_AsOff_t(res, PyExc_ValueError);
  662. Py_DECREF(res);
  663. if (n < 0) {
  664. if (!PyErr_Occurred())
  665. PyErr_Format(PyExc_OSError,
  666. "Raw stream returned invalid position %" PY_PRIdOFF,
  667. (PY_OFF_T_COMPAT)n);
  668. return -1;
  669. }
  670. self->abs_pos = n;
  671. return n;
  672. }
  673. static int
  674. _buffered_init(buffered *self)
  675. {
  676. Py_ssize_t n;
  677. if (self->buffer_size <= 0) {
  678. PyErr_SetString(PyExc_ValueError,
  679. "buffer size must be strictly positive");
  680. return -1;
  681. }
  682. if (self->buffer)
  683. PyMem_Free(self->buffer);
  684. self->buffer = PyMem_Malloc(self->buffer_size);
  685. if (self->buffer == NULL) {
  686. PyErr_NoMemory();
  687. return -1;
  688. }
  689. if (self->lock)
  690. PyThread_free_lock(self->lock);
  691. self->lock = PyThread_allocate_lock();
  692. if (self->lock == NULL) {
  693. PyErr_SetString(PyExc_RuntimeError, "can't allocate read lock");
  694. return -1;
  695. }
  696. self->owner = 0;
  697. /* Find out whether buffer_size is a power of 2 */
  698. /* XXX is this optimization useful? */
  699. for (n = self->buffer_size - 1; n & 1; n >>= 1)
  700. ;
  701. if (n == 0)
  702. self->buffer_mask = self->buffer_size - 1;
  703. else
  704. self->buffer_mask = 0;
  705. if (_buffered_raw_tell(self) == -1)
  706. PyErr_Clear();
  707. return 0;
  708. }
  709. /* Return 1 if an OSError with errno == EINTR is set (and then
  710. clears the error indicator), 0 otherwise.
  711. Should only be called when PyErr_Occurred() is true.
  712. */
  713. int
  714. _PyIO_trap_eintr(void)
  715. {
  716. if (!PyErr_ExceptionMatches(PyExc_OSError)) {
  717. return 0;
  718. }
  719. PyObject *exc = PyErr_GetRaisedException();
  720. PyOSErrorObject *env_err = (PyOSErrorObject *)exc;
  721. assert(env_err != NULL);
  722. if (env_err->myerrno != NULL) {
  723. assert(EINTR > 0 && EINTR < INT_MAX);
  724. assert(PyLong_CheckExact(env_err->myerrno));
  725. int overflow;
  726. int myerrno = PyLong_AsLongAndOverflow(env_err->myerrno, &overflow);
  727. PyErr_Clear();
  728. if (myerrno == EINTR) {
  729. Py_DECREF(exc);
  730. return 1;
  731. }
  732. }
  733. /* This silences any error set by PyObject_RichCompareBool() */
  734. PyErr_SetRaisedException(exc);
  735. return 0;
  736. }
  737. /*
  738. * Shared methods and wrappers
  739. */
  740. static PyObject *
  741. buffered_flush_and_rewind_unlocked(buffered *self)
  742. {
  743. PyObject *res;
  744. res = _bufferedwriter_flush_unlocked(self);
  745. if (res == NULL)
  746. return NULL;
  747. Py_DECREF(res);
  748. if (self->readable) {
  749. /* Rewind the raw stream so that its position corresponds to
  750. the current logical position. */
  751. Py_off_t n;
  752. n = _buffered_raw_seek(self, -RAW_OFFSET(self), 1);
  753. _bufferedreader_reset_buf(self);
  754. if (n == -1)
  755. return NULL;
  756. }
  757. Py_RETURN_NONE;
  758. }
  759. /*[clinic input]
  760. _io._Buffered.flush
  761. [clinic start generated code]*/
  762. static PyObject *
  763. _io__Buffered_flush_impl(buffered *self)
  764. /*[clinic end generated code: output=da2674ef1ce71f3a input=fda63444697c6bf4]*/
  765. {
  766. PyObject *res;
  767. CHECK_INITIALIZED(self)
  768. CHECK_CLOSED(self, "flush of closed file")
  769. if (!ENTER_BUFFERED(self))
  770. return NULL;
  771. res = buffered_flush_and_rewind_unlocked(self);
  772. LEAVE_BUFFERED(self)
  773. return res;
  774. }
  775. /*[clinic input]
  776. _io._Buffered.peek
  777. size: Py_ssize_t = 0
  778. /
  779. [clinic start generated code]*/
  780. static PyObject *
  781. _io__Buffered_peek_impl(buffered *self, Py_ssize_t size)
  782. /*[clinic end generated code: output=ba7a097ca230102b input=37ffb97d06ff4adb]*/
  783. {
  784. PyObject *res = NULL;
  785. CHECK_INITIALIZED(self)
  786. CHECK_CLOSED(self, "peek of closed file")
  787. if (!ENTER_BUFFERED(self))
  788. return NULL;
  789. if (self->writable) {
  790. res = buffered_flush_and_rewind_unlocked(self);
  791. if (res == NULL)
  792. goto end;
  793. Py_CLEAR(res);
  794. }
  795. res = _bufferedreader_peek_unlocked(self);
  796. end:
  797. LEAVE_BUFFERED(self)
  798. return res;
  799. }
  800. /*[clinic input]
  801. _io._Buffered.read
  802. size as n: Py_ssize_t(accept={int, NoneType}) = -1
  803. /
  804. [clinic start generated code]*/
  805. static PyObject *
  806. _io__Buffered_read_impl(buffered *self, Py_ssize_t n)
  807. /*[clinic end generated code: output=f41c78bb15b9bbe9 input=7df81e82e08a68a2]*/
  808. {
  809. PyObject *res;
  810. CHECK_INITIALIZED(self)
  811. if (n < -1) {
  812. PyErr_SetString(PyExc_ValueError,
  813. "read length must be non-negative or -1");
  814. return NULL;
  815. }
  816. CHECK_CLOSED(self, "read of closed file")
  817. if (n == -1) {
  818. /* The number of bytes is unspecified, read until the end of stream */
  819. if (!ENTER_BUFFERED(self))
  820. return NULL;
  821. res = _bufferedreader_read_all(self);
  822. }
  823. else {
  824. res = _bufferedreader_read_fast(self, n);
  825. if (res != Py_None)
  826. return res;
  827. Py_DECREF(res);
  828. if (!ENTER_BUFFERED(self))
  829. return NULL;
  830. res = _bufferedreader_read_generic(self, n);
  831. }
  832. LEAVE_BUFFERED(self)
  833. return res;
  834. }
  835. /*[clinic input]
  836. _io._Buffered.read1
  837. size as n: Py_ssize_t = -1
  838. /
  839. [clinic start generated code]*/
  840. static PyObject *
  841. _io__Buffered_read1_impl(buffered *self, Py_ssize_t n)
  842. /*[clinic end generated code: output=bcc4fb4e54d103a3 input=7d22de9630b61774]*/
  843. {
  844. Py_ssize_t have, r;
  845. PyObject *res = NULL;
  846. CHECK_INITIALIZED(self)
  847. if (n < 0) {
  848. n = self->buffer_size;
  849. }
  850. CHECK_CLOSED(self, "read of closed file")
  851. if (n == 0)
  852. return PyBytes_FromStringAndSize(NULL, 0);
  853. /* Return up to n bytes. If at least one byte is buffered, we
  854. only return buffered bytes. Otherwise, we do one raw read. */
  855. have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
  856. if (have > 0) {
  857. n = Py_MIN(have, n);
  858. res = _bufferedreader_read_fast(self, n);
  859. assert(res != Py_None);
  860. return res;
  861. }
  862. res = PyBytes_FromStringAndSize(NULL, n);
  863. if (res == NULL)
  864. return NULL;
  865. if (!ENTER_BUFFERED(self)) {
  866. Py_DECREF(res);
  867. return NULL;
  868. }
  869. /* Flush the write buffer if necessary */
  870. if (self->writable) {
  871. PyObject *r = buffered_flush_and_rewind_unlocked(self);
  872. if (r == NULL) {
  873. LEAVE_BUFFERED(self)
  874. Py_DECREF(res);
  875. return NULL;
  876. }
  877. Py_DECREF(r);
  878. }
  879. _bufferedreader_reset_buf(self);
  880. r = _bufferedreader_raw_read(self, PyBytes_AS_STRING(res), n);
  881. LEAVE_BUFFERED(self)
  882. if (r == -1) {
  883. Py_DECREF(res);
  884. return NULL;
  885. }
  886. if (r == -2)
  887. r = 0;
  888. if (n > r)
  889. _PyBytes_Resize(&res, r);
  890. return res;
  891. }
  892. static PyObject *
  893. _buffered_readinto_generic(buffered *self, Py_buffer *buffer, char readinto1)
  894. {
  895. Py_ssize_t n, written = 0, remaining;
  896. PyObject *res = NULL;
  897. CHECK_INITIALIZED(self)
  898. CHECK_CLOSED(self, "readinto of closed file")
  899. n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
  900. if (n > 0) {
  901. if (n >= buffer->len) {
  902. memcpy(buffer->buf, self->buffer + self->pos, buffer->len);
  903. self->pos += buffer->len;
  904. return PyLong_FromSsize_t(buffer->len);
  905. }
  906. memcpy(buffer->buf, self->buffer + self->pos, n);
  907. self->pos += n;
  908. written = n;
  909. }
  910. if (!ENTER_BUFFERED(self))
  911. return NULL;
  912. if (self->writable) {
  913. res = buffered_flush_and_rewind_unlocked(self);
  914. if (res == NULL)
  915. goto end;
  916. Py_CLEAR(res);
  917. }
  918. _bufferedreader_reset_buf(self);
  919. self->pos = 0;
  920. for (remaining = buffer->len - written;
  921. remaining > 0;
  922. written += n, remaining -= n) {
  923. /* If remaining bytes is larger than internal buffer size, copy
  924. * directly into caller's buffer. */
  925. if (remaining > self->buffer_size) {
  926. n = _bufferedreader_raw_read(self, (char *) buffer->buf + written,
  927. remaining);
  928. }
  929. /* In readinto1 mode, we do not want to fill the internal
  930. buffer if we already have some data to return */
  931. else if (!(readinto1 && written)) {
  932. n = _bufferedreader_fill_buffer(self);
  933. if (n > 0) {
  934. if (n > remaining)
  935. n = remaining;
  936. memcpy((char *) buffer->buf + written,
  937. self->buffer + self->pos, n);
  938. self->pos += n;
  939. continue; /* short circuit */
  940. }
  941. }
  942. else
  943. n = 0;
  944. if (n == 0 || (n == -2 && written > 0))
  945. break;
  946. if (n < 0) {
  947. if (n == -2) {
  948. res = Py_NewRef(Py_None);
  949. }
  950. goto end;
  951. }
  952. /* At most one read in readinto1 mode */
  953. if (readinto1) {
  954. written += n;
  955. break;
  956. }
  957. }
  958. res = PyLong_FromSsize_t(written);
  959. end:
  960. LEAVE_BUFFERED(self);
  961. return res;
  962. }
  963. /*[clinic input]
  964. _io._Buffered.readinto
  965. buffer: Py_buffer(accept={rwbuffer})
  966. /
  967. [clinic start generated code]*/
  968. static PyObject *
  969. _io__Buffered_readinto_impl(buffered *self, Py_buffer *buffer)
  970. /*[clinic end generated code: output=bcb376580b1d8170 input=ed6b98b7a20a3008]*/
  971. {
  972. return _buffered_readinto_generic(self, buffer, 0);
  973. }
  974. /*[clinic input]
  975. _io._Buffered.readinto1
  976. buffer: Py_buffer(accept={rwbuffer})
  977. /
  978. [clinic start generated code]*/
  979. static PyObject *
  980. _io__Buffered_readinto1_impl(buffered *self, Py_buffer *buffer)
  981. /*[clinic end generated code: output=6e5c6ac5868205d6 input=4455c5d55fdf1687]*/
  982. {
  983. return _buffered_readinto_generic(self, buffer, 1);
  984. }
  985. static PyObject *
  986. _buffered_readline(buffered *self, Py_ssize_t limit)
  987. {
  988. PyObject *res = NULL;
  989. PyObject *chunks = NULL;
  990. Py_ssize_t n;
  991. const char *start, *s, *end;
  992. CHECK_CLOSED(self, "readline of closed file")
  993. /* First, try to find a line in the buffer. This can run unlocked because
  994. the calls to the C API are simple enough that they can't trigger
  995. any thread switch. */
  996. n = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
  997. if (limit >= 0 && n > limit)
  998. n = limit;
  999. start = self->buffer + self->pos;
  1000. s = memchr(start, '\n', n);
  1001. if (s != NULL) {
  1002. res = PyBytes_FromStringAndSize(start, s - start + 1);
  1003. if (res != NULL)
  1004. self->pos += s - start + 1;
  1005. goto end_unlocked;
  1006. }
  1007. if (n == limit) {
  1008. res = PyBytes_FromStringAndSize(start, n);
  1009. if (res != NULL)
  1010. self->pos += n;
  1011. goto end_unlocked;
  1012. }
  1013. if (!ENTER_BUFFERED(self))
  1014. goto end_unlocked;
  1015. /* Now we try to get some more from the raw stream */
  1016. chunks = PyList_New(0);
  1017. if (chunks == NULL)
  1018. goto end;
  1019. if (n > 0) {
  1020. res = PyBytes_FromStringAndSize(start, n);
  1021. if (res == NULL)
  1022. goto end;
  1023. if (PyList_Append(chunks, res) < 0) {
  1024. Py_CLEAR(res);
  1025. goto end;
  1026. }
  1027. Py_CLEAR(res);
  1028. self->pos += n;
  1029. if (limit >= 0)
  1030. limit -= n;
  1031. }
  1032. if (self->writable) {
  1033. PyObject *r = buffered_flush_and_rewind_unlocked(self);
  1034. if (r == NULL)
  1035. goto end;
  1036. Py_DECREF(r);
  1037. }
  1038. for (;;) {
  1039. _bufferedreader_reset_buf(self);
  1040. n = _bufferedreader_fill_buffer(self);
  1041. if (n == -1)
  1042. goto end;
  1043. if (n <= 0)
  1044. break;
  1045. if (limit >= 0 && n > limit)
  1046. n = limit;
  1047. start = self->buffer;
  1048. end = start + n;
  1049. s = start;
  1050. while (s < end) {
  1051. if (*s++ == '\n') {
  1052. res = PyBytes_FromStringAndSize(start, s - start);
  1053. if (res == NULL)
  1054. goto end;
  1055. self->pos = s - start;
  1056. goto found;
  1057. }
  1058. }
  1059. res = PyBytes_FromStringAndSize(start, n);
  1060. if (res == NULL)
  1061. goto end;
  1062. if (n == limit) {
  1063. self->pos = n;
  1064. break;
  1065. }
  1066. if (PyList_Append(chunks, res) < 0) {
  1067. Py_CLEAR(res);
  1068. goto end;
  1069. }
  1070. Py_CLEAR(res);
  1071. if (limit >= 0)
  1072. limit -= n;
  1073. }
  1074. found:
  1075. if (res != NULL && PyList_Append(chunks, res) < 0) {
  1076. Py_CLEAR(res);
  1077. goto end;
  1078. }
  1079. Py_XSETREF(res, _PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), chunks));
  1080. end:
  1081. LEAVE_BUFFERED(self)
  1082. end_unlocked:
  1083. Py_XDECREF(chunks);
  1084. return res;
  1085. }
  1086. /*[clinic input]
  1087. _io._Buffered.readline
  1088. size: Py_ssize_t(accept={int, NoneType}) = -1
  1089. /
  1090. [clinic start generated code]*/
  1091. static PyObject *
  1092. _io__Buffered_readline_impl(buffered *self, Py_ssize_t size)
  1093. /*[clinic end generated code: output=24dd2aa6e33be83c input=673b6240e315ef8a]*/
  1094. {
  1095. CHECK_INITIALIZED(self)
  1096. return _buffered_readline(self, size);
  1097. }
  1098. /*[clinic input]
  1099. _io._Buffered.tell
  1100. [clinic start generated code]*/
  1101. static PyObject *
  1102. _io__Buffered_tell_impl(buffered *self)
  1103. /*[clinic end generated code: output=386972ae84716c1e input=ad61e04a6b349573]*/
  1104. {
  1105. Py_off_t pos;
  1106. CHECK_INITIALIZED(self)
  1107. pos = _buffered_raw_tell(self);
  1108. if (pos == -1)
  1109. return NULL;
  1110. pos -= RAW_OFFSET(self);
  1111. // GH-95782
  1112. if (pos < 0)
  1113. pos = 0;
  1114. return PyLong_FromOff_t(pos);
  1115. }
  1116. /*[clinic input]
  1117. _io._Buffered.seek
  1118. target as targetobj: object
  1119. whence: int = 0
  1120. /
  1121. [clinic start generated code]*/
  1122. static PyObject *
  1123. _io__Buffered_seek_impl(buffered *self, PyObject *targetobj, int whence)
  1124. /*[clinic end generated code: output=7ae0e8dc46efdefb input=a9c4920bfcba6163]*/
  1125. {
  1126. Py_off_t target, n;
  1127. PyObject *res = NULL;
  1128. CHECK_INITIALIZED(self)
  1129. /* Do some error checking instead of trusting OS 'seek()'
  1130. ** error detection, just in case.
  1131. */
  1132. if ((whence < 0 || whence >2)
  1133. #ifdef SEEK_HOLE
  1134. && (whence != SEEK_HOLE)
  1135. #endif
  1136. #ifdef SEEK_DATA
  1137. && (whence != SEEK_DATA)
  1138. #endif
  1139. ) {
  1140. PyErr_Format(PyExc_ValueError,
  1141. "whence value %d unsupported", whence);
  1142. return NULL;
  1143. }
  1144. CHECK_CLOSED(self, "seek of closed file")
  1145. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  1146. if (_PyIOBase_check_seekable(state, self->raw, Py_True) == NULL) {
  1147. return NULL;
  1148. }
  1149. target = PyNumber_AsOff_t(targetobj, PyExc_ValueError);
  1150. if (target == -1 && PyErr_Occurred())
  1151. return NULL;
  1152. /* SEEK_SET and SEEK_CUR are special because we could seek inside the
  1153. buffer. Other whence values must be managed without this optimization.
  1154. Some Operating Systems can provide additional values, like
  1155. SEEK_HOLE/SEEK_DATA. */
  1156. if (((whence == 0) || (whence == 1)) && self->readable) {
  1157. Py_off_t current, avail;
  1158. /* Check if seeking leaves us inside the current buffer,
  1159. so as to return quickly if possible. Also, we needn't take the
  1160. lock in this fast path.
  1161. Don't know how to do that when whence == 2, though. */
  1162. /* NOTE: RAW_TELL() can release the GIL but the object is in a stable
  1163. state at this point. */
  1164. current = RAW_TELL(self);
  1165. avail = READAHEAD(self);
  1166. if (avail > 0) {
  1167. Py_off_t offset;
  1168. if (whence == 0)
  1169. offset = target - (current - RAW_OFFSET(self));
  1170. else
  1171. offset = target;
  1172. if (offset >= -self->pos && offset <= avail) {
  1173. self->pos += offset;
  1174. // GH-95782
  1175. if (current - avail + offset < 0)
  1176. return PyLong_FromOff_t(0);
  1177. return PyLong_FromOff_t(current - avail + offset);
  1178. }
  1179. }
  1180. }
  1181. if (!ENTER_BUFFERED(self))
  1182. return NULL;
  1183. /* Fallback: invoke raw seek() method and clear buffer */
  1184. if (self->writable) {
  1185. res = _bufferedwriter_flush_unlocked(self);
  1186. if (res == NULL)
  1187. goto end;
  1188. Py_CLEAR(res);
  1189. }
  1190. /* TODO: align on block boundary and read buffer if needed? */
  1191. if (whence == 1)
  1192. target -= RAW_OFFSET(self);
  1193. n = _buffered_raw_seek(self, target, whence);
  1194. if (n == -1)
  1195. goto end;
  1196. self->raw_pos = -1;
  1197. res = PyLong_FromOff_t(n);
  1198. if (res != NULL && self->readable)
  1199. _bufferedreader_reset_buf(self);
  1200. end:
  1201. LEAVE_BUFFERED(self)
  1202. return res;
  1203. }
  1204. /*[clinic input]
  1205. _io._Buffered.truncate
  1206. cls: defining_class
  1207. pos: object = None
  1208. /
  1209. [clinic start generated code]*/
  1210. static PyObject *
  1211. _io__Buffered_truncate_impl(buffered *self, PyTypeObject *cls, PyObject *pos)
  1212. /*[clinic end generated code: output=fe3882fbffe79f1a input=f5b737d97d76303f]*/
  1213. {
  1214. PyObject *res = NULL;
  1215. CHECK_INITIALIZED(self)
  1216. CHECK_CLOSED(self, "truncate of closed file")
  1217. if (!self->writable) {
  1218. _PyIO_State *state = get_io_state_by_cls(cls);
  1219. return bufferediobase_unsupported(state, "truncate");
  1220. }
  1221. if (!ENTER_BUFFERED(self))
  1222. return NULL;
  1223. res = buffered_flush_and_rewind_unlocked(self);
  1224. if (res == NULL) {
  1225. goto end;
  1226. }
  1227. Py_CLEAR(res);
  1228. res = PyObject_CallMethodOneArg(self->raw, &_Py_ID(truncate), pos);
  1229. if (res == NULL)
  1230. goto end;
  1231. /* Reset cached position */
  1232. if (_buffered_raw_tell(self) == -1)
  1233. PyErr_Clear();
  1234. end:
  1235. LEAVE_BUFFERED(self)
  1236. return res;
  1237. }
  1238. static PyObject *
  1239. buffered_iternext(buffered *self)
  1240. {
  1241. PyObject *line;
  1242. PyTypeObject *tp;
  1243. CHECK_INITIALIZED(self);
  1244. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  1245. tp = Py_TYPE(self);
  1246. if (Py_IS_TYPE(tp, state->PyBufferedReader_Type) ||
  1247. Py_IS_TYPE(tp, state->PyBufferedRandom_Type))
  1248. {
  1249. /* Skip method call overhead for speed */
  1250. line = _buffered_readline(self, -1);
  1251. }
  1252. else {
  1253. line = PyObject_CallMethodNoArgs((PyObject *)self,
  1254. &_Py_ID(readline));
  1255. if (line && !PyBytes_Check(line)) {
  1256. PyErr_Format(PyExc_OSError,
  1257. "readline() should have returned a bytes object, "
  1258. "not '%.200s'", Py_TYPE(line)->tp_name);
  1259. Py_DECREF(line);
  1260. return NULL;
  1261. }
  1262. }
  1263. if (line == NULL)
  1264. return NULL;
  1265. if (PyBytes_GET_SIZE(line) == 0) {
  1266. /* Reached EOF or would have blocked */
  1267. Py_DECREF(line);
  1268. return NULL;
  1269. }
  1270. return line;
  1271. }
  1272. static PyObject *
  1273. buffered_repr(buffered *self)
  1274. {
  1275. PyObject *nameobj, *res;
  1276. if (_PyObject_LookupAttr((PyObject *) self, &_Py_ID(name), &nameobj) < 0) {
  1277. if (!PyErr_ExceptionMatches(PyExc_ValueError)) {
  1278. return NULL;
  1279. }
  1280. /* Ignore ValueError raised if the underlying stream was detached */
  1281. PyErr_Clear();
  1282. }
  1283. if (nameobj == NULL) {
  1284. res = PyUnicode_FromFormat("<%s>", Py_TYPE(self)->tp_name);
  1285. }
  1286. else {
  1287. int status = Py_ReprEnter((PyObject *)self);
  1288. res = NULL;
  1289. if (status == 0) {
  1290. res = PyUnicode_FromFormat("<%s name=%R>",
  1291. Py_TYPE(self)->tp_name, nameobj);
  1292. Py_ReprLeave((PyObject *)self);
  1293. }
  1294. else if (status > 0) {
  1295. PyErr_Format(PyExc_RuntimeError,
  1296. "reentrant call inside %s.__repr__",
  1297. Py_TYPE(self)->tp_name);
  1298. }
  1299. Py_DECREF(nameobj);
  1300. }
  1301. return res;
  1302. }
  1303. /*
  1304. * class BufferedReader
  1305. */
  1306. static void _bufferedreader_reset_buf(buffered *self)
  1307. {
  1308. self->read_end = -1;
  1309. }
  1310. /*[clinic input]
  1311. _io.BufferedReader.__init__
  1312. raw: object
  1313. buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
  1314. Create a new buffered reader using the given readable raw IO object.
  1315. [clinic start generated code]*/
  1316. static int
  1317. _io_BufferedReader___init___impl(buffered *self, PyObject *raw,
  1318. Py_ssize_t buffer_size)
  1319. /*[clinic end generated code: output=cddcfefa0ed294c4 input=fb887e06f11b4e48]*/
  1320. {
  1321. self->ok = 0;
  1322. self->detached = 0;
  1323. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  1324. if (_PyIOBase_check_readable(state, raw, Py_True) == NULL) {
  1325. return -1;
  1326. }
  1327. Py_XSETREF(self->raw, Py_NewRef(raw));
  1328. self->buffer_size = buffer_size;
  1329. self->readable = 1;
  1330. self->writable = 0;
  1331. if (_buffered_init(self) < 0)
  1332. return -1;
  1333. _bufferedreader_reset_buf(self);
  1334. self->fast_closed_checks = (
  1335. Py_IS_TYPE(self, state->PyBufferedReader_Type) &&
  1336. Py_IS_TYPE(raw, state->PyFileIO_Type)
  1337. );
  1338. self->ok = 1;
  1339. return 0;
  1340. }
  1341. static Py_ssize_t
  1342. _bufferedreader_raw_read(buffered *self, char *start, Py_ssize_t len)
  1343. {
  1344. Py_buffer buf;
  1345. PyObject *memobj, *res;
  1346. Py_ssize_t n;
  1347. /* NOTE: the buffer needn't be released as its object is NULL. */
  1348. if (PyBuffer_FillInfo(&buf, NULL, start, len, 0, PyBUF_CONTIG) == -1)
  1349. return -1;
  1350. memobj = PyMemoryView_FromBuffer(&buf);
  1351. if (memobj == NULL)
  1352. return -1;
  1353. /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR
  1354. occurs so we needn't do it ourselves.
  1355. We then retry reading, ignoring the signal if no handler has
  1356. raised (see issue #10956).
  1357. */
  1358. do {
  1359. res = PyObject_CallMethodOneArg(self->raw, &_Py_ID(readinto), memobj);
  1360. } while (res == NULL && _PyIO_trap_eintr());
  1361. Py_DECREF(memobj);
  1362. if (res == NULL)
  1363. return -1;
  1364. if (res == Py_None) {
  1365. /* Non-blocking stream would have blocked. Special return code! */
  1366. Py_DECREF(res);
  1367. return -2;
  1368. }
  1369. n = PyNumber_AsSsize_t(res, PyExc_ValueError);
  1370. Py_DECREF(res);
  1371. if (n == -1 && PyErr_Occurred()) {
  1372. _PyErr_FormatFromCause(
  1373. PyExc_OSError,
  1374. "raw readinto() failed"
  1375. );
  1376. return -1;
  1377. }
  1378. if (n < 0 || n > len) {
  1379. PyErr_Format(PyExc_OSError,
  1380. "raw readinto() returned invalid length %zd "
  1381. "(should have been between 0 and %zd)", n, len);
  1382. return -1;
  1383. }
  1384. if (n > 0 && self->abs_pos != -1)
  1385. self->abs_pos += n;
  1386. return n;
  1387. }
  1388. static Py_ssize_t
  1389. _bufferedreader_fill_buffer(buffered *self)
  1390. {
  1391. Py_ssize_t start, len, n;
  1392. if (VALID_READ_BUFFER(self))
  1393. start = Py_SAFE_DOWNCAST(self->read_end, Py_off_t, Py_ssize_t);
  1394. else
  1395. start = 0;
  1396. len = self->buffer_size - start;
  1397. n = _bufferedreader_raw_read(self, self->buffer + start, len);
  1398. if (n <= 0)
  1399. return n;
  1400. self->read_end = start + n;
  1401. self->raw_pos = start + n;
  1402. return n;
  1403. }
  1404. static PyObject *
  1405. _bufferedreader_read_all(buffered *self)
  1406. {
  1407. Py_ssize_t current_size;
  1408. PyObject *res = NULL, *data = NULL, *tmp = NULL, *chunks = NULL, *readall;
  1409. /* First copy what we have in the current buffer. */
  1410. current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
  1411. if (current_size) {
  1412. data = PyBytes_FromStringAndSize(
  1413. self->buffer + self->pos, current_size);
  1414. if (data == NULL)
  1415. return NULL;
  1416. self->pos += current_size;
  1417. }
  1418. /* We're going past the buffer's bounds, flush it */
  1419. if (self->writable) {
  1420. tmp = buffered_flush_and_rewind_unlocked(self);
  1421. if (tmp == NULL)
  1422. goto cleanup;
  1423. Py_CLEAR(tmp);
  1424. }
  1425. _bufferedreader_reset_buf(self);
  1426. if (_PyObject_LookupAttr(self->raw, &_Py_ID(readall), &readall) < 0) {
  1427. goto cleanup;
  1428. }
  1429. if (readall) {
  1430. tmp = _PyObject_CallNoArgs(readall);
  1431. Py_DECREF(readall);
  1432. if (tmp == NULL)
  1433. goto cleanup;
  1434. if (tmp != Py_None && !PyBytes_Check(tmp)) {
  1435. PyErr_SetString(PyExc_TypeError, "readall() should return bytes");
  1436. goto cleanup;
  1437. }
  1438. if (current_size == 0) {
  1439. res = tmp;
  1440. } else {
  1441. if (tmp != Py_None) {
  1442. PyBytes_Concat(&data, tmp);
  1443. }
  1444. res = data;
  1445. }
  1446. goto cleanup;
  1447. }
  1448. chunks = PyList_New(0);
  1449. if (chunks == NULL)
  1450. goto cleanup;
  1451. while (1) {
  1452. if (data) {
  1453. if (PyList_Append(chunks, data) < 0)
  1454. goto cleanup;
  1455. Py_CLEAR(data);
  1456. }
  1457. /* Read until EOF or until read() would block. */
  1458. data = PyObject_CallMethodNoArgs(self->raw, &_Py_ID(read));
  1459. if (data == NULL)
  1460. goto cleanup;
  1461. if (data != Py_None && !PyBytes_Check(data)) {
  1462. PyErr_SetString(PyExc_TypeError, "read() should return bytes");
  1463. goto cleanup;
  1464. }
  1465. if (data == Py_None || PyBytes_GET_SIZE(data) == 0) {
  1466. if (current_size == 0) {
  1467. res = data;
  1468. goto cleanup;
  1469. }
  1470. else {
  1471. tmp = _PyBytes_Join((PyObject *)&_Py_SINGLETON(bytes_empty), chunks);
  1472. res = tmp;
  1473. goto cleanup;
  1474. }
  1475. }
  1476. current_size += PyBytes_GET_SIZE(data);
  1477. if (self->abs_pos != -1)
  1478. self->abs_pos += PyBytes_GET_SIZE(data);
  1479. }
  1480. cleanup:
  1481. /* res is either NULL or a borrowed ref */
  1482. Py_XINCREF(res);
  1483. Py_XDECREF(data);
  1484. Py_XDECREF(tmp);
  1485. Py_XDECREF(chunks);
  1486. return res;
  1487. }
  1488. /* Read n bytes from the buffer if it can, otherwise return None.
  1489. This function is simple enough that it can run unlocked. */
  1490. static PyObject *
  1491. _bufferedreader_read_fast(buffered *self, Py_ssize_t n)
  1492. {
  1493. Py_ssize_t current_size;
  1494. current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
  1495. if (n <= current_size) {
  1496. /* Fast path: the data to read is fully buffered. */
  1497. PyObject *res = PyBytes_FromStringAndSize(self->buffer + self->pos, n);
  1498. if (res != NULL)
  1499. self->pos += n;
  1500. return res;
  1501. }
  1502. Py_RETURN_NONE;
  1503. }
  1504. /* Generic read function: read from the stream until enough bytes are read,
  1505. * or until an EOF occurs or until read() would block.
  1506. */
  1507. static PyObject *
  1508. _bufferedreader_read_generic(buffered *self, Py_ssize_t n)
  1509. {
  1510. PyObject *res = NULL;
  1511. Py_ssize_t current_size, remaining, written;
  1512. char *out;
  1513. current_size = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
  1514. if (n <= current_size)
  1515. return _bufferedreader_read_fast(self, n);
  1516. res = PyBytes_FromStringAndSize(NULL, n);
  1517. if (res == NULL)
  1518. goto error;
  1519. out = PyBytes_AS_STRING(res);
  1520. remaining = n;
  1521. written = 0;
  1522. if (current_size > 0) {
  1523. memcpy(out, self->buffer + self->pos, current_size);
  1524. remaining -= current_size;
  1525. written += current_size;
  1526. self->pos += current_size;
  1527. }
  1528. /* Flush the write buffer if necessary */
  1529. if (self->writable) {
  1530. PyObject *r = buffered_flush_and_rewind_unlocked(self);
  1531. if (r == NULL)
  1532. goto error;
  1533. Py_DECREF(r);
  1534. }
  1535. _bufferedreader_reset_buf(self);
  1536. while (remaining > 0) {
  1537. /* We want to read a whole block at the end into buffer.
  1538. If we had readv() we could do this in one pass. */
  1539. Py_ssize_t r = MINUS_LAST_BLOCK(self, remaining);
  1540. if (r == 0)
  1541. break;
  1542. r = _bufferedreader_raw_read(self, out + written, r);
  1543. if (r == -1)
  1544. goto error;
  1545. if (r == 0 || r == -2) {
  1546. /* EOF occurred or read() would block. */
  1547. if (r == 0 || written > 0) {
  1548. if (_PyBytes_Resize(&res, written))
  1549. goto error;
  1550. return res;
  1551. }
  1552. Py_DECREF(res);
  1553. Py_RETURN_NONE;
  1554. }
  1555. remaining -= r;
  1556. written += r;
  1557. }
  1558. assert(remaining <= self->buffer_size);
  1559. self->pos = 0;
  1560. self->raw_pos = 0;
  1561. self->read_end = 0;
  1562. /* NOTE: when the read is satisfied, we avoid issuing any additional
  1563. reads, which could block indefinitely (e.g. on a socket).
  1564. See issue #9550. */
  1565. while (remaining > 0 && self->read_end < self->buffer_size) {
  1566. Py_ssize_t r = _bufferedreader_fill_buffer(self);
  1567. if (r == -1)
  1568. goto error;
  1569. if (r == 0 || r == -2) {
  1570. /* EOF occurred or read() would block. */
  1571. if (r == 0 || written > 0) {
  1572. if (_PyBytes_Resize(&res, written))
  1573. goto error;
  1574. return res;
  1575. }
  1576. Py_DECREF(res);
  1577. Py_RETURN_NONE;
  1578. }
  1579. if (remaining > r) {
  1580. memcpy(out + written, self->buffer + self->pos, r);
  1581. written += r;
  1582. self->pos += r;
  1583. remaining -= r;
  1584. }
  1585. else if (remaining > 0) {
  1586. memcpy(out + written, self->buffer + self->pos, remaining);
  1587. written += remaining;
  1588. self->pos += remaining;
  1589. remaining = 0;
  1590. }
  1591. if (remaining == 0)
  1592. break;
  1593. }
  1594. return res;
  1595. error:
  1596. Py_XDECREF(res);
  1597. return NULL;
  1598. }
  1599. static PyObject *
  1600. _bufferedreader_peek_unlocked(buffered *self)
  1601. {
  1602. Py_ssize_t have, r;
  1603. have = Py_SAFE_DOWNCAST(READAHEAD(self), Py_off_t, Py_ssize_t);
  1604. /* Constraints:
  1605. 1. we don't want to advance the file position.
  1606. 2. we don't want to lose block alignment, so we can't shift the buffer
  1607. to make some place.
  1608. Therefore, we either return `have` bytes (if > 0), or a full buffer.
  1609. */
  1610. if (have > 0) {
  1611. return PyBytes_FromStringAndSize(self->buffer + self->pos, have);
  1612. }
  1613. /* Fill the buffer from the raw stream, and copy it to the result. */
  1614. _bufferedreader_reset_buf(self);
  1615. r = _bufferedreader_fill_buffer(self);
  1616. if (r == -1)
  1617. return NULL;
  1618. if (r == -2)
  1619. r = 0;
  1620. self->pos = 0;
  1621. return PyBytes_FromStringAndSize(self->buffer, r);
  1622. }
  1623. /*
  1624. * class BufferedWriter
  1625. */
  1626. static void
  1627. _bufferedwriter_reset_buf(buffered *self)
  1628. {
  1629. self->write_pos = 0;
  1630. self->write_end = -1;
  1631. }
  1632. /*[clinic input]
  1633. _io.BufferedWriter.__init__
  1634. raw: object
  1635. buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
  1636. A buffer for a writeable sequential RawIO object.
  1637. The constructor creates a BufferedWriter for the given writeable raw
  1638. stream. If the buffer_size is not given, it defaults to
  1639. DEFAULT_BUFFER_SIZE.
  1640. [clinic start generated code]*/
  1641. static int
  1642. _io_BufferedWriter___init___impl(buffered *self, PyObject *raw,
  1643. Py_ssize_t buffer_size)
  1644. /*[clinic end generated code: output=c8942a020c0dee64 input=914be9b95e16007b]*/
  1645. {
  1646. self->ok = 0;
  1647. self->detached = 0;
  1648. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  1649. if (_PyIOBase_check_writable(state, raw, Py_True) == NULL) {
  1650. return -1;
  1651. }
  1652. Py_INCREF(raw);
  1653. Py_XSETREF(self->raw, raw);
  1654. self->readable = 0;
  1655. self->writable = 1;
  1656. self->buffer_size = buffer_size;
  1657. if (_buffered_init(self) < 0)
  1658. return -1;
  1659. _bufferedwriter_reset_buf(self);
  1660. self->pos = 0;
  1661. self->fast_closed_checks = (
  1662. Py_IS_TYPE(self, state->PyBufferedWriter_Type) &&
  1663. Py_IS_TYPE(raw, state->PyFileIO_Type)
  1664. );
  1665. self->ok = 1;
  1666. return 0;
  1667. }
  1668. static Py_ssize_t
  1669. _bufferedwriter_raw_write(buffered *self, char *start, Py_ssize_t len)
  1670. {
  1671. Py_buffer buf;
  1672. PyObject *memobj, *res;
  1673. Py_ssize_t n;
  1674. int errnum;
  1675. /* NOTE: the buffer needn't be released as its object is NULL. */
  1676. if (PyBuffer_FillInfo(&buf, NULL, start, len, 1, PyBUF_CONTIG_RO) == -1)
  1677. return -1;
  1678. memobj = PyMemoryView_FromBuffer(&buf);
  1679. if (memobj == NULL)
  1680. return -1;
  1681. /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals() when EINTR
  1682. occurs so we needn't do it ourselves.
  1683. We then retry writing, ignoring the signal if no handler has
  1684. raised (see issue #10956).
  1685. */
  1686. do {
  1687. errno = 0;
  1688. res = PyObject_CallMethodOneArg(self->raw, &_Py_ID(write), memobj);
  1689. errnum = errno;
  1690. } while (res == NULL && _PyIO_trap_eintr());
  1691. Py_DECREF(memobj);
  1692. if (res == NULL)
  1693. return -1;
  1694. if (res == Py_None) {
  1695. /* Non-blocking stream would have blocked. Special return code!
  1696. Being paranoid we reset errno in case it is changed by code
  1697. triggered by a decref. errno is used by _set_BlockingIOError(). */
  1698. Py_DECREF(res);
  1699. errno = errnum;
  1700. return -2;
  1701. }
  1702. n = PyNumber_AsSsize_t(res, PyExc_ValueError);
  1703. Py_DECREF(res);
  1704. if (n < 0 || n > len) {
  1705. PyErr_Format(PyExc_OSError,
  1706. "raw write() returned invalid length %zd "
  1707. "(should have been between 0 and %zd)", n, len);
  1708. return -1;
  1709. }
  1710. if (n > 0 && self->abs_pos != -1)
  1711. self->abs_pos += n;
  1712. return n;
  1713. }
  1714. static PyObject *
  1715. _bufferedwriter_flush_unlocked(buffered *self)
  1716. {
  1717. Py_off_t n, rewind;
  1718. if (!VALID_WRITE_BUFFER(self) || self->write_pos == self->write_end)
  1719. goto end;
  1720. /* First, rewind */
  1721. rewind = RAW_OFFSET(self) + (self->pos - self->write_pos);
  1722. if (rewind != 0) {
  1723. n = _buffered_raw_seek(self, -rewind, 1);
  1724. if (n < 0) {
  1725. goto error;
  1726. }
  1727. self->raw_pos -= rewind;
  1728. }
  1729. while (self->write_pos < self->write_end) {
  1730. n = _bufferedwriter_raw_write(self,
  1731. self->buffer + self->write_pos,
  1732. Py_SAFE_DOWNCAST(self->write_end - self->write_pos,
  1733. Py_off_t, Py_ssize_t));
  1734. if (n == -1) {
  1735. goto error;
  1736. }
  1737. else if (n == -2) {
  1738. _set_BlockingIOError("write could not complete without blocking",
  1739. 0);
  1740. goto error;
  1741. }
  1742. self->write_pos += n;
  1743. self->raw_pos = self->write_pos;
  1744. /* Partial writes can return successfully when interrupted by a
  1745. signal (see write(2)). We must run signal handlers before
  1746. blocking another time, possibly indefinitely. */
  1747. if (PyErr_CheckSignals() < 0)
  1748. goto error;
  1749. }
  1750. end:
  1751. /* This ensures that after return from this function,
  1752. VALID_WRITE_BUFFER(self) returns false.
  1753. This is a required condition because when a tell() is called
  1754. after flushing and if VALID_READ_BUFFER(self) is false, we need
  1755. VALID_WRITE_BUFFER(self) to be false to have
  1756. RAW_OFFSET(self) == 0.
  1757. Issue: https://bugs.python.org/issue32228 */
  1758. _bufferedwriter_reset_buf(self);
  1759. Py_RETURN_NONE;
  1760. error:
  1761. return NULL;
  1762. }
  1763. /*[clinic input]
  1764. _io.BufferedWriter.write
  1765. buffer: Py_buffer
  1766. /
  1767. [clinic start generated code]*/
  1768. static PyObject *
  1769. _io_BufferedWriter_write_impl(buffered *self, Py_buffer *buffer)
  1770. /*[clinic end generated code: output=7f8d1365759bfc6b input=dd87dd85fc7f8850]*/
  1771. {
  1772. PyObject *res = NULL;
  1773. Py_ssize_t written, avail, remaining;
  1774. Py_off_t offset;
  1775. CHECK_INITIALIZED(self)
  1776. if (!ENTER_BUFFERED(self))
  1777. return NULL;
  1778. /* Issue #31976: Check for closed file after acquiring the lock. Another
  1779. thread could be holding the lock while closing the file. */
  1780. if (IS_CLOSED(self)) {
  1781. PyErr_SetString(PyExc_ValueError, "write to closed file");
  1782. goto error;
  1783. }
  1784. /* Fast path: the data to write can be fully buffered. */
  1785. if (!VALID_READ_BUFFER(self) && !VALID_WRITE_BUFFER(self)) {
  1786. self->pos = 0;
  1787. self->raw_pos = 0;
  1788. }
  1789. avail = Py_SAFE_DOWNCAST(self->buffer_size - self->pos, Py_off_t, Py_ssize_t);
  1790. if (buffer->len <= avail) {
  1791. memcpy(self->buffer + self->pos, buffer->buf, buffer->len);
  1792. if (!VALID_WRITE_BUFFER(self) || self->write_pos > self->pos) {
  1793. self->write_pos = self->pos;
  1794. }
  1795. ADJUST_POSITION(self, self->pos + buffer->len);
  1796. if (self->pos > self->write_end)
  1797. self->write_end = self->pos;
  1798. written = buffer->len;
  1799. goto end;
  1800. }
  1801. /* First write the current buffer */
  1802. res = _bufferedwriter_flush_unlocked(self);
  1803. if (res == NULL) {
  1804. Py_ssize_t *w = _buffered_check_blocking_error();
  1805. if (w == NULL)
  1806. goto error;
  1807. if (self->readable)
  1808. _bufferedreader_reset_buf(self);
  1809. /* Make some place by shifting the buffer. */
  1810. assert(VALID_WRITE_BUFFER(self));
  1811. memmove(self->buffer, self->buffer + self->write_pos,
  1812. Py_SAFE_DOWNCAST(self->write_end - self->write_pos,
  1813. Py_off_t, Py_ssize_t));
  1814. self->write_end -= self->write_pos;
  1815. self->raw_pos -= self->write_pos;
  1816. self->pos -= self->write_pos;
  1817. self->write_pos = 0;
  1818. avail = Py_SAFE_DOWNCAST(self->buffer_size - self->write_end,
  1819. Py_off_t, Py_ssize_t);
  1820. if (buffer->len <= avail) {
  1821. /* Everything can be buffered */
  1822. PyErr_Clear();
  1823. memcpy(self->buffer + self->write_end, buffer->buf, buffer->len);
  1824. self->write_end += buffer->len;
  1825. self->pos += buffer->len;
  1826. written = buffer->len;
  1827. goto end;
  1828. }
  1829. /* Buffer as much as possible. */
  1830. memcpy(self->buffer + self->write_end, buffer->buf, avail);
  1831. self->write_end += avail;
  1832. self->pos += avail;
  1833. /* XXX Modifying the existing exception e using the pointer w
  1834. will change e.characters_written but not e.args[2].
  1835. Therefore we just replace with a new error. */
  1836. _set_BlockingIOError("write could not complete without blocking",
  1837. avail);
  1838. goto error;
  1839. }
  1840. Py_CLEAR(res);
  1841. /* Adjust the raw stream position if it is away from the logical stream
  1842. position. This happens if the read buffer has been filled but not
  1843. modified (and therefore _bufferedwriter_flush_unlocked() didn't rewind
  1844. the raw stream by itself).
  1845. Fixes issue #6629.
  1846. */
  1847. offset = RAW_OFFSET(self);
  1848. if (offset != 0) {
  1849. if (_buffered_raw_seek(self, -offset, 1) < 0)
  1850. goto error;
  1851. self->raw_pos -= offset;
  1852. }
  1853. /* Then write buf itself. At this point the buffer has been emptied. */
  1854. remaining = buffer->len;
  1855. written = 0;
  1856. while (remaining > self->buffer_size) {
  1857. Py_ssize_t n = _bufferedwriter_raw_write(
  1858. self, (char *) buffer->buf + written, buffer->len - written);
  1859. if (n == -1) {
  1860. goto error;
  1861. } else if (n == -2) {
  1862. /* Write failed because raw file is non-blocking */
  1863. if (remaining > self->buffer_size) {
  1864. /* Can't buffer everything, still buffer as much as possible */
  1865. memcpy(self->buffer,
  1866. (char *) buffer->buf + written, self->buffer_size);
  1867. self->raw_pos = 0;
  1868. ADJUST_POSITION(self, self->buffer_size);
  1869. self->write_end = self->buffer_size;
  1870. written += self->buffer_size;
  1871. _set_BlockingIOError("write could not complete without "
  1872. "blocking", written);
  1873. goto error;
  1874. }
  1875. PyErr_Clear();
  1876. break;
  1877. }
  1878. written += n;
  1879. remaining -= n;
  1880. /* Partial writes can return successfully when interrupted by a
  1881. signal (see write(2)). We must run signal handlers before
  1882. blocking another time, possibly indefinitely. */
  1883. if (PyErr_CheckSignals() < 0)
  1884. goto error;
  1885. }
  1886. if (self->readable)
  1887. _bufferedreader_reset_buf(self);
  1888. if (remaining > 0) {
  1889. memcpy(self->buffer, (char *) buffer->buf + written, remaining);
  1890. written += remaining;
  1891. }
  1892. self->write_pos = 0;
  1893. /* TODO: sanity check (remaining >= 0) */
  1894. self->write_end = remaining;
  1895. ADJUST_POSITION(self, remaining);
  1896. self->raw_pos = 0;
  1897. end:
  1898. res = PyLong_FromSsize_t(written);
  1899. error:
  1900. LEAVE_BUFFERED(self)
  1901. return res;
  1902. }
  1903. /*
  1904. * BufferedRWPair
  1905. */
  1906. /* XXX The usefulness of this (compared to having two separate IO objects) is
  1907. * questionable.
  1908. */
  1909. typedef struct {
  1910. PyObject_HEAD
  1911. buffered *reader;
  1912. buffered *writer;
  1913. PyObject *dict;
  1914. PyObject *weakreflist;
  1915. } rwpair;
  1916. /*[clinic input]
  1917. _io.BufferedRWPair.__init__
  1918. reader: object
  1919. writer: object
  1920. buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
  1921. /
  1922. A buffered reader and writer object together.
  1923. A buffered reader object and buffered writer object put together to
  1924. form a sequential IO object that can read and write. This is typically
  1925. used with a socket or two-way pipe.
  1926. reader and writer are RawIOBase objects that are readable and
  1927. writeable respectively. If the buffer_size is omitted it defaults to
  1928. DEFAULT_BUFFER_SIZE.
  1929. [clinic start generated code]*/
  1930. static int
  1931. _io_BufferedRWPair___init___impl(rwpair *self, PyObject *reader,
  1932. PyObject *writer, Py_ssize_t buffer_size)
  1933. /*[clinic end generated code: output=327e73d1aee8f984 input=620d42d71f33a031]*/
  1934. {
  1935. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  1936. if (_PyIOBase_check_readable(state, reader, Py_True) == NULL) {
  1937. return -1;
  1938. }
  1939. if (_PyIOBase_check_writable(state, writer, Py_True) == NULL) {
  1940. return -1;
  1941. }
  1942. self->reader = (buffered *) PyObject_CallFunction(
  1943. (PyObject *)state->PyBufferedReader_Type,
  1944. "On", reader, buffer_size);
  1945. if (self->reader == NULL)
  1946. return -1;
  1947. self->writer = (buffered *) PyObject_CallFunction(
  1948. (PyObject *)state->PyBufferedWriter_Type,
  1949. "On", writer, buffer_size);
  1950. if (self->writer == NULL) {
  1951. Py_CLEAR(self->reader);
  1952. return -1;
  1953. }
  1954. return 0;
  1955. }
  1956. static int
  1957. bufferedrwpair_traverse(rwpair *self, visitproc visit, void *arg)
  1958. {
  1959. Py_VISIT(Py_TYPE(self));
  1960. Py_VISIT(self->dict);
  1961. Py_VISIT(self->reader);
  1962. Py_VISIT(self->writer);
  1963. return 0;
  1964. }
  1965. static int
  1966. bufferedrwpair_clear(rwpair *self)
  1967. {
  1968. Py_CLEAR(self->reader);
  1969. Py_CLEAR(self->writer);
  1970. Py_CLEAR(self->dict);
  1971. return 0;
  1972. }
  1973. static void
  1974. bufferedrwpair_dealloc(rwpair *self)
  1975. {
  1976. PyTypeObject *tp = Py_TYPE(self);
  1977. _PyObject_GC_UNTRACK(self);
  1978. if (self->weakreflist != NULL)
  1979. PyObject_ClearWeakRefs((PyObject *)self);
  1980. (void)bufferedrwpair_clear(self);
  1981. tp->tp_free((PyObject *) self);
  1982. Py_DECREF(tp);
  1983. }
  1984. static PyObject *
  1985. _forward_call(buffered *self, PyObject *name, PyObject *args)
  1986. {
  1987. PyObject *func, *ret;
  1988. if (self == NULL) {
  1989. PyErr_SetString(PyExc_ValueError,
  1990. "I/O operation on uninitialized object");
  1991. return NULL;
  1992. }
  1993. func = PyObject_GetAttr((PyObject *)self, name);
  1994. if (func == NULL) {
  1995. PyErr_SetObject(PyExc_AttributeError, name);
  1996. return NULL;
  1997. }
  1998. ret = PyObject_CallObject(func, args);
  1999. Py_DECREF(func);
  2000. return ret;
  2001. }
  2002. static PyObject *
  2003. bufferedrwpair_read(rwpair *self, PyObject *args)
  2004. {
  2005. return _forward_call(self->reader, &_Py_ID(read), args);
  2006. }
  2007. static PyObject *
  2008. bufferedrwpair_peek(rwpair *self, PyObject *args)
  2009. {
  2010. return _forward_call(self->reader, &_Py_ID(peek), args);
  2011. }
  2012. static PyObject *
  2013. bufferedrwpair_read1(rwpair *self, PyObject *args)
  2014. {
  2015. return _forward_call(self->reader, &_Py_ID(read1), args);
  2016. }
  2017. static PyObject *
  2018. bufferedrwpair_readinto(rwpair *self, PyObject *args)
  2019. {
  2020. return _forward_call(self->reader, &_Py_ID(readinto), args);
  2021. }
  2022. static PyObject *
  2023. bufferedrwpair_readinto1(rwpair *self, PyObject *args)
  2024. {
  2025. return _forward_call(self->reader, &_Py_ID(readinto1), args);
  2026. }
  2027. static PyObject *
  2028. bufferedrwpair_write(rwpair *self, PyObject *args)
  2029. {
  2030. return _forward_call(self->writer, &_Py_ID(write), args);
  2031. }
  2032. static PyObject *
  2033. bufferedrwpair_flush(rwpair *self, PyObject *Py_UNUSED(ignored))
  2034. {
  2035. return _forward_call(self->writer, &_Py_ID(flush), NULL);
  2036. }
  2037. static PyObject *
  2038. bufferedrwpair_readable(rwpair *self, PyObject *Py_UNUSED(ignored))
  2039. {
  2040. return _forward_call(self->reader, &_Py_ID(readable), NULL);
  2041. }
  2042. static PyObject *
  2043. bufferedrwpair_writable(rwpair *self, PyObject *Py_UNUSED(ignored))
  2044. {
  2045. return _forward_call(self->writer, &_Py_ID(writable), NULL);
  2046. }
  2047. static PyObject *
  2048. bufferedrwpair_close(rwpair *self, PyObject *Py_UNUSED(ignored))
  2049. {
  2050. PyObject *exc = NULL;
  2051. PyObject *ret = _forward_call(self->writer, &_Py_ID(close), NULL);
  2052. if (ret == NULL) {
  2053. exc = PyErr_GetRaisedException();
  2054. }
  2055. else {
  2056. Py_DECREF(ret);
  2057. }
  2058. ret = _forward_call(self->reader, &_Py_ID(close), NULL);
  2059. if (exc != NULL) {
  2060. _PyErr_ChainExceptions1(exc);
  2061. Py_CLEAR(ret);
  2062. }
  2063. return ret;
  2064. }
  2065. static PyObject *
  2066. bufferedrwpair_isatty(rwpair *self, PyObject *Py_UNUSED(ignored))
  2067. {
  2068. PyObject *ret = _forward_call(self->writer, &_Py_ID(isatty), NULL);
  2069. if (ret != Py_False) {
  2070. /* either True or exception */
  2071. return ret;
  2072. }
  2073. Py_DECREF(ret);
  2074. return _forward_call(self->reader, &_Py_ID(isatty), NULL);
  2075. }
  2076. static PyObject *
  2077. bufferedrwpair_closed_get(rwpair *self, void *context)
  2078. {
  2079. if (self->writer == NULL) {
  2080. PyErr_SetString(PyExc_RuntimeError,
  2081. "the BufferedRWPair object is being garbage-collected");
  2082. return NULL;
  2083. }
  2084. return PyObject_GetAttr((PyObject *) self->writer, &_Py_ID(closed));
  2085. }
  2086. /*
  2087. * BufferedRandom
  2088. */
  2089. /*[clinic input]
  2090. _io.BufferedRandom.__init__
  2091. raw: object
  2092. buffer_size: Py_ssize_t(c_default="DEFAULT_BUFFER_SIZE") = DEFAULT_BUFFER_SIZE
  2093. A buffered interface to random access streams.
  2094. The constructor creates a reader and writer for a seekable stream,
  2095. raw, given in the first argument. If the buffer_size is omitted it
  2096. defaults to DEFAULT_BUFFER_SIZE.
  2097. [clinic start generated code]*/
  2098. static int
  2099. _io_BufferedRandom___init___impl(buffered *self, PyObject *raw,
  2100. Py_ssize_t buffer_size)
  2101. /*[clinic end generated code: output=d3d64eb0f64e64a3 input=a4e818fb86d0e50c]*/
  2102. {
  2103. self->ok = 0;
  2104. self->detached = 0;
  2105. _PyIO_State *state = find_io_state_by_def(Py_TYPE(self));
  2106. if (_PyIOBase_check_seekable(state, raw, Py_True) == NULL) {
  2107. return -1;
  2108. }
  2109. if (_PyIOBase_check_readable(state, raw, Py_True) == NULL) {
  2110. return -1;
  2111. }
  2112. if (_PyIOBase_check_writable(state, raw, Py_True) == NULL) {
  2113. return -1;
  2114. }
  2115. Py_INCREF(raw);
  2116. Py_XSETREF(self->raw, raw);
  2117. self->buffer_size = buffer_size;
  2118. self->readable = 1;
  2119. self->writable = 1;
  2120. if (_buffered_init(self) < 0)
  2121. return -1;
  2122. _bufferedreader_reset_buf(self);
  2123. _bufferedwriter_reset_buf(self);
  2124. self->pos = 0;
  2125. self->fast_closed_checks = (Py_IS_TYPE(self, state->PyBufferedRandom_Type) &&
  2126. Py_IS_TYPE(raw, state->PyFileIO_Type));
  2127. self->ok = 1;
  2128. return 0;
  2129. }
  2130. #define clinic_state() (find_io_state_by_def(Py_TYPE(self)))
  2131. #include "clinic/bufferedio.c.h"
  2132. #undef clinic_state
  2133. static PyMethodDef bufferediobase_methods[] = {
  2134. _IO__BUFFEREDIOBASE_DETACH_METHODDEF
  2135. _IO__BUFFEREDIOBASE_READ_METHODDEF
  2136. _IO__BUFFEREDIOBASE_READ1_METHODDEF
  2137. _IO__BUFFEREDIOBASE_READINTO_METHODDEF
  2138. _IO__BUFFEREDIOBASE_READINTO1_METHODDEF
  2139. _IO__BUFFEREDIOBASE_WRITE_METHODDEF
  2140. {NULL, NULL}
  2141. };
  2142. static PyType_Slot bufferediobase_slots[] = {
  2143. {Py_tp_doc, (void *)bufferediobase_doc},
  2144. {Py_tp_methods, bufferediobase_methods},
  2145. {0, NULL},
  2146. };
  2147. /* Do not set Py_TPFLAGS_HAVE_GC so that tp_traverse and tp_clear are inherited */
  2148. PyType_Spec bufferediobase_spec = {
  2149. .name = "_io._BufferedIOBase",
  2150. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
  2151. Py_TPFLAGS_IMMUTABLETYPE),
  2152. .slots = bufferediobase_slots,
  2153. };
  2154. static PyMethodDef bufferedreader_methods[] = {
  2155. /* BufferedIOMixin methods */
  2156. _IO__BUFFERED_DETACH_METHODDEF
  2157. _IO__BUFFERED_SIMPLE_FLUSH_METHODDEF
  2158. _IO__BUFFERED_CLOSE_METHODDEF
  2159. _IO__BUFFERED_SEEKABLE_METHODDEF
  2160. _IO__BUFFERED_READABLE_METHODDEF
  2161. _IO__BUFFERED_FILENO_METHODDEF
  2162. _IO__BUFFERED_ISATTY_METHODDEF
  2163. _IO__BUFFERED__DEALLOC_WARN_METHODDEF
  2164. _IO__BUFFERED_READ_METHODDEF
  2165. _IO__BUFFERED_PEEK_METHODDEF
  2166. _IO__BUFFERED_READ1_METHODDEF
  2167. _IO__BUFFERED_READINTO_METHODDEF
  2168. _IO__BUFFERED_READINTO1_METHODDEF
  2169. _IO__BUFFERED_READLINE_METHODDEF
  2170. _IO__BUFFERED_SEEK_METHODDEF
  2171. _IO__BUFFERED_TELL_METHODDEF
  2172. _IO__BUFFERED_TRUNCATE_METHODDEF
  2173. _IO__BUFFERED___SIZEOF___METHODDEF
  2174. {"__reduce__", _PyIOBase_cannot_pickle, METH_VARARGS},
  2175. {"__reduce_ex__", _PyIOBase_cannot_pickle, METH_VARARGS},
  2176. {NULL, NULL}
  2177. };
  2178. static PyMemberDef bufferedreader_members[] = {
  2179. {"raw", T_OBJECT, offsetof(buffered, raw), READONLY},
  2180. {"_finalizing", T_BOOL, offsetof(buffered, finalizing), 0},
  2181. {"__weaklistoffset__", T_PYSSIZET, offsetof(buffered, weakreflist), READONLY},
  2182. {"__dictoffset__", T_PYSSIZET, offsetof(buffered, dict), READONLY},
  2183. {NULL}
  2184. };
  2185. static PyGetSetDef bufferedreader_getset[] = {
  2186. {"closed", (getter)buffered_closed_get, NULL, NULL},
  2187. {"name", (getter)buffered_name_get, NULL, NULL},
  2188. {"mode", (getter)buffered_mode_get, NULL, NULL},
  2189. {NULL}
  2190. };
  2191. static PyType_Slot bufferedreader_slots[] = {
  2192. {Py_tp_dealloc, buffered_dealloc},
  2193. {Py_tp_repr, buffered_repr},
  2194. {Py_tp_doc, (void *)_io_BufferedReader___init____doc__},
  2195. {Py_tp_traverse, buffered_traverse},
  2196. {Py_tp_clear, buffered_clear},
  2197. {Py_tp_iternext, buffered_iternext},
  2198. {Py_tp_methods, bufferedreader_methods},
  2199. {Py_tp_members, bufferedreader_members},
  2200. {Py_tp_getset, bufferedreader_getset},
  2201. {Py_tp_init, _io_BufferedReader___init__},
  2202. {0, NULL},
  2203. };
  2204. PyType_Spec bufferedreader_spec = {
  2205. .name = "_io.BufferedReader",
  2206. .basicsize = sizeof(buffered),
  2207. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  2208. Py_TPFLAGS_IMMUTABLETYPE),
  2209. .slots = bufferedreader_slots,
  2210. };
  2211. static PyMethodDef bufferedwriter_methods[] = {
  2212. /* BufferedIOMixin methods */
  2213. _IO__BUFFERED_CLOSE_METHODDEF
  2214. _IO__BUFFERED_DETACH_METHODDEF
  2215. _IO__BUFFERED_SEEKABLE_METHODDEF
  2216. _IO__BUFFERED_WRITABLE_METHODDEF
  2217. _IO__BUFFERED_FILENO_METHODDEF
  2218. _IO__BUFFERED_ISATTY_METHODDEF
  2219. _IO__BUFFERED__DEALLOC_WARN_METHODDEF
  2220. _IO_BUFFEREDWRITER_WRITE_METHODDEF
  2221. _IO__BUFFERED_TRUNCATE_METHODDEF
  2222. _IO__BUFFERED_FLUSH_METHODDEF
  2223. _IO__BUFFERED_SEEK_METHODDEF
  2224. _IO__BUFFERED_TELL_METHODDEF
  2225. _IO__BUFFERED___SIZEOF___METHODDEF
  2226. {"__reduce__", _PyIOBase_cannot_pickle, METH_VARARGS},
  2227. {"__reduce_ex__", _PyIOBase_cannot_pickle, METH_VARARGS},
  2228. {NULL, NULL}
  2229. };
  2230. static PyMemberDef bufferedwriter_members[] = {
  2231. {"raw", T_OBJECT, offsetof(buffered, raw), READONLY},
  2232. {"_finalizing", T_BOOL, offsetof(buffered, finalizing), 0},
  2233. {"__weaklistoffset__", T_PYSSIZET, offsetof(buffered, weakreflist), READONLY},
  2234. {"__dictoffset__", T_PYSSIZET, offsetof(buffered, dict), READONLY},
  2235. {NULL}
  2236. };
  2237. static PyGetSetDef bufferedwriter_getset[] = {
  2238. {"closed", (getter)buffered_closed_get, NULL, NULL},
  2239. {"name", (getter)buffered_name_get, NULL, NULL},
  2240. {"mode", (getter)buffered_mode_get, NULL, NULL},
  2241. {NULL}
  2242. };
  2243. static PyType_Slot bufferedwriter_slots[] = {
  2244. {Py_tp_dealloc, buffered_dealloc},
  2245. {Py_tp_repr, buffered_repr},
  2246. {Py_tp_doc, (void *)_io_BufferedWriter___init____doc__},
  2247. {Py_tp_traverse, buffered_traverse},
  2248. {Py_tp_clear, buffered_clear},
  2249. {Py_tp_methods, bufferedwriter_methods},
  2250. {Py_tp_members, bufferedwriter_members},
  2251. {Py_tp_getset, bufferedwriter_getset},
  2252. {Py_tp_init, _io_BufferedWriter___init__},
  2253. {0, NULL},
  2254. };
  2255. PyType_Spec bufferedwriter_spec = {
  2256. .name = "_io.BufferedWriter",
  2257. .basicsize = sizeof(buffered),
  2258. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  2259. Py_TPFLAGS_IMMUTABLETYPE),
  2260. .slots = bufferedwriter_slots,
  2261. };
  2262. static PyMethodDef bufferedrwpair_methods[] = {
  2263. {"read", (PyCFunction)bufferedrwpair_read, METH_VARARGS},
  2264. {"peek", (PyCFunction)bufferedrwpair_peek, METH_VARARGS},
  2265. {"read1", (PyCFunction)bufferedrwpair_read1, METH_VARARGS},
  2266. {"readinto", (PyCFunction)bufferedrwpair_readinto, METH_VARARGS},
  2267. {"readinto1", (PyCFunction)bufferedrwpair_readinto1, METH_VARARGS},
  2268. {"write", (PyCFunction)bufferedrwpair_write, METH_VARARGS},
  2269. {"flush", (PyCFunction)bufferedrwpair_flush, METH_NOARGS},
  2270. {"readable", (PyCFunction)bufferedrwpair_readable, METH_NOARGS},
  2271. {"writable", (PyCFunction)bufferedrwpair_writable, METH_NOARGS},
  2272. {"close", (PyCFunction)bufferedrwpair_close, METH_NOARGS},
  2273. {"isatty", (PyCFunction)bufferedrwpair_isatty, METH_NOARGS},
  2274. {NULL, NULL}
  2275. };
  2276. static PyMemberDef bufferedrwpair_members[] = {
  2277. {"__weaklistoffset__", T_PYSSIZET, offsetof(rwpair, weakreflist), READONLY},
  2278. {"__dictoffset__", T_PYSSIZET, offsetof(rwpair, dict), READONLY},
  2279. {NULL}
  2280. };
  2281. static PyGetSetDef bufferedrwpair_getset[] = {
  2282. {"closed", (getter)bufferedrwpair_closed_get, NULL, NULL},
  2283. {NULL}
  2284. };
  2285. static PyType_Slot bufferedrwpair_slots[] = {
  2286. {Py_tp_dealloc, bufferedrwpair_dealloc},
  2287. {Py_tp_doc, (void *)_io_BufferedRWPair___init____doc__},
  2288. {Py_tp_traverse, bufferedrwpair_traverse},
  2289. {Py_tp_clear, bufferedrwpair_clear},
  2290. {Py_tp_methods, bufferedrwpair_methods},
  2291. {Py_tp_members, bufferedrwpair_members},
  2292. {Py_tp_getset, bufferedrwpair_getset},
  2293. {Py_tp_init, _io_BufferedRWPair___init__},
  2294. {0, NULL},
  2295. };
  2296. PyType_Spec bufferedrwpair_spec = {
  2297. .name = "_io.BufferedRWPair",
  2298. .basicsize = sizeof(rwpair),
  2299. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  2300. Py_TPFLAGS_IMMUTABLETYPE),
  2301. .slots = bufferedrwpair_slots,
  2302. };
  2303. static PyMethodDef bufferedrandom_methods[] = {
  2304. /* BufferedIOMixin methods */
  2305. _IO__BUFFERED_CLOSE_METHODDEF
  2306. _IO__BUFFERED_DETACH_METHODDEF
  2307. _IO__BUFFERED_SEEKABLE_METHODDEF
  2308. _IO__BUFFERED_READABLE_METHODDEF
  2309. _IO__BUFFERED_WRITABLE_METHODDEF
  2310. _IO__BUFFERED_FILENO_METHODDEF
  2311. _IO__BUFFERED_ISATTY_METHODDEF
  2312. _IO__BUFFERED__DEALLOC_WARN_METHODDEF
  2313. _IO__BUFFERED_FLUSH_METHODDEF
  2314. _IO__BUFFERED_SEEK_METHODDEF
  2315. _IO__BUFFERED_TELL_METHODDEF
  2316. _IO__BUFFERED_TRUNCATE_METHODDEF
  2317. _IO__BUFFERED_READ_METHODDEF
  2318. _IO__BUFFERED_READ1_METHODDEF
  2319. _IO__BUFFERED_READINTO_METHODDEF
  2320. _IO__BUFFERED_READINTO1_METHODDEF
  2321. _IO__BUFFERED_READLINE_METHODDEF
  2322. _IO__BUFFERED_PEEK_METHODDEF
  2323. _IO_BUFFEREDWRITER_WRITE_METHODDEF
  2324. _IO__BUFFERED___SIZEOF___METHODDEF
  2325. {"__reduce__", _PyIOBase_cannot_pickle, METH_VARARGS},
  2326. {"__reduce_ex__", _PyIOBase_cannot_pickle, METH_VARARGS},
  2327. {NULL, NULL}
  2328. };
  2329. static PyMemberDef bufferedrandom_members[] = {
  2330. {"raw", T_OBJECT, offsetof(buffered, raw), READONLY},
  2331. {"_finalizing", T_BOOL, offsetof(buffered, finalizing), 0},
  2332. {"__weaklistoffset__", T_PYSSIZET, offsetof(buffered, weakreflist), READONLY},
  2333. {"__dictoffset__", T_PYSSIZET, offsetof(buffered, dict), READONLY},
  2334. {NULL}
  2335. };
  2336. static PyGetSetDef bufferedrandom_getset[] = {
  2337. {"closed", (getter)buffered_closed_get, NULL, NULL},
  2338. {"name", (getter)buffered_name_get, NULL, NULL},
  2339. {"mode", (getter)buffered_mode_get, NULL, NULL},
  2340. {NULL}
  2341. };
  2342. static PyType_Slot bufferedrandom_slots[] = {
  2343. {Py_tp_dealloc, buffered_dealloc},
  2344. {Py_tp_repr, buffered_repr},
  2345. {Py_tp_doc, (void *)_io_BufferedRandom___init____doc__},
  2346. {Py_tp_traverse, buffered_traverse},
  2347. {Py_tp_clear, buffered_clear},
  2348. {Py_tp_iternext, buffered_iternext},
  2349. {Py_tp_methods, bufferedrandom_methods},
  2350. {Py_tp_members, bufferedrandom_members},
  2351. {Py_tp_getset, bufferedrandom_getset},
  2352. {Py_tp_init, _io_BufferedRandom___init__},
  2353. {0, NULL},
  2354. };
  2355. PyType_Spec bufferedrandom_spec = {
  2356. .name = "_io.BufferedRandom",
  2357. .basicsize = sizeof(buffered),
  2358. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_GC |
  2359. Py_TPFLAGS_IMMUTABLETYPE),
  2360. .slots = bufferedrandom_slots,
  2361. };