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