ยปCore Development>Code coverage>Modules/_io/_iomodule.c

Python code coverage for Modules/_io/_iomodule.c

#countcontent
1n/a/*
2n/a An implementation of the new I/O lib as defined by PEP 3116 - "New I/O"
3n/a
4n/a Classes defined here: UnsupportedOperation, BlockingIOError.
5n/a Functions defined here: open().
6n/a
7n/a Mostly written by Amaury Forgeot d'Arc
8n/a*/
9n/a
10n/a#define PY_SSIZE_T_CLEAN
11n/a#include "Python.h"
12n/a#include "structmember.h"
13n/a#include "_iomodule.h"
14n/a
15n/a#ifdef HAVE_SYS_TYPES_H
16n/a#include <sys/types.h>
17n/a#endif /* HAVE_SYS_TYPES_H */
18n/a
19n/a#ifdef HAVE_SYS_STAT_H
20n/a#include <sys/stat.h>
21n/a#endif /* HAVE_SYS_STAT_H */
22n/a
23n/a#ifdef MS_WINDOWS
24n/a#include <consoleapi.h>
25n/a#endif
26n/a
27n/a/* Various interned strings */
28n/a
29n/aPyObject *_PyIO_str_close;
30n/aPyObject *_PyIO_str_closed;
31n/aPyObject *_PyIO_str_decode;
32n/aPyObject *_PyIO_str_encode;
33n/aPyObject *_PyIO_str_fileno;
34n/aPyObject *_PyIO_str_flush;
35n/aPyObject *_PyIO_str_getstate;
36n/aPyObject *_PyIO_str_isatty;
37n/aPyObject *_PyIO_str_newlines;
38n/aPyObject *_PyIO_str_nl;
39n/aPyObject *_PyIO_str_read;
40n/aPyObject *_PyIO_str_read1;
41n/aPyObject *_PyIO_str_readable;
42n/aPyObject *_PyIO_str_readall;
43n/aPyObject *_PyIO_str_readinto;
44n/aPyObject *_PyIO_str_readline;
45n/aPyObject *_PyIO_str_reset;
46n/aPyObject *_PyIO_str_seek;
47n/aPyObject *_PyIO_str_seekable;
48n/aPyObject *_PyIO_str_setstate;
49n/aPyObject *_PyIO_str_tell;
50n/aPyObject *_PyIO_str_truncate;
51n/aPyObject *_PyIO_str_writable;
52n/aPyObject *_PyIO_str_write;
53n/a
54n/aPyObject *_PyIO_empty_str;
55n/aPyObject *_PyIO_empty_bytes;
56n/aPyObject *_PyIO_zero;
57n/a
58n/aPyDoc_STRVAR(module_doc,
59n/a"The io module provides the Python interfaces to stream handling. The\n"
60n/a"builtin open function is defined in this module.\n"
61n/a"\n"
62n/a"At the top of the I/O hierarchy is the abstract base class IOBase. It\n"
63n/a"defines the basic interface to a stream. Note, however, that there is no\n"
64n/a"separation between reading and writing to streams; implementations are\n"
65n/a"allowed to raise an IOError if they do not support a given operation.\n"
66n/a"\n"
67n/a"Extending IOBase is RawIOBase which deals simply with the reading and\n"
68n/a"writing of raw bytes to a stream. FileIO subclasses RawIOBase to provide\n"
69n/a"an interface to OS files.\n"
70n/a"\n"
71n/a"BufferedIOBase deals with buffering on a raw byte stream (RawIOBase). Its\n"
72n/a"subclasses, BufferedWriter, BufferedReader, and BufferedRWPair buffer\n"
73n/a"streams that are readable, writable, and both respectively.\n"
74n/a"BufferedRandom provides a buffered interface to random access\n"
75n/a"streams. BytesIO is a simple stream of in-memory bytes.\n"
76n/a"\n"
77n/a"Another IOBase subclass, TextIOBase, deals with the encoding and decoding\n"
78n/a"of streams into text. TextIOWrapper, which extends it, is a buffered text\n"
79n/a"interface to a buffered raw stream (`BufferedIOBase`). Finally, StringIO\n"
80n/a"is an in-memory stream for text.\n"
81n/a"\n"
82n/a"Argument names are not part of the specification, and only the arguments\n"
83n/a"of open() are intended to be used as keyword arguments.\n"
84n/a"\n"
85n/a"data:\n"
86n/a"\n"
87n/a"DEFAULT_BUFFER_SIZE\n"
88n/a"\n"
89n/a" An int containing the default buffer size used by the module's buffered\n"
90n/a" I/O classes. open() uses the file's blksize (as obtained by os.stat) if\n"
91n/a" possible.\n"
92n/a );
93n/a
94n/a
95n/a/*
96n/a * The main open() function
97n/a */
98n/a/*[clinic input]
99n/amodule _io
100n/a
101n/a_io.open
102n/a file: object
103n/a mode: str = "r"
104n/a buffering: int = -1
105n/a encoding: str(accept={str, NoneType}) = NULL
106n/a errors: str(accept={str, NoneType}) = NULL
107n/a newline: str(accept={str, NoneType}) = NULL
108n/a closefd: int(c_default="1") = True
109n/a opener: object = None
110n/a
111n/aOpen file and return a stream. Raise IOError upon failure.
112n/a
113n/afile is either a text or byte string giving the name (and the path
114n/aif the file isn't in the current working directory) of the file to
115n/abe opened or an integer file descriptor of the file to be
116n/awrapped. (If a file descriptor is given, it is closed when the
117n/areturned I/O object is closed, unless closefd is set to False.)
118n/a
119n/amode is an optional string that specifies the mode in which the file
120n/ais opened. It defaults to 'r' which means open for reading in text
121n/amode. Other common values are 'w' for writing (truncating the file if
122n/ait already exists), 'x' for creating and writing to a new file, and
123n/a'a' for appending (which on some Unix systems, means that all writes
124n/aappend to the end of the file regardless of the current seek position).
125n/aIn text mode, if encoding is not specified the encoding used is platform
126n/adependent: locale.getpreferredencoding(False) is called to get the
127n/acurrent locale encoding. (For reading and writing raw bytes use binary
128n/amode and leave encoding unspecified.) The available modes are:
129n/a
130n/a========= ===============================================================
131n/aCharacter Meaning
132n/a--------- ---------------------------------------------------------------
133n/a'r' open for reading (default)
134n/a'w' open for writing, truncating the file first
135n/a'x' create a new file and open it for writing
136n/a'a' open for writing, appending to the end of the file if it exists
137n/a'b' binary mode
138n/a't' text mode (default)
139n/a'+' open a disk file for updating (reading and writing)
140n/a'U' universal newline mode (deprecated)
141n/a========= ===============================================================
142n/a
143n/aThe default mode is 'rt' (open for reading text). For binary random
144n/aaccess, the mode 'w+b' opens and truncates the file to 0 bytes, while
145n/a'r+b' opens the file without truncation. The 'x' mode implies 'w' and
146n/araises an `FileExistsError` if the file already exists.
147n/a
148n/aPython distinguishes between files opened in binary and text modes,
149n/aeven when the underlying operating system doesn't. Files opened in
150n/abinary mode (appending 'b' to the mode argument) return contents as
151n/abytes objects without any decoding. In text mode (the default, or when
152n/a't' is appended to the mode argument), the contents of the file are
153n/areturned as strings, the bytes having been first decoded using a
154n/aplatform-dependent encoding or using the specified encoding if given.
155n/a
156n/a'U' mode is deprecated and will raise an exception in future versions
157n/aof Python. It has no effect in Python 3. Use newline to control
158n/auniversal newlines mode.
159n/a
160n/abuffering is an optional integer used to set the buffering policy.
161n/aPass 0 to switch buffering off (only allowed in binary mode), 1 to select
162n/aline buffering (only usable in text mode), and an integer > 1 to indicate
163n/athe size of a fixed-size chunk buffer. When no buffering argument is
164n/agiven, the default buffering policy works as follows:
165n/a
166n/a* Binary files are buffered in fixed-size chunks; the size of the buffer
167n/a is chosen using a heuristic trying to determine the underlying device's
168n/a "block size" and falling back on `io.DEFAULT_BUFFER_SIZE`.
169n/a On many systems, the buffer will typically be 4096 or 8192 bytes long.
170n/a
171n/a* "Interactive" text files (files for which isatty() returns True)
172n/a use line buffering. Other text files use the policy described above
173n/a for binary files.
174n/a
175n/aencoding is the name of the encoding used to decode or encode the
176n/afile. This should only be used in text mode. The default encoding is
177n/aplatform dependent, but any encoding supported by Python can be
178n/apassed. See the codecs module for the list of supported encodings.
179n/a
180n/aerrors is an optional string that specifies how encoding errors are to
181n/abe handled---this argument should not be used in binary mode. Pass
182n/a'strict' to raise a ValueError exception if there is an encoding error
183n/a(the default of None has the same effect), or pass 'ignore' to ignore
184n/aerrors. (Note that ignoring encoding errors can lead to data loss.)
185n/aSee the documentation for codecs.register or run 'help(codecs.Codec)'
186n/afor a list of the permitted encoding error strings.
187n/a
188n/anewline controls how universal newlines works (it only applies to text
189n/amode). It can be None, '', '\n', '\r', and '\r\n'. It works as
190n/afollows:
191n/a
192n/a* On input, if newline is None, universal newlines mode is
193n/a enabled. Lines in the input can end in '\n', '\r', or '\r\n', and
194n/a these are translated into '\n' before being returned to the
195n/a caller. If it is '', universal newline mode is enabled, but line
196n/a endings are returned to the caller untranslated. If it has any of
197n/a the other legal values, input lines are only terminated by the given
198n/a string, and the line ending is returned to the caller untranslated.
199n/a
200n/a* On output, if newline is None, any '\n' characters written are
201n/a translated to the system default line separator, os.linesep. If
202n/a newline is '' or '\n', no translation takes place. If newline is any
203n/a of the other legal values, any '\n' characters written are translated
204n/a to the given string.
205n/a
206n/aIf closefd is False, the underlying file descriptor will be kept open
207n/awhen the file is closed. This does not work when a file name is given
208n/aand must be True in that case.
209n/a
210n/aA custom opener can be used by passing a callable as *opener*. The
211n/aunderlying file descriptor for the file object is then obtained by
212n/acalling *opener* with (*file*, *flags*). *opener* must return an open
213n/afile descriptor (passing os.open as *opener* results in functionality
214n/asimilar to passing None).
215n/a
216n/aopen() returns a file object whose type depends on the mode, and
217n/athrough which the standard file operations such as reading and writing
218n/aare performed. When open() is used to open a file in a text mode ('w',
219n/a'r', 'wt', 'rt', etc.), it returns a TextIOWrapper. When used to open
220n/aa file in a binary mode, the returned class varies: in read binary
221n/amode, it returns a BufferedReader; in write binary and append binary
222n/amodes, it returns a BufferedWriter, and in read/write mode, it returns
223n/aa BufferedRandom.
224n/a
225n/aIt is also possible to use a string or bytearray as a file for both
226n/areading and writing. For strings StringIO can be used like a file
227n/aopened in a text mode, and for bytes a BytesIO can be used like a file
228n/aopened in a binary mode.
229n/a[clinic start generated code]*/
230n/a
231n/astatic PyObject *
232n/a_io_open_impl(PyObject *module, PyObject *file, const char *mode,
233n/a int buffering, const char *encoding, const char *errors,
234n/a const char *newline, int closefd, PyObject *opener)
235n/a/*[clinic end generated code: output=aefafc4ce2b46dc0 input=f4e1ca75223987bc]*/
236n/a{
237n/a unsigned i;
238n/a
239n/a int creating = 0, reading = 0, writing = 0, appending = 0, updating = 0;
240n/a int text = 0, binary = 0, universal = 0;
241n/a
242n/a char rawmode[6], *m;
243n/a int line_buffering, is_number;
244n/a long isatty;
245n/a
246n/a PyObject *raw, *modeobj = NULL, *buffer, *wrapper, *result = NULL, *path_or_fd = NULL;
247n/a
248n/a _Py_IDENTIFIER(_blksize);
249n/a _Py_IDENTIFIER(isatty);
250n/a _Py_IDENTIFIER(mode);
251n/a _Py_IDENTIFIER(close);
252n/a
253n/a is_number = PyNumber_Check(file);
254n/a
255n/a if (is_number) {
256n/a path_or_fd = file;
257n/a Py_INCREF(path_or_fd);
258n/a } else {
259n/a path_or_fd = PyOS_FSPath(file);
260n/a if (path_or_fd == NULL) {
261n/a return NULL;
262n/a }
263n/a }
264n/a
265n/a if (!is_number &&
266n/a !PyUnicode_Check(path_or_fd) &&
267n/a !PyBytes_Check(path_or_fd)) {
268n/a PyErr_Format(PyExc_TypeError, "invalid file: %R", file);
269n/a goto error;
270n/a }
271n/a
272n/a /* Decode mode */
273n/a for (i = 0; i < strlen(mode); i++) {
274n/a char c = mode[i];
275n/a
276n/a switch (c) {
277n/a case 'x':
278n/a creating = 1;
279n/a break;
280n/a case 'r':
281n/a reading = 1;
282n/a break;
283n/a case 'w':
284n/a writing = 1;
285n/a break;
286n/a case 'a':
287n/a appending = 1;
288n/a break;
289n/a case '+':
290n/a updating = 1;
291n/a break;
292n/a case 't':
293n/a text = 1;
294n/a break;
295n/a case 'b':
296n/a binary = 1;
297n/a break;
298n/a case 'U':
299n/a universal = 1;
300n/a reading = 1;
301n/a break;
302n/a default:
303n/a goto invalid_mode;
304n/a }
305n/a
306n/a /* c must not be duplicated */
307n/a if (strchr(mode+i+1, c)) {
308n/a invalid_mode:
309n/a PyErr_Format(PyExc_ValueError, "invalid mode: '%s'", mode);
310n/a goto error;
311n/a }
312n/a
313n/a }
314n/a
315n/a m = rawmode;
316n/a if (creating) *(m++) = 'x';
317n/a if (reading) *(m++) = 'r';
318n/a if (writing) *(m++) = 'w';
319n/a if (appending) *(m++) = 'a';
320n/a if (updating) *(m++) = '+';
321n/a *m = '\0';
322n/a
323n/a /* Parameters validation */
324n/a if (universal) {
325n/a if (creating || writing || appending || updating) {
326n/a PyErr_SetString(PyExc_ValueError,
327n/a "mode U cannot be combined with x', 'w', 'a', or '+'");
328n/a goto error;
329n/a }
330n/a if (PyErr_WarnEx(PyExc_DeprecationWarning,
331n/a "'U' mode is deprecated", 1) < 0)
332n/a goto error;
333n/a reading = 1;
334n/a }
335n/a
336n/a if (text && binary) {
337n/a PyErr_SetString(PyExc_ValueError,
338n/a "can't have text and binary mode at once");
339n/a goto error;
340n/a }
341n/a
342n/a if (creating + reading + writing + appending > 1) {
343n/a PyErr_SetString(PyExc_ValueError,
344n/a "must have exactly one of create/read/write/append mode");
345n/a goto error;
346n/a }
347n/a
348n/a if (binary && encoding != NULL) {
349n/a PyErr_SetString(PyExc_ValueError,
350n/a "binary mode doesn't take an encoding argument");
351n/a goto error;
352n/a }
353n/a
354n/a if (binary && errors != NULL) {
355n/a PyErr_SetString(PyExc_ValueError,
356n/a "binary mode doesn't take an errors argument");
357n/a goto error;
358n/a }
359n/a
360n/a if (binary && newline != NULL) {
361n/a PyErr_SetString(PyExc_ValueError,
362n/a "binary mode doesn't take a newline argument");
363n/a goto error;
364n/a }
365n/a
366n/a /* Create the Raw file stream */
367n/a {
368n/a PyObject *RawIO_class = (PyObject *)&PyFileIO_Type;
369n/a#ifdef MS_WINDOWS
370n/a if (!Py_LegacyWindowsStdioFlag && _PyIO_get_console_type(path_or_fd) != '\0') {
371n/a RawIO_class = (PyObject *)&PyWindowsConsoleIO_Type;
372n/a encoding = "utf-8";
373n/a }
374n/a#endif
375n/a raw = PyObject_CallFunction(RawIO_class,
376n/a "OsiO", path_or_fd, rawmode, closefd, opener);
377n/a }
378n/a
379n/a if (raw == NULL)
380n/a goto error;
381n/a result = raw;
382n/a
383n/a Py_DECREF(path_or_fd);
384n/a path_or_fd = NULL;
385n/a
386n/a modeobj = PyUnicode_FromString(mode);
387n/a if (modeobj == NULL)
388n/a goto error;
389n/a
390n/a /* buffering */
391n/a {
392n/a PyObject *res = _PyObject_CallMethodId(raw, &PyId_isatty, NULL);
393n/a if (res == NULL)
394n/a goto error;
395n/a isatty = PyLong_AsLong(res);
396n/a Py_DECREF(res);
397n/a if (isatty == -1 && PyErr_Occurred())
398n/a goto error;
399n/a }
400n/a
401n/a if (buffering == 1 || (buffering < 0 && isatty)) {
402n/a buffering = -1;
403n/a line_buffering = 1;
404n/a }
405n/a else
406n/a line_buffering = 0;
407n/a
408n/a if (buffering < 0) {
409n/a PyObject *blksize_obj;
410n/a blksize_obj = _PyObject_GetAttrId(raw, &PyId__blksize);
411n/a if (blksize_obj == NULL)
412n/a goto error;
413n/a buffering = PyLong_AsLong(blksize_obj);
414n/a Py_DECREF(blksize_obj);
415n/a if (buffering == -1 && PyErr_Occurred())
416n/a goto error;
417n/a }
418n/a if (buffering < 0) {
419n/a PyErr_SetString(PyExc_ValueError,
420n/a "invalid buffering size");
421n/a goto error;
422n/a }
423n/a
424n/a /* if not buffering, returns the raw file object */
425n/a if (buffering == 0) {
426n/a if (!binary) {
427n/a PyErr_SetString(PyExc_ValueError,
428n/a "can't have unbuffered text I/O");
429n/a goto error;
430n/a }
431n/a
432n/a Py_DECREF(modeobj);
433n/a return result;
434n/a }
435n/a
436n/a /* wraps into a buffered file */
437n/a {
438n/a PyObject *Buffered_class;
439n/a
440n/a if (updating)
441n/a Buffered_class = (PyObject *)&PyBufferedRandom_Type;
442n/a else if (creating || writing || appending)
443n/a Buffered_class = (PyObject *)&PyBufferedWriter_Type;
444n/a else if (reading)
445n/a Buffered_class = (PyObject *)&PyBufferedReader_Type;
446n/a else {
447n/a PyErr_Format(PyExc_ValueError,
448n/a "unknown mode: '%s'", mode);
449n/a goto error;
450n/a }
451n/a
452n/a buffer = PyObject_CallFunction(Buffered_class, "Oi", raw, buffering);
453n/a }
454n/a if (buffer == NULL)
455n/a goto error;
456n/a result = buffer;
457n/a Py_DECREF(raw);
458n/a
459n/a
460n/a /* if binary, returns the buffered file */
461n/a if (binary) {
462n/a Py_DECREF(modeobj);
463n/a return result;
464n/a }
465n/a
466n/a /* wraps into a TextIOWrapper */
467n/a wrapper = PyObject_CallFunction((PyObject *)&PyTextIOWrapper_Type,
468n/a "Osssi",
469n/a buffer,
470n/a encoding, errors, newline,
471n/a line_buffering);
472n/a if (wrapper == NULL)
473n/a goto error;
474n/a result = wrapper;
475n/a Py_DECREF(buffer);
476n/a
477n/a if (_PyObject_SetAttrId(wrapper, &PyId_mode, modeobj) < 0)
478n/a goto error;
479n/a Py_DECREF(modeobj);
480n/a return result;
481n/a
482n/a error:
483n/a if (result != NULL) {
484n/a PyObject *exc, *val, *tb, *close_result;
485n/a PyErr_Fetch(&exc, &val, &tb);
486n/a close_result = _PyObject_CallMethodId(result, &PyId_close, NULL);
487n/a _PyErr_ChainExceptions(exc, val, tb);
488n/a Py_XDECREF(close_result);
489n/a Py_DECREF(result);
490n/a }
491n/a Py_XDECREF(path_or_fd);
492n/a Py_XDECREF(modeobj);
493n/a return NULL;
494n/a}
495n/a
496n/a/*
497n/a * Private helpers for the io module.
498n/a */
499n/a
500n/aPy_off_t
501n/aPyNumber_AsOff_t(PyObject *item, PyObject *err)
502n/a{
503n/a Py_off_t result;
504n/a PyObject *runerr;
505n/a PyObject *value = PyNumber_Index(item);
506n/a if (value == NULL)
507n/a return -1;
508n/a
509n/a /* We're done if PyLong_AsSsize_t() returns without error. */
510n/a result = PyLong_AsOff_t(value);
511n/a if (result != -1 || !(runerr = PyErr_Occurred()))
512n/a goto finish;
513n/a
514n/a /* Error handling code -- only manage OverflowError differently */
515n/a if (!PyErr_GivenExceptionMatches(runerr, PyExc_OverflowError))
516n/a goto finish;
517n/a
518n/a PyErr_Clear();
519n/a /* If no error-handling desired then the default clipping
520n/a is sufficient.
521n/a */
522n/a if (!err) {
523n/a assert(PyLong_Check(value));
524n/a /* Whether or not it is less than or equal to
525n/a zero is determined by the sign of ob_size
526n/a */
527n/a if (_PyLong_Sign(value) < 0)
528n/a result = PY_OFF_T_MIN;
529n/a else
530n/a result = PY_OFF_T_MAX;
531n/a }
532n/a else {
533n/a /* Otherwise replace the error with caller's error object. */
534n/a PyErr_Format(err,
535n/a "cannot fit '%.200s' into an offset-sized integer",
536n/a item->ob_type->tp_name);
537n/a }
538n/a
539n/a finish:
540n/a Py_DECREF(value);
541n/a return result;
542n/a}
543n/a
544n/a
545n/a/* Basically the "n" format code with the ability to turn None into -1. */
546n/aint
547n/a_PyIO_ConvertSsize_t(PyObject *obj, void *result) {
548n/a Py_ssize_t limit;
549n/a if (obj == Py_None) {
550n/a limit = -1;
551n/a }
552n/a else if (PyNumber_Check(obj)) {
553n/a limit = PyNumber_AsSsize_t(obj, PyExc_OverflowError);
554n/a if (limit == -1 && PyErr_Occurred())
555n/a return 0;
556n/a }
557n/a else {
558n/a PyErr_Format(PyExc_TypeError,
559n/a "integer argument expected, got '%.200s'",
560n/a Py_TYPE(obj)->tp_name);
561n/a return 0;
562n/a }
563n/a *((Py_ssize_t *)result) = limit;
564n/a return 1;
565n/a}
566n/a
567n/a
568n/a_PyIO_State *
569n/a_PyIO_get_module_state(void)
570n/a{
571n/a PyObject *mod = PyState_FindModule(&_PyIO_Module);
572n/a _PyIO_State *state;
573n/a if (mod == NULL || (state = IO_MOD_STATE(mod)) == NULL) {
574n/a PyErr_SetString(PyExc_RuntimeError,
575n/a "could not find io module state "
576n/a "(interpreter shutdown?)");
577n/a return NULL;
578n/a }
579n/a return state;
580n/a}
581n/a
582n/aPyObject *
583n/a_PyIO_get_locale_module(_PyIO_State *state)
584n/a{
585n/a PyObject *mod;
586n/a if (state->locale_module != NULL) {
587n/a assert(PyWeakref_CheckRef(state->locale_module));
588n/a mod = PyWeakref_GET_OBJECT(state->locale_module);
589n/a if (mod != Py_None) {
590n/a Py_INCREF(mod);
591n/a return mod;
592n/a }
593n/a Py_CLEAR(state->locale_module);
594n/a }
595n/a mod = PyImport_ImportModule("_bootlocale");
596n/a if (mod == NULL)
597n/a return NULL;
598n/a state->locale_module = PyWeakref_NewRef(mod, NULL);
599n/a if (state->locale_module == NULL) {
600n/a Py_DECREF(mod);
601n/a return NULL;
602n/a }
603n/a return mod;
604n/a}
605n/a
606n/a
607n/astatic int
608n/aiomodule_traverse(PyObject *mod, visitproc visit, void *arg) {
609n/a _PyIO_State *state = IO_MOD_STATE(mod);
610n/a if (!state->initialized)
611n/a return 0;
612n/a if (state->locale_module != NULL) {
613n/a Py_VISIT(state->locale_module);
614n/a }
615n/a Py_VISIT(state->unsupported_operation);
616n/a return 0;
617n/a}
618n/a
619n/a
620n/astatic int
621n/aiomodule_clear(PyObject *mod) {
622n/a _PyIO_State *state = IO_MOD_STATE(mod);
623n/a if (!state->initialized)
624n/a return 0;
625n/a if (state->locale_module != NULL)
626n/a Py_CLEAR(state->locale_module);
627n/a Py_CLEAR(state->unsupported_operation);
628n/a return 0;
629n/a}
630n/a
631n/astatic void
632n/aiomodule_free(PyObject *mod) {
633n/a iomodule_clear(mod);
634n/a}
635n/a
636n/a
637n/a/*
638n/a * Module definition
639n/a */
640n/a
641n/a#include "clinic/_iomodule.c.h"
642n/a
643n/astatic PyMethodDef module_methods[] = {
644n/a _IO_OPEN_METHODDEF
645n/a {NULL, NULL}
646n/a};
647n/a
648n/astruct PyModuleDef _PyIO_Module = {
649n/a PyModuleDef_HEAD_INIT,
650n/a "io",
651n/a module_doc,
652n/a sizeof(_PyIO_State),
653n/a module_methods,
654n/a NULL,
655n/a iomodule_traverse,
656n/a iomodule_clear,
657n/a (freefunc)iomodule_free,
658n/a};
659n/a
660n/aPyMODINIT_FUNC
661n/aPyInit__io(void)
662n/a{
663n/a PyObject *m = PyModule_Create(&_PyIO_Module);
664n/a _PyIO_State *state = NULL;
665n/a if (m == NULL)
666n/a return NULL;
667n/a state = IO_MOD_STATE(m);
668n/a state->initialized = 0;
669n/a
670n/a#define ADD_TYPE(type, name) \
671n/a if (PyType_Ready(type) < 0) \
672n/a goto fail; \
673n/a Py_INCREF(type); \
674n/a if (PyModule_AddObject(m, name, (PyObject *)type) < 0) { \
675n/a Py_DECREF(type); \
676n/a goto fail; \
677n/a }
678n/a
679n/a /* DEFAULT_BUFFER_SIZE */
680n/a if (PyModule_AddIntMacro(m, DEFAULT_BUFFER_SIZE) < 0)
681n/a goto fail;
682n/a
683n/a /* UnsupportedOperation inherits from ValueError and IOError */
684n/a state->unsupported_operation = PyObject_CallFunction(
685n/a (PyObject *)&PyType_Type, "s(OO){}",
686n/a "UnsupportedOperation", PyExc_OSError, PyExc_ValueError);
687n/a if (state->unsupported_operation == NULL)
688n/a goto fail;
689n/a Py_INCREF(state->unsupported_operation);
690n/a if (PyModule_AddObject(m, "UnsupportedOperation",
691n/a state->unsupported_operation) < 0)
692n/a goto fail;
693n/a
694n/a /* BlockingIOError, for compatibility */
695n/a Py_INCREF(PyExc_BlockingIOError);
696n/a if (PyModule_AddObject(m, "BlockingIOError",
697n/a (PyObject *) PyExc_BlockingIOError) < 0)
698n/a goto fail;
699n/a
700n/a /* Concrete base types of the IO ABCs.
701n/a (the ABCs themselves are declared through inheritance in io.py)
702n/a */
703n/a ADD_TYPE(&PyIOBase_Type, "_IOBase");
704n/a ADD_TYPE(&PyRawIOBase_Type, "_RawIOBase");
705n/a ADD_TYPE(&PyBufferedIOBase_Type, "_BufferedIOBase");
706n/a ADD_TYPE(&PyTextIOBase_Type, "_TextIOBase");
707n/a
708n/a /* Implementation of concrete IO objects. */
709n/a /* FileIO */
710n/a PyFileIO_Type.tp_base = &PyRawIOBase_Type;
711n/a ADD_TYPE(&PyFileIO_Type, "FileIO");
712n/a
713n/a /* BytesIO */
714n/a PyBytesIO_Type.tp_base = &PyBufferedIOBase_Type;
715n/a ADD_TYPE(&PyBytesIO_Type, "BytesIO");
716n/a if (PyType_Ready(&_PyBytesIOBuffer_Type) < 0)
717n/a goto fail;
718n/a
719n/a /* StringIO */
720n/a PyStringIO_Type.tp_base = &PyTextIOBase_Type;
721n/a ADD_TYPE(&PyStringIO_Type, "StringIO");
722n/a
723n/a#ifdef MS_WINDOWS
724n/a /* WindowsConsoleIO */
725n/a PyWindowsConsoleIO_Type.tp_base = &PyRawIOBase_Type;
726n/a ADD_TYPE(&PyWindowsConsoleIO_Type, "_WindowsConsoleIO");
727n/a#endif
728n/a
729n/a /* BufferedReader */
730n/a PyBufferedReader_Type.tp_base = &PyBufferedIOBase_Type;
731n/a ADD_TYPE(&PyBufferedReader_Type, "BufferedReader");
732n/a
733n/a /* BufferedWriter */
734n/a PyBufferedWriter_Type.tp_base = &PyBufferedIOBase_Type;
735n/a ADD_TYPE(&PyBufferedWriter_Type, "BufferedWriter");
736n/a
737n/a /* BufferedRWPair */
738n/a PyBufferedRWPair_Type.tp_base = &PyBufferedIOBase_Type;
739n/a ADD_TYPE(&PyBufferedRWPair_Type, "BufferedRWPair");
740n/a
741n/a /* BufferedRandom */
742n/a PyBufferedRandom_Type.tp_base = &PyBufferedIOBase_Type;
743n/a ADD_TYPE(&PyBufferedRandom_Type, "BufferedRandom");
744n/a
745n/a /* TextIOWrapper */
746n/a PyTextIOWrapper_Type.tp_base = &PyTextIOBase_Type;
747n/a ADD_TYPE(&PyTextIOWrapper_Type, "TextIOWrapper");
748n/a
749n/a /* IncrementalNewlineDecoder */
750n/a ADD_TYPE(&PyIncrementalNewlineDecoder_Type, "IncrementalNewlineDecoder");
751n/a
752n/a /* Interned strings */
753n/a#define ADD_INTERNED(name) \
754n/a if (!_PyIO_str_ ## name && \
755n/a !(_PyIO_str_ ## name = PyUnicode_InternFromString(# name))) \
756n/a goto fail;
757n/a
758n/a ADD_INTERNED(close)
759n/a ADD_INTERNED(closed)
760n/a ADD_INTERNED(decode)
761n/a ADD_INTERNED(encode)
762n/a ADD_INTERNED(fileno)
763n/a ADD_INTERNED(flush)
764n/a ADD_INTERNED(getstate)
765n/a ADD_INTERNED(isatty)
766n/a ADD_INTERNED(newlines)
767n/a ADD_INTERNED(read)
768n/a ADD_INTERNED(read1)
769n/a ADD_INTERNED(readable)
770n/a ADD_INTERNED(readall)
771n/a ADD_INTERNED(readinto)
772n/a ADD_INTERNED(readline)
773n/a ADD_INTERNED(reset)
774n/a ADD_INTERNED(seek)
775n/a ADD_INTERNED(seekable)
776n/a ADD_INTERNED(setstate)
777n/a ADD_INTERNED(tell)
778n/a ADD_INTERNED(truncate)
779n/a ADD_INTERNED(write)
780n/a ADD_INTERNED(writable)
781n/a
782n/a if (!_PyIO_str_nl &&
783n/a !(_PyIO_str_nl = PyUnicode_InternFromString("\n")))
784n/a goto fail;
785n/a
786n/a if (!_PyIO_empty_str &&
787n/a !(_PyIO_empty_str = PyUnicode_FromStringAndSize(NULL, 0)))
788n/a goto fail;
789n/a if (!_PyIO_empty_bytes &&
790n/a !(_PyIO_empty_bytes = PyBytes_FromStringAndSize(NULL, 0)))
791n/a goto fail;
792n/a if (!_PyIO_zero &&
793n/a !(_PyIO_zero = PyLong_FromLong(0L)))
794n/a goto fail;
795n/a
796n/a state->initialized = 1;
797n/a
798n/a return m;
799n/a
800n/a fail:
801n/a Py_XDECREF(state->unsupported_operation);
802n/a Py_DECREF(m);
803n/a return NULL;
804n/a}