blob: 6f5bd48780c02cddcd34c1600e493d6c9d86c773 [file] [log] [blame]
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +00001/*
2 An implementation of the new I/O lib as defined by PEP 3116 - "New I/O"
3
4 Classes defined here: UnsupportedOperation, BlockingIOError.
5 Functions defined here: open().
6
7 Mostly written by Amaury Forgeot d'Arc
8*/
9
10#define PY_SSIZE_T_CLEAN
11#include "Python.h"
12#include "structmember.h"
13#include "_iomodule.h"
14
15#ifdef HAVE_SYS_TYPES_H
16#include <sys/types.h>
17#endif /* HAVE_SYS_TYPES_H */
18
19#ifdef HAVE_SYS_STAT_H
20#include <sys/stat.h>
21#endif /* HAVE_SYS_STAT_H */
22
23
24/* Various interned strings */
25
26PyObject *_PyIO_str_close;
27PyObject *_PyIO_str_closed;
28PyObject *_PyIO_str_decode;
29PyObject *_PyIO_str_encode;
30PyObject *_PyIO_str_fileno;
31PyObject *_PyIO_str_flush;
32PyObject *_PyIO_str_getstate;
33PyObject *_PyIO_str_isatty;
34PyObject *_PyIO_str_newlines;
35PyObject *_PyIO_str_nl;
36PyObject *_PyIO_str_read;
37PyObject *_PyIO_str_read1;
38PyObject *_PyIO_str_readable;
Victor Stinnerb57f1082011-05-26 00:19:38 +020039PyObject *_PyIO_str_readall;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000040PyObject *_PyIO_str_readinto;
41PyObject *_PyIO_str_readline;
42PyObject *_PyIO_str_reset;
43PyObject *_PyIO_str_seek;
44PyObject *_PyIO_str_seekable;
Antoine Pitroue4501852009-05-14 18:55:55 +000045PyObject *_PyIO_str_setstate;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000046PyObject *_PyIO_str_tell;
47PyObject *_PyIO_str_truncate;
48PyObject *_PyIO_str_writable;
49PyObject *_PyIO_str_write;
50
51PyObject *_PyIO_empty_str;
52PyObject *_PyIO_empty_bytes;
Antoine Pitroue4501852009-05-14 18:55:55 +000053PyObject *_PyIO_zero;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000054
55
56PyDoc_STRVAR(module_doc,
57"The io module provides the Python interfaces to stream handling. The\n"
58"builtin open function is defined in this module.\n"
59"\n"
60"At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
61"defines the basic interface to a stream. Note, however, that there is no\n"
62"seperation between reading and writing to streams; implementations are\n"
63"allowed to throw an IOError if they do not support a given operation.\n"
64"\n"
65"Extending IOBase is RawIOBase which deals simply with the reading and\n"
Benjamin Peterson8f2b6652009-04-05 00:46:27 +000066"writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000067"an interface to OS files.\n"
68"\n"
69"BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
70"subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
71"streams that are readable, writable, and both respectively.\n"
72"BufferedRandom provides a buffered interface to random access\n"
73"streams. BytesIO is a simple stream of in-memory bytes.\n"
74"\n"
75"Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
76"of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
77"interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
78"is a in-memory stream for text.\n"
79"\n"
80"Argument names are not part of the specification, and only the arguments\n"
81"of open() are intended to be used as keyword arguments.\n"
82"\n"
83"data:\n"
84"\n"
85"DEFAULT_BUFFER_SIZE\n"
86"\n"
87" An int containing the default buffer size used by the module's buffered\n"
88" I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
89" possible.\n"
90 );
91
92
93/*
94 * BlockingIOError extends IOError
95 */
96
97static int
Benjamin Peterson680bf1a2009-06-12 02:07:12 +000098blockingioerror_init(PyBlockingIOErrorObject *self, PyObject *args,
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +000099 PyObject *kwds)
100{
101 PyObject *myerrno = NULL, *strerror = NULL;
102 PyObject *baseargs = NULL;
103 Py_ssize_t written = 0;
104
105 assert(PyTuple_Check(args));
106
107 self->written = 0;
108 if (!PyArg_ParseTuple(args, "OO|n:BlockingIOError",
109 &myerrno, &strerror, &written))
110 return -1;
111
112 baseargs = PyTuple_Pack(2, myerrno, strerror);
113 if (baseargs == NULL)
114 return -1;
115 /* This will take care of initializing of myerrno and strerror members */
116 if (((PyTypeObject *)PyExc_IOError)->tp_init(
117 (PyObject *)self, baseargs, kwds) == -1) {
118 Py_DECREF(baseargs);
119 return -1;
120 }
121 Py_DECREF(baseargs);
122
123 self->written = written;
124 return 0;
125}
126
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000127static PyMemberDef blockingioerror_members[] = {
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000128 {"characters_written", T_PYSSIZET, offsetof(PyBlockingIOErrorObject, written), 0},
129 {NULL} /* Sentinel */
130};
131
132static PyTypeObject _PyExc_BlockingIOError = {
133 PyVarObject_HEAD_INIT(NULL, 0)
134 "BlockingIOError", /*tp_name*/
135 sizeof(PyBlockingIOErrorObject), /*tp_basicsize*/
136 0, /*tp_itemsize*/
137 0, /*tp_dealloc*/
138 0, /*tp_print*/
139 0, /*tp_getattr*/
140 0, /*tp_setattr*/
141 0, /*tp_compare */
142 0, /*tp_repr*/
143 0, /*tp_as_number*/
144 0, /*tp_as_sequence*/
145 0, /*tp_as_mapping*/
146 0, /*tp_hash */
147 0, /*tp_call*/
148 0, /*tp_str*/
149 0, /*tp_getattro*/
150 0, /*tp_setattro*/
151 0, /*tp_as_buffer*/
152 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /*tp_flags*/
153 PyDoc_STR("Exception raised when I/O would block "
154 "on a non-blocking I/O stream"), /* tp_doc */
155 0, /* tp_traverse */
156 0, /* tp_clear */
157 0, /* tp_richcompare */
158 0, /* tp_weaklistoffset */
159 0, /* tp_iter */
160 0, /* tp_iternext */
161 0, /* tp_methods */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000162 blockingioerror_members, /* tp_members */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000163 0, /* tp_getset */
164 0, /* tp_base */
165 0, /* tp_dict */
166 0, /* tp_descr_get */
167 0, /* tp_descr_set */
168 0, /* tp_dictoffset */
Benjamin Peterson680bf1a2009-06-12 02:07:12 +0000169 (initproc)blockingioerror_init, /* tp_init */
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000170 0, /* tp_alloc */
171 0, /* tp_new */
172};
173PyObject *PyExc_BlockingIOError = (PyObject *)&_PyExc_BlockingIOError;
174
175
176/*
177 * The main open() function
178 */
179PyDoc_STRVAR(open_doc,
Georg Brandle40ee502010-07-11 09:33:39 +0000180"open(file, mode='r', buffering=-1, encoding=None,\n"
Georg Brandl5e8f6d12009-12-23 10:30:45 +0000181" errors=None, newline=None, closefd=True) -> file object\n"
182"\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000183"Open file and return a stream. Raise IOError upon failure.\n"
184"\n"
185"file is either a text or byte string giving the name (and the path\n"
186"if the file isn't in the current working directory) of the file to\n"
187"be opened or an integer file descriptor of the file to be\n"
188"wrapped. (If a file descriptor is given, it is closed when the\n"
189"returned I/O object is closed, unless closefd is set to False.)\n"
190"\n"
191"mode is an optional string that specifies the mode in which the file\n"
192"is opened. It defaults to 'r' which means open for reading in text\n"
193"mode. Other common values are 'w' for writing (truncating the file if\n"
194"it already exists), and 'a' for appending (which on some Unix systems,\n"
195"means that all writes append to the end of the file regardless of the\n"
196"current seek position). In text mode, if encoding is not specified the\n"
197"encoding used is platform dependent. (For reading and writing raw\n"
198"bytes use binary mode and leave encoding unspecified.) The available\n"
199"modes are:\n"
200"\n"
201"========= ===============================================================\n"
202"Character Meaning\n"
203"--------- ---------------------------------------------------------------\n"
204"'r' open for reading (default)\n"
205"'w' open for writing, truncating the file first\n"
206"'a' open for writing, appending to the end of the file if it exists\n"
207"'b' binary mode\n"
208"'t' text mode (default)\n"
209"'+' open a disk file for updating (reading and writing)\n"
210"'U' universal newline mode (for backwards compatibility; unneeded\n"
211" for new code)\n"
212"========= ===============================================================\n"
213"\n"
214"The default mode is 'rt' (open for reading text). For binary random\n"
215"access, the mode 'w+b' opens and truncates the file to 0 bytes, while\n"
216"'r+b' opens the file without truncation.\n"
217"\n"
218"Python distinguishes between files opened in binary and text modes,\n"
219"even when the underlying operating system doesn't. Files opened in\n"
220"binary mode (appending 'b' to the mode argument) return contents as\n"
221"bytes objects without any decoding. In text mode (the default, or when\n"
222"'t' is appended to the mode argument), the contents of the file are\n"
223"returned as strings, the bytes having been first decoded using a\n"
224"platform-dependent encoding or using the specified encoding if given.\n"
225"\n"
Antoine Pitroud5587bc2009-12-19 21:08:31 +0000226"buffering is an optional integer used to set the buffering policy.\n"
227"Pass 0 to switch buffering off (only allowed in binary mode), 1 to select\n"
228"line buffering (only usable in text mode), and an integer > 1 to indicate\n"
229"the size of a fixed-size chunk buffer. When no buffering argument is\n"
230"given, the default buffering policy works as follows:\n"
231"\n"
232"* Binary files are buffered in fixed-size chunks; the size of the buffer\n"
233" is chosen using a heuristic trying to determine the underlying device's\n"
234" \"block size\" and falling back on `io.DEFAULT_BUFFER_SIZE`.\n"
235" On many systems, the buffer will typically be 4096 or 8192 bytes long.\n"
236"\n"
237"* \"Interactive\" text files (files for which isatty() returns True)\n"
238" use line buffering. Other text files use the policy described above\n"
239" for binary files.\n"
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000240"\n"
241"encoding is the name of the encoding used to decode or encode the\n"
242"file. This should only be used in text mode. The default encoding is\n"
243"platform dependent, but any encoding supported by Python can be\n"
244"passed. See the codecs module for the list of supported encodings.\n"
245"\n"
246"errors is an optional string that specifies how encoding errors are to\n"
247"be handled---this argument should not be used in binary mode. Pass\n"
248"'strict' to raise a ValueError exception if there is an encoding error\n"
249"(the default of None has the same effect), or pass 'ignore' to ignore\n"
250"errors. (Note that ignoring encoding errors can lead to data loss.)\n"
251"See the documentation for codecs.register for a list of the permitted\n"
252"encoding error strings.\n"
253"\n"
254"newline controls how universal newlines works (it only applies to text\n"
255"mode). It can be None, '', '\\n', '\\r', and '\\r\\n'. It works as\n"
256"follows:\n"
257"\n"
258"* On input, if newline is None, universal newlines mode is\n"
259" enabled. Lines in the input can end in '\\n', '\\r', or '\\r\\n', and\n"
260" these are translated into '\\n' before being returned to the\n"
261" caller. If it is '', universal newline mode is enabled, but line\n"
262" endings are returned to the caller untranslated. If it has any of\n"
263" the other legal values, input lines are only terminated by the given\n"
264" string, and the line ending is returned to the caller untranslated.\n"
265"\n"
266"* On output, if newline is None, any '\\n' characters written are\n"
267" translated to the system default line separator, os.linesep. If\n"
268" newline is '', no translation takes place. If newline is any of the\n"
269" other legal values, any '\\n' characters written are translated to\n"
270" the given string.\n"
271"\n"
272"If closefd is False, the underlying file descriptor will be kept open\n"
273"when the file is closed. This does not work when a file name is given\n"
274"and must be True in that case.\n"
275"\n"
276"open() returns a file object whose type depends on the mode, and\n"
277"through which the standard file operations such as reading and writing\n"
278"are performed. When open() is used to open a file in a text mode ('w',\n"
279"'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open\n"
280"a file in a binary mode, the returned class varies: in read binary\n"
281"mode, it returns a BufferedReader; in write binary and append binary\n"
282"modes, it returns a BufferedWriter, and in read/write mode, it returns\n"
283"a BufferedRandom.\n"
284"\n"
285"It is also possible to use a string or bytearray as a file for both\n"
286"reading and writing. For strings StringIO can be used like a file\n"
287"opened in a text mode, and for bytes a BytesIO can be used like a file\n"
288"opened in a binary mode.\n"
289 );
290
291static PyObject *
292io_open(PyObject *self, PyObject *args, PyObject *kwds)
293{
294 char *kwlist[] = {"file", "mode", "buffering",
295 "encoding", "errors", "newline",
296 "closefd", NULL};
297 PyObject *file;
298 char *mode = "r";
299 int buffering = -1, closefd = 1;
300 char *encoding = NULL, *errors = NULL, *newline = NULL;
301 unsigned i;
302
303 int reading = 0, writing = 0, appending = 0, updating = 0;
304 int text = 0, binary = 0, universal = 0;
305
306 char rawmode[5], *m;
307 int line_buffering, isatty;
308
309 PyObject *raw, *modeobj = NULL, *buffer = NULL, *wrapper = NULL;
310
311 if (!PyArg_ParseTupleAndKeywords(args, kwds, "O|sizzzi:open", kwlist,
312 &file, &mode, &buffering,
313 &encoding, &errors, &newline,
314 &closefd)) {
315 return NULL;
316 }
317
318 if (!PyUnicode_Check(file) &&
319 !PyBytes_Check(file) &&
320 !PyNumber_Check(file)) {
321 PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
322 return NULL;
323 }
324
325 /* Decode mode */
326 for (i = 0; i < strlen(mode); i++) {
327 char c = mode[i];
328
329 switch (c) {
330 case 'r':
331 reading = 1;
332 break;
333 case 'w':
334 writing = 1;
335 break;
336 case 'a':
337 appending = 1;
338 break;
339 case '+':
340 updating = 1;
341 break;
342 case 't':
343 text = 1;
344 break;
345 case 'b':
346 binary = 1;
347 break;
348 case 'U':
349 universal = 1;
350 reading = 1;
351 break;
352 default:
353 goto invalid_mode;
354 }
355
356 /* c must not be duplicated */
357 if (strchr(mode+i+1, c)) {
358 invalid_mode:
359 PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
360 return NULL;
361 }
362
363 }
364
365 m = rawmode;
366 if (reading) *(m++) = 'r';
367 if (writing) *(m++) = 'w';
368 if (appending) *(m++) = 'a';
369 if (updating) *(m++) = '+';
370 *m = '\0';
371
372 /* Parameters validation */
373 if (universal) {
374 if (writing || appending) {
375 PyErr_SetString(PyExc_ValueError,
376 "can't use U and writing mode at once");
377 return NULL;
378 }
379 reading = 1;
380 }
381
382 if (text && binary) {
383 PyErr_SetString(PyExc_ValueError,
384 "can't have text and binary mode at once");
385 return NULL;
386 }
387
388 if (reading + writing + appending > 1) {
389 PyErr_SetString(PyExc_ValueError,
390 "must have exactly one of read/write/append mode");
391 return NULL;
392 }
393
394 if (binary && encoding != NULL) {
395 PyErr_SetString(PyExc_ValueError,
396 "binary mode doesn't take an encoding argument");
397 return NULL;
398 }
399
400 if (binary && errors != NULL) {
401 PyErr_SetString(PyExc_ValueError,
402 "binary mode doesn't take an errors argument");
403 return NULL;
404 }
405
406 if (binary && newline != NULL) {
407 PyErr_SetString(PyExc_ValueError,
408 "binary mode doesn't take a newline argument");
409 return NULL;
410 }
411
412 /* Create the Raw file stream */
413 raw = PyObject_CallFunction((PyObject *)&PyFileIO_Type,
414 "Osi", file, rawmode, closefd);
415 if (raw == NULL)
416 return NULL;
417
418 modeobj = PyUnicode_FromString(mode);
419 if (modeobj == NULL)
420 goto error;
421
422 /* buffering */
423 {
424 PyObject *res = PyObject_CallMethod(raw, "isatty", NULL);
425 if (res == NULL)
426 goto error;
427 isatty = PyLong_AsLong(res);
428 Py_DECREF(res);
429 if (isatty == -1 && PyErr_Occurred())
430 goto error;
431 }
432
433 if (buffering == 1 || (buffering < 0 && isatty)) {
434 buffering = -1;
435 line_buffering = 1;
436 }
437 else
438 line_buffering = 0;
439
440 if (buffering < 0) {
441 buffering = DEFAULT_BUFFER_SIZE;
442#ifdef HAVE_STRUCT_STAT_ST_BLKSIZE
443 {
444 struct stat st;
445 long fileno;
446 PyObject *res = PyObject_CallMethod(raw, "fileno", NULL);
447 if (res == NULL)
448 goto error;
449
450 fileno = PyLong_AsLong(res);
451 Py_DECREF(res);
452 if (fileno == -1 && PyErr_Occurred())
453 goto error;
454
Antoine Pitrouea5d17d2010-10-27 19:45:43 +0000455 if (fstat(fileno, &st) >= 0 && st.st_blksize > 1)
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000456 buffering = st.st_blksize;
457 }
458#endif
459 }
460 if (buffering < 0) {
461 PyErr_SetString(PyExc_ValueError,
462 "invalid buffering size");
463 goto error;
464 }
465
466 /* if not buffering, returns the raw file object */
467 if (buffering == 0) {
468 if (!binary) {
469 PyErr_SetString(PyExc_ValueError,
470 "can't have unbuffered text I/O");
471 goto error;
472 }
473
474 Py_DECREF(modeobj);
475 return raw;
476 }
477
478 /* wraps into a buffered file */
479 {
480 PyObject *Buffered_class;
481
482 if (updating)
483 Buffered_class = (PyObject *)&PyBufferedRandom_Type;
484 else if (writing || appending)
485 Buffered_class = (PyObject *)&PyBufferedWriter_Type;
486 else if (reading)
487 Buffered_class = (PyObject *)&PyBufferedReader_Type;
488 else {
489 PyErr_Format(PyExc_ValueError,
490 "unknown mode: '%s'", mode);
491 goto error;
492 }
493
494 buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
495 }
496 Py_CLEAR(raw);
497 if (buffer == NULL)
498 goto error;
499
500
501 /* if binary, returns the buffered file */
502 if (binary) {
503 Py_DECREF(modeobj);
504 return buffer;
505 }
506
507 /* wraps into a TextIOWrapper */
508 wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
509 "Osssi",
510 buffer,
511 encoding, errors, newline,
512 line_buffering);
513 Py_CLEAR(buffer);
514 if (wrapper == NULL)
515 goto error;
516
517 if (PyObject_SetAttrString(wrapper, "mode", modeobj) < 0)
518 goto error;
519 Py_DECREF(modeobj);
520 return wrapper;
521
522 error:
523 Py_XDECREF(raw);
524 Py_XDECREF(modeobj);
525 Py_XDECREF(buffer);
526 Py_XDECREF(wrapper);
527 return NULL;
528}
529
530/*
531 * Private helpers for the io module.
532 */
533
534Py_off_t
535PyNumber_AsOff_t(PyObject *item, PyObject *err)
536{
537 Py_off_t result;
538 PyObject *runerr;
539 PyObject *value = PyNumber_Index(item);
540 if (value == NULL)
541 return -1;
542
543 /* We're done if PyLong_AsSsize_t() returns without error. */
544 result = PyLong_AsOff_t(value);
545 if (result != -1 || !(runerr = PyErr_Occurred()))
546 goto finish;
547
548 /* Error handling code -- only manage OverflowError differently */
549 if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
550 goto finish;
551
552 PyErr_Clear();
553 /* If no error-handling desired then the default clipping
554 is sufficient.
555 */
556 if (!err) {
557 assert(PyLong_Check(value));
558 /* Whether or not it is less than or equal to
559 zero is determined by the sign of ob_size
560 */
561 if (_PyLong_Sign(value) < 0)
562 result = PY_OFF_T_MIN;
563 else
564 result = PY_OFF_T_MAX;
565 }
566 else {
567 /* Otherwise replace the error with caller's error object. */
568 PyErr_Format(err,
569 "cannot fit '%.200s' into an offset-sized integer",
570 item->ob_type->tp_name);
571 }
572
573 finish:
574 Py_DECREF(value);
575 return result;
576}
577
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000578
579/* Basically the "n" format code with the ability to turn None into -1. */
580int
581_PyIO_ConvertSsize_t(PyObject *obj, void *result) {
582 Py_ssize_t limit;
583 if (obj == Py_None) {
584 limit = -1;
585 }
586 else if (PyNumber_Check(obj)) {
587 limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError);
588 if (limit == -1 && PyErr_Occurred())
589 return 0;
590 }
591 else {
592 PyErr_Format(PyExc_TypeError,
593 "integer argument expected, got '%.200s'",
594 Py_TYPE(obj)->tp_name);
595 return 0;
596 }
597 *((Py_ssize_t *)result) = limit;
598 return 1;
599}
600
601
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000602static int
603iomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
604 _PyIO_State *state = IO_MOD_STATE(mod);
605 if (!state->initialized)
606 return 0;
607 Py_VISIT(state->os_module);
608 if (state->locale_module != NULL) {
609 Py_VISIT(state->locale_module);
610 }
611 Py_VISIT(state->unsupported_operation);
612 return 0;
613}
614
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000615
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000616static int
617iomodule_clear(PyObject *mod) {
618 _PyIO_State *state = IO_MOD_STATE(mod);
619 if (!state->initialized)
620 return 0;
621 Py_CLEAR(state->os_module);
622 if (state->locale_module != NULL)
623 Py_CLEAR(state->locale_module);
624 Py_CLEAR(state->unsupported_operation);
625 return 0;
626}
627
628static void
629iomodule_free(PyObject *mod) {
630 iomodule_clear(mod);
631}
632
Benjamin Petersonbf5ff762009-12-13 19:25:34 +0000633
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000634/*
635 * Module definition
636 */
637
638static PyMethodDef module_methods[] = {
639 {"open", (PyCFunction)io_open, METH_VARARGS|METH_KEYWORDS, open_doc},
640 {NULL, NULL}
641};
642
643struct PyModuleDef _PyIO_Module = {
644 PyModuleDef_HEAD_INIT,
645 "io",
646 module_doc,
647 sizeof(_PyIO_State),
648 module_methods,
649 NULL,
650 iomodule_traverse,
651 iomodule_clear,
652 (freefunc)iomodule_free,
653};
654
655PyMODINIT_FUNC
656PyInit__io(void)
657{
658 PyObject *m = PyModule_Create(&_PyIO_Module);
659 _PyIO_State *state = NULL;
660 if (m == NULL)
661 return NULL;
662 state = IO_MOD_STATE(m);
663 state->initialized = 0;
664
665 /* put os in the module state */
666 state->os_module = PyImport_ImportModule("os");
667 if (state->os_module == NULL)
668 goto fail;
669
670#define ADD_TYPE(type, name) \
671 if (PyType_Ready(type) < 0) \
672 goto fail; \
673 Py_INCREF(type); \
674 if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
675 Py_DECREF(type); \
676 goto fail; \
677 }
678
679 /* DEFAULT_BUFFER_SIZE */
680 if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
681 goto fail;
682
683 /* UnsupportedOperation inherits from ValueError and IOError */
684 state->unsupported_operation = PyObject_CallFunction(
685 (PyObject *)&PyType_Type, "s(OO){}",
686 "UnsupportedOperation", PyExc_ValueError, PyExc_IOError);
687 if (state->unsupported_operation == NULL)
688 goto fail;
689 Py_INCREF(state->unsupported_operation);
690 if (PyModule_AddObject(m, "UnsupportedOperation",
691 state->unsupported_operation) < 0)
692 goto fail;
693
694 /* BlockingIOError */
695 _PyExc_BlockingIOError.tp_base = (PyTypeObject *) PyExc_IOError;
696 ADD_TYPE(&_PyExc_BlockingIOError, "BlockingIOError");
697
698 /* Concrete base types of the IO ABCs.
699 (the ABCs themselves are declared through inheritance in io.py)
700 */
701 ADD_TYPE(&PyIOBase_Type, "_IOBase");
702 ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
703 ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
704 ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
705
706 /* Implementation of concrete IO objects. */
707 /* FileIO */
708 PyFileIO_Type.tp_base = &PyRawIOBase_Type;
709 ADD_TYPE(&PyFileIO_Type, "FileIO");
710
711 /* BytesIO */
712 PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
713 ADD_TYPE(&PyBytesIO_Type, "BytesIO");
Antoine Pitrou972ee132010-09-06 18:48:21 +0000714 if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
715 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000716
717 /* StringIO */
718 PyStringIO_Type.tp_base = &PyTextIOBase_Type;
719 ADD_TYPE(&PyStringIO_Type, "StringIO");
720
721 /* BufferedReader */
722 PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
723 ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
724
725 /* BufferedWriter */
726 PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
727 ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
728
729 /* BufferedRWPair */
730 PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
731 ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
732
733 /* BufferedRandom */
734 PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
735 ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
736
737 /* TextIOWrapper */
738 PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
739 ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
740
741 /* IncrementalNewlineDecoder */
742 ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
743
744 /* Interned strings */
745 if (!(_PyIO_str_close = PyUnicode_InternFromString("close")))
746 goto fail;
747 if (!(_PyIO_str_closed = PyUnicode_InternFromString("closed")))
748 goto fail;
749 if (!(_PyIO_str_decode = PyUnicode_InternFromString("decode")))
750 goto fail;
751 if (!(_PyIO_str_encode = PyUnicode_InternFromString("encode")))
752 goto fail;
753 if (!(_PyIO_str_fileno = PyUnicode_InternFromString("fileno")))
754 goto fail;
755 if (!(_PyIO_str_flush = PyUnicode_InternFromString("flush")))
756 goto fail;
757 if (!(_PyIO_str_getstate = PyUnicode_InternFromString("getstate")))
758 goto fail;
759 if (!(_PyIO_str_isatty = PyUnicode_InternFromString("isatty")))
760 goto fail;
761 if (!(_PyIO_str_newlines = PyUnicode_InternFromString("newlines")))
762 goto fail;
763 if (!(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
764 goto fail;
765 if (!(_PyIO_str_read = PyUnicode_InternFromString("read")))
766 goto fail;
767 if (!(_PyIO_str_read1 = PyUnicode_InternFromString("read1")))
768 goto fail;
769 if (!(_PyIO_str_readable = PyUnicode_InternFromString("readable")))
770 goto fail;
Victor Stinnerb57f1082011-05-26 00:19:38 +0200771 if (!(_PyIO_str_readall = PyUnicode_InternFromString("readall")))
772 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000773 if (!(_PyIO_str_readinto = PyUnicode_InternFromString("readinto")))
774 goto fail;
775 if (!(_PyIO_str_readline = PyUnicode_InternFromString("readline")))
776 goto fail;
777 if (!(_PyIO_str_reset = PyUnicode_InternFromString("reset")))
778 goto fail;
779 if (!(_PyIO_str_seek = PyUnicode_InternFromString("seek")))
780 goto fail;
781 if (!(_PyIO_str_seekable = PyUnicode_InternFromString("seekable")))
782 goto fail;
Antoine Pitroue4501852009-05-14 18:55:55 +0000783 if (!(_PyIO_str_setstate = PyUnicode_InternFromString("setstate")))
784 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000785 if (!(_PyIO_str_tell = PyUnicode_InternFromString("tell")))
786 goto fail;
787 if (!(_PyIO_str_truncate = PyUnicode_InternFromString("truncate")))
788 goto fail;
789 if (!(_PyIO_str_write = PyUnicode_InternFromString("write")))
790 goto fail;
791 if (!(_PyIO_str_writable = PyUnicode_InternFromString("writable")))
792 goto fail;
793
794 if (!(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
795 goto fail;
796 if (!(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
797 goto fail;
Antoine Pitroue4501852009-05-14 18:55:55 +0000798 if (!(_PyIO_zero = PyLong_FromLong(0L)))
799 goto fail;
Benjamin Peterson4fa88fa2009-03-04 00:14:51 +0000800
801 state->initialized = 1;
802
803 return m;
804
805 fail:
806 Py_XDECREF(state->os_module);
807 Py_XDECREF(state->unsupported_operation);
808 Py_DECREF(m);
809 return NULL;
810}