iobase.c 27.4 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
/*
    An implementation of the I/O abstract base classes hierarchy
    as defined by PEP 3116 - "New I/O"
    
    Classes defined here: IOBase, RawIOBase.
    
    Written by Amaury Forgeot d'Arc and Antoine Pitrou
*/


#define PY_SSIZE_T_CLEAN
#include "Python.h"
#include "structmember.h"
#include "_iomodule.h"

/*
 * IOBase class, an abstract class
 */

typedef struct {
    PyObject_HEAD
    
    PyObject *dict;
    PyObject *weakreflist;
25
} iobase;
26

27
PyDoc_STRVAR(iobase_doc,
28 29 30 31 32 33 34 35 36 37
    "The abstract base class for all I/O classes, acting on streams of\n"
    "bytes. There is no public constructor.\n"
    "\n"
    "This class provides dummy implementations for many methods that\n"
    "derived classes can override selectively; the default implementations\n"
    "represent a file that cannot be read, written or seeked.\n"
    "\n"
    "Even though IOBase does not declare read, readinto, or write because\n"
    "their signatures will vary, implementations and clients should\n"
    "consider those methods part of the interface. Also, implementations\n"
38 39
    "may raise UnsupportedOperation when operations they do not support are\n"
    "called.\n"
40 41 42 43 44 45 46 47 48 49 50 51 52
    "\n"
    "The basic type used for binary data read from or written to a file is\n"
    "bytes. bytearrays are accepted too, and in some cases (such as\n"
    "readinto) needed. Text I/O classes work with str data.\n"
    "\n"
    "Note that calling any method (even inquiries) on a closed stream is\n"
    "undefined. Implementations may raise IOError in this case.\n"
    "\n"
    "IOBase (and its subclasses) support the iterator protocol, meaning\n"
    "that an IOBase object can be iterated over yielding the lines in a\n"
    "stream.\n"
    "\n"
    "IOBase also supports the :keyword:`with` statement. In this example,\n"
53
    "fp is closed after the suite of the with statement is complete:\n"
54 55 56 57 58 59 60 61
    "\n"
    "with open('spam.txt', 'r') as fp:\n"
    "    fp.write('Spam and eggs!')\n");

/* Use this macro whenever you want to check the internal `closed` status
   of the IOBase object rather than the virtual `closed` attribute as returned
   by whatever subclass. */

62
_Py_IDENTIFIER(__IOBase_closed);
63
#define IS_CLOSED(self) \
64
    _PyObject_HasAttrId(self, &PyId___IOBase_closed)
65 66 67

/* Internal methods */
static PyObject *
68
iobase_unsupported(const char *message)
69 70 71 72 73 74 75
{
    PyErr_SetString(IO_STATE->unsupported_operation, message);
    return NULL;
}

/* Positionning */

76
PyDoc_STRVAR(iobase_seek_doc,
77 78
    "Change stream position.\n"
    "\n"
79
    "Change the stream position to the given byte offset. The offset is\n"
80 81 82 83 84 85 86 87 88 89
    "interpreted relative to the position indicated by whence.  Values\n"
    "for whence are:\n"
    "\n"
    "* 0 -- start of stream (the default); offset should be zero or positive\n"
    "* 1 -- current stream position; offset may be negative\n"
    "* 2 -- end of stream; offset is usually negative\n"
    "\n"
    "Return the new absolute position.");

static PyObject *
90
iobase_seek(PyObject *self, PyObject *args)
91
{
92
    return iobase_unsupported("seek");
93 94
}

95
PyDoc_STRVAR(iobase_tell_doc,
96 97 98
             "Return current stream position.");

static PyObject *
99
iobase_tell(PyObject *self, PyObject *args)
100
{
101
    _Py_IDENTIFIER(seek);
102 103

    return _PyObject_CallMethodId(self, &PyId_seek, "ii", 0, 1);
104 105
}

106
PyDoc_STRVAR(iobase_truncate_doc,
107 108
    "Truncate file to size bytes.\n"
    "\n"
109 110
    "File pointer is left unchanged.  Size defaults to the current IO\n"
    "position as reported by tell().  Returns the new size.");
111 112

static PyObject *
113
iobase_truncate(PyObject *self, PyObject *args)
114
{
115
    return iobase_unsupported("truncate");
116 117 118 119
}

/* Flush and close methods */

120
PyDoc_STRVAR(iobase_flush_doc,
121 122 123 124 125
    "Flush write buffers, if applicable.\n"
    "\n"
    "This is not implemented for read-only and non-blocking streams.\n");

static PyObject *
126
iobase_flush(PyObject *self, PyObject *args)
127 128 129 130 131 132 133 134 135
{
    /* XXX Should this return the number of bytes written??? */
    if (IS_CLOSED(self)) {
        PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
        return NULL;
    }
    Py_RETURN_NONE;
}

136
PyDoc_STRVAR(iobase_close_doc,
137 138 139 140 141
    "Flush and close the IO object.\n"
    "\n"
    "This method has no effect if the file is already closed.\n");

static int
142
iobase_closed(PyObject *self)
143 144 145 146 147 148 149 150 151 152 153 154 155 156
{
    PyObject *res;
    int closed;
    /* This gets the derived attribute, which is *not* __IOBase_closed
       in most cases! */
    res = PyObject_GetAttr(self, _PyIO_str_closed);
    if (res == NULL)
        return 0;
    closed = PyObject_IsTrue(res);
    Py_DECREF(res);
    return closed;
}

static PyObject *
157
iobase_closed_get(PyObject *self, void *context)
158 159 160 161 162
{
    return PyBool_FromLong(IS_CLOSED(self));
}

PyObject *
163
_PyIOBase_check_closed(PyObject *self, PyObject *args)
164
{
165
    if (iobase_closed(self)) {
166 167 168 169 170 171 172 173 174 175 176 177 178 179
        PyErr_SetString(PyExc_ValueError, "I/O operation on closed file.");
        return NULL;
    }
    if (args == Py_True)
        return Py_None;
    else
        Py_RETURN_NONE;
}

/* XXX: IOBase thinks it has to maintain its own internal state in
   `__IOBase_closed` and call flush() by itself, but it is redundant with
   whatever behaviour a non-trivial derived class will implement. */

static PyObject *
180
iobase_close(PyObject *self, PyObject *args)
181 182
{
    PyObject *res;
183
    _Py_IDENTIFIER(__IOBase_closed);
184 185 186 187 188

    if (IS_CLOSED(self))
        Py_RETURN_NONE;

    res = PyObject_CallMethodObjArgs(self, _PyIO_str_flush, NULL);
189
    _PyObject_SetAttrId(self, &PyId___IOBase_closed, Py_True);
190
    if (res == NULL) {
191
        return NULL;
192 193 194 195 196 197 198
    }
    Py_XDECREF(res);
    Py_RETURN_NONE;
}

/* Finalization and garbage collection support */

199 200
static void
iobase_finalize(PyObject *self)
201 202
{
    PyObject *res;
203 204 205 206 207 208
    PyObject *error_type, *error_value, *error_traceback;
    int closed;
    _Py_IDENTIFIER(_finalizing);

    /* Save the current exception, if any. */
    PyErr_Fetch(&error_type, &error_value, &error_traceback);
209 210 211 212

    /* If `closed` doesn't exist or can't be evaluated as bool, then the
       object is probably in an unusable state, so ignore. */
    res = PyObject_GetAttr(self, _PyIO_str_closed);
213
    if (res == NULL) {
214
        PyErr_Clear();
215 216
        closed = -1;
    }
217 218 219 220 221 222 223
    else {
        closed = PyObject_IsTrue(res);
        Py_DECREF(res);
        if (closed == -1)
            PyErr_Clear();
    }
    if (closed == 0) {
224 225 226 227
        /* Signal close() that it was called as part of the object
           finalization process. */
        if (_PyObject_SetAttrId(self, &PyId__finalizing, Py_True))
            PyErr_Clear();
228 229 230 231 232 233 234 235 236 237
        res = PyObject_CallMethodObjArgs((PyObject *) self, _PyIO_str_close,
                                          NULL);
        /* Silencing I/O errors is bad, but printing spurious tracebacks is
           equally as bad, and potentially more frequent (because of
           shutdown issues). */
        if (res == NULL)
            PyErr_Clear();
        else
            Py_DECREF(res);
    }
238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255

    /* Restore the saved exception. */
    PyErr_Restore(error_type, error_value, error_traceback);
}

int
_PyIOBase_finalize(PyObject *self)
{
    int is_zombie;

    /* If _PyIOBase_finalize() is called from a destructor, we need to
       resurrect the object as calling close() can invoke arbitrary code. */
    is_zombie = (Py_REFCNT(self) == 0);
    if (is_zombie)
        return PyObject_CallFinalizerFromDealloc(self);
    else {
        PyObject_CallFinalizer(self);
        return 0;
256 257 258 259
    }
}

static int
260
iobase_traverse(iobase *self, visitproc visit, void *arg)
261 262 263 264 265 266
{
    Py_VISIT(self->dict);
    return 0;
}

static int
267
iobase_clear(iobase *self)
268 269 270 271 272 273 274 275
{
    Py_CLEAR(self->dict);
    return 0;
}

/* Destructor */

static void
276
iobase_dealloc(iobase *self)
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298
{
    /* NOTE: since IOBaseObject has its own dict, Python-defined attributes
       are still available here for close() to use.
       However, if the derived class declares a __slots__, those slots are
       already gone.
    */
    if (_PyIOBase_finalize((PyObject *) self) < 0) {
        /* When called from a heap type's dealloc, the type will be
           decref'ed on return (see e.g. subtype_dealloc in typeobject.c). */
        if (PyType_HasFeature(Py_TYPE(self), Py_TPFLAGS_HEAPTYPE))
            Py_INCREF(Py_TYPE(self));
        return;
    }
    _PyObject_GC_UNTRACK(self);
    if (self->weakreflist != NULL)
        PyObject_ClearWeakRefs((PyObject *) self);
    Py_CLEAR(self->dict);
    Py_TYPE(self)->tp_free((PyObject *) self);
}

/* Inquiry methods */

299
PyDoc_STRVAR(iobase_seekable_doc,
300 301
    "Return whether object supports random access.\n"
    "\n"
302
    "If False, seek(), tell() and truncate() will raise UnsupportedOperation.\n"
303 304 305
    "This method may need to do a test seek().");

static PyObject *
306
iobase_seekable(PyObject *self, PyObject *args)
307 308 309 310 311
{
    Py_RETURN_FALSE;
}

PyObject *
312
_PyIOBase_check_seekable(PyObject *self, PyObject *args)
313 314 315 316 317 318
{
    PyObject *res  = PyObject_CallMethodObjArgs(self, _PyIO_str_seekable, NULL);
    if (res == NULL)
        return NULL;
    if (res != Py_True) {
        Py_CLEAR(res);
319
        iobase_unsupported("File or stream is not seekable.");
320 321 322 323 324 325 326 327
        return NULL;
    }
    if (args == Py_True) {
        Py_DECREF(res);
    }
    return res;
}

328
PyDoc_STRVAR(iobase_readable_doc,
329 330
    "Return whether object was opened for reading.\n"
    "\n"
331
    "If False, read() will raise UnsupportedOperation.");
332 333

static PyObject *
334
iobase_readable(PyObject *self, PyObject *args)
335 336 337 338 339 340
{
    Py_RETURN_FALSE;
}

/* May be called with any object */
PyObject *
341
_PyIOBase_check_readable(PyObject *self, PyObject *args)
342 343 344 345 346 347
{
    PyObject *res  = PyObject_CallMethodObjArgs(self, _PyIO_str_readable, NULL);
    if (res == NULL)
        return NULL;
    if (res != Py_True) {
        Py_CLEAR(res);
348
        iobase_unsupported("File or stream is not readable.");
349 350 351 352 353 354 355 356
        return NULL;
    }
    if (args == Py_True) {
        Py_DECREF(res);
    }
    return res;
}

357
PyDoc_STRVAR(iobase_writable_doc,
358 359
    "Return whether object was opened for writing.\n"
    "\n"
360
    "If False, write() will raise UnsupportedOperation.");
361 362

static PyObject *
363
iobase_writable(PyObject *self, PyObject *args)
364 365 366 367 368 369
{
    Py_RETURN_FALSE;
}

/* May be called with any object */
PyObject *
370
_PyIOBase_check_writable(PyObject *self, PyObject *args)
371 372 373 374 375 376
{
    PyObject *res  = PyObject_CallMethodObjArgs(self, _PyIO_str_writable, NULL);
    if (res == NULL)
        return NULL;
    if (res != Py_True) {
        Py_CLEAR(res);
377
        iobase_unsupported("File or stream is not writable.");
378 379 380 381 382 383 384 385 386 387 388
        return NULL;
    }
    if (args == Py_True) {
        Py_DECREF(res);
    }
    return res;
}

/* Context manager */

static PyObject *
389
iobase_enter(PyObject *self, PyObject *args)
390
{
391
    if (_PyIOBase_check_closed(self, Py_True) == NULL)
392 393 394 395 396 397 398
        return NULL;

    Py_INCREF(self);
    return self;
}

static PyObject *
399
iobase_exit(PyObject *self, PyObject *args)
400 401 402 403 404 405 406 407
{
    return PyObject_CallMethodObjArgs(self, _PyIO_str_close, NULL);
}

/* Lower-level APIs */

/* XXX Should these be present even if unimplemented? */

408
PyDoc_STRVAR(iobase_fileno_doc,
409 410 411 412 413
    "Returns underlying file descriptor if one exists.\n"
    "\n"
    "An IOError is raised if the IO object does not use a file descriptor.\n");

static PyObject *
414
iobase_fileno(PyObject *self, PyObject *args)
415
{
416
    return iobase_unsupported("fileno");
417 418
}

419
PyDoc_STRVAR(iobase_isatty_doc,
420 421 422 423 424
    "Return whether this is an 'interactive' stream.\n"
    "\n"
    "Return False if it can't be determined.\n");

static PyObject *
425
iobase_isatty(PyObject *self, PyObject *args)
426
{
427
    if (_PyIOBase_check_closed(self, Py_True) == NULL)
428 429 430 431 432 433
        return NULL;
    Py_RETURN_FALSE;
}

/* Readline(s) and writelines */

434
PyDoc_STRVAR(iobase_readline_doc,
435 436 437 438
    "Read and return a line from the stream.\n"
    "\n"
    "If limit is specified, at most limit bytes will be read.\n"
    "\n"
439
    "The line terminator is always b'\\n' for binary files; for text\n"
440 441 442 443
    "files, the newlines argument to open can be used to select the line\n"
    "terminator(s) recognized.\n");

static PyObject *
444
iobase_readline(PyObject *self, PyObject *args)
445 446 447 448 449 450 451
{
    /* For backwards compatibility, a (slowish) readline(). */

    Py_ssize_t limit = -1;
    int has_peek = 0;
    PyObject *buffer, *result;
    Py_ssize_t old_size = -1;
452
    _Py_IDENTIFIER(read);
453
    _Py_IDENTIFIER(peek);
454

455
    if (!PyArg_ParseTuple(args, "|O&:readline", &_PyIO_ConvertSsize_t, &limit)) {
456 457 458
        return NULL;
    }

459
    if (_PyObject_HasAttrId(self, &PyId_peek))
460 461 462 463 464 465 466 467 468 469 470
        has_peek = 1;

    buffer = PyByteArray_FromStringAndSize(NULL, 0);
    if (buffer == NULL)
        return NULL;

    while (limit < 0 || Py_SIZE(buffer) < limit) {
        Py_ssize_t nreadahead = 1;
        PyObject *b;

        if (has_peek) {
471
            PyObject *readahead = _PyObject_CallMethodId(self, &PyId_peek, "i", 1);
472 473 474 475 476 477
            if (readahead == NULL) {
                /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
                   when EINTR occurs so we needn't do it ourselves. */
                if (_PyIO_trap_eintr()) {
                    continue;
                }
478
                goto fail;
479
            }
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510
            if (!PyBytes_Check(readahead)) {
                PyErr_Format(PyExc_IOError,
                             "peek() should have returned a bytes object, "
                             "not '%.200s'", Py_TYPE(readahead)->tp_name);
                Py_DECREF(readahead);
                goto fail;
            }
            if (PyBytes_GET_SIZE(readahead) > 0) {
                Py_ssize_t n = 0;
                const char *buf = PyBytes_AS_STRING(readahead);
                if (limit >= 0) {
                    do {
                        if (n >= PyBytes_GET_SIZE(readahead) || n >= limit)
                            break;
                        if (buf[n++] == '\n')
                            break;
                    } while (1);
                }
                else {
                    do {
                        if (n >= PyBytes_GET_SIZE(readahead))
                            break;
                        if (buf[n++] == '\n')
                            break;
                    } while (1);
                }
                nreadahead = n;
            }
            Py_DECREF(readahead);
        }

511
        b = _PyObject_CallMethodId(self, &PyId_read, "n", nreadahead);
512 513 514 515 516 517
        if (b == NULL) {
            /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
               when EINTR occurs so we needn't do it ourselves. */
            if (_PyIO_trap_eintr()) {
                continue;
            }
518
            goto fail;
519
        }
520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552
        if (!PyBytes_Check(b)) {
            PyErr_Format(PyExc_IOError,
                         "read() should have returned a bytes object, "
                         "not '%.200s'", Py_TYPE(b)->tp_name);
            Py_DECREF(b);
            goto fail;
        }
        if (PyBytes_GET_SIZE(b) == 0) {
            Py_DECREF(b);
            break;
        }

        old_size = PyByteArray_GET_SIZE(buffer);
        PyByteArray_Resize(buffer, old_size + PyBytes_GET_SIZE(b));
        memcpy(PyByteArray_AS_STRING(buffer) + old_size,
               PyBytes_AS_STRING(b), PyBytes_GET_SIZE(b));

        Py_DECREF(b);

        if (PyByteArray_AS_STRING(buffer)[PyByteArray_GET_SIZE(buffer) - 1] == '\n')
            break;
    }

    result = PyBytes_FromStringAndSize(PyByteArray_AS_STRING(buffer),
                                       PyByteArray_GET_SIZE(buffer));
    Py_DECREF(buffer);
    return result;
  fail:
    Py_DECREF(buffer);
    return NULL;
}

static PyObject *
553
iobase_iter(PyObject *self)
554
{
555
    if (_PyIOBase_check_closed(self, Py_True) == NULL)
556 557 558 559 560 561 562
        return NULL;

    Py_INCREF(self);
    return self;
}

static PyObject *
563
iobase_iternext(PyObject *self)
564 565 566 567 568 569 570 571 572 573 574 575 576 577
{
    PyObject *line = PyObject_CallMethodObjArgs(self, _PyIO_str_readline, NULL);

    if (line == NULL)
        return NULL;

    if (PyObject_Size(line) == 0) {
        Py_DECREF(line);
        return NULL;
    }

    return line;
}

578
PyDoc_STRVAR(iobase_readlines_doc,
579 580 581 582 583 584 585
    "Return a list of lines from the stream.\n"
    "\n"
    "hint can be specified to control the number of lines read: no more\n"
    "lines will be read if the total size (in bytes/characters) of all\n"
    "lines so far exceeds hint.");

static PyObject *
586
iobase_readlines(PyObject *self, PyObject *args)
587 588
{
    Py_ssize_t hint = -1, length = 0;
589
    PyObject *result;
590

591
    if (!PyArg_ParseTuple(args, "|O&:readlines", &_PyIO_ConvertSsize_t, &hint)) {
592 593 594 595 596 597 598 599 600 601 602
        return NULL;
    }

    result = PyList_New(0);
    if (result == NULL)
        return NULL;

    if (hint <= 0) {
        /* XXX special-casing this made sense in the Python version in order
           to remove the bytecode interpretation overhead, but it could
           probably be removed here. */
603
        _Py_IDENTIFIER(extend);
604 605
        PyObject *ret = _PyObject_CallMethodId(result, &PyId_extend, "O", self);

606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639
        if (ret == NULL) {
            Py_DECREF(result);
            return NULL;
        }
        Py_DECREF(ret);
        return result;
    }

    while (1) {
        PyObject *line = PyIter_Next(self);
        if (line == NULL) {
            if (PyErr_Occurred()) {
                Py_DECREF(result);
                return NULL;
            }
            else
                break; /* StopIteration raised */
        }

        if (PyList_Append(result, line) < 0) {
            Py_DECREF(line);
            Py_DECREF(result);
            return NULL;
        }
        length += PyObject_Size(line);
        Py_DECREF(line);

        if (length > hint)
            break;
    }
    return result;
}

static PyObject *
640
iobase_writelines(PyObject *self, PyObject *args)
641 642 643 644 645 646 647
{
    PyObject *lines, *iter, *res;

    if (!PyArg_ParseTuple(args, "O:writelines", &lines)) {
        return NULL;
    }

648
    if (_PyIOBase_check_closed(self, Py_True) == NULL)
649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665
        return NULL;

    iter = PyObject_GetIter(lines);
    if (iter == NULL)
        return NULL;

    while (1) {
        PyObject *line = PyIter_Next(iter);
        if (line == NULL) {
            if (PyErr_Occurred()) {
                Py_DECREF(iter);
                return NULL;
            }
            else
                break; /* Stop Iteration */
        }

666 667 668 669
        res = NULL;
        do {
            res = PyObject_CallMethodObjArgs(self, _PyIO_str_write, line, NULL);
        } while (res == NULL && _PyIO_trap_eintr());
670 671 672 673 674 675 676 677 678 679 680
        Py_DECREF(line);
        if (res == NULL) {
            Py_DECREF(iter);
            return NULL;
        }
        Py_DECREF(res);
    }
    Py_DECREF(iter);
    Py_RETURN_NONE;
}

681 682 683 684 685 686
static PyMethodDef iobase_methods[] = {
    {"seek", iobase_seek, METH_VARARGS, iobase_seek_doc},
    {"tell", iobase_tell, METH_NOARGS, iobase_tell_doc},
    {"truncate", iobase_truncate, METH_VARARGS, iobase_truncate_doc},
    {"flush", iobase_flush, METH_NOARGS, iobase_flush_doc},
    {"close", iobase_close, METH_NOARGS, iobase_close_doc},
687

688 689 690
    {"seekable", iobase_seekable, METH_NOARGS, iobase_seekable_doc},
    {"readable", iobase_readable, METH_NOARGS, iobase_readable_doc},
    {"writable", iobase_writable, METH_NOARGS, iobase_writable_doc},
691

692 693 694 695
    {"_checkClosed",   _PyIOBase_check_closed, METH_NOARGS},
    {"_checkSeekable", _PyIOBase_check_seekable, METH_NOARGS},
    {"_checkReadable", _PyIOBase_check_readable, METH_NOARGS},
    {"_checkWritable", _PyIOBase_check_writable, METH_NOARGS},
696

697 698
    {"fileno", iobase_fileno, METH_NOARGS, iobase_fileno_doc},
    {"isatty", iobase_isatty, METH_NOARGS, iobase_isatty_doc},
699

700 701
    {"__enter__", iobase_enter, METH_NOARGS},
    {"__exit__", iobase_exit, METH_VARARGS},
702

703 704 705
    {"readline", iobase_readline, METH_VARARGS, iobase_readline_doc},
    {"readlines", iobase_readlines, METH_VARARGS, iobase_readlines_doc},
    {"writelines", iobase_writelines, METH_VARARGS},
706 707 708 709

    {NULL, NULL}
};

710
static PyGetSetDef iobase_getset[] = {
711
    {"__dict__", PyObject_GenericGetDict, NULL, NULL},
712
    {"closed", (getter)iobase_closed_get, NULL, NULL},
713
    {NULL}
714 715 716 717 718 719
};


PyTypeObject PyIOBase_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "_io._IOBase",              /*tp_name*/
720
    sizeof(iobase),             /*tp_basicsize*/
721
    0,                          /*tp_itemsize*/
722
    (destructor)iobase_dealloc, /*tp_dealloc*/
723 724 725 726 727 728 729 730 731 732 733 734 735 736 737
    0,                          /*tp_print*/
    0,                          /*tp_getattr*/
    0,                          /*tp_setattr*/
    0,                          /*tp_compare */
    0,                          /*tp_repr*/
    0,                          /*tp_as_number*/
    0,                          /*tp_as_sequence*/
    0,                          /*tp_as_mapping*/
    0,                          /*tp_hash */
    0,                          /*tp_call*/
    0,                          /*tp_str*/
    0,                          /*tp_getattro*/
    0,                          /*tp_setattro*/
    0,                          /*tp_as_buffer*/
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE
738
        | Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_HAVE_FINALIZE,   /*tp_flags*/
739 740 741
    iobase_doc,                 /* tp_doc */
    (traverseproc)iobase_traverse, /* tp_traverse */
    (inquiry)iobase_clear,      /* tp_clear */
742
    0,                          /* tp_richcompare */
743 744 745 746
    offsetof(iobase, weakreflist), /* tp_weaklistoffset */
    iobase_iter,                /* tp_iter */
    iobase_iternext,            /* tp_iternext */
    iobase_methods,             /* tp_methods */
747
    0,                          /* tp_members */
748
    iobase_getset,              /* tp_getset */
749 750 751 752
    0,                          /* tp_base */
    0,                          /* tp_dict */
    0,                          /* tp_descr_get */
    0,                          /* tp_descr_set */
753
    offsetof(iobase, dict),     /* tp_dictoffset */
754 755 756
    0,                          /* tp_init */
    0,                          /* tp_alloc */
    PyType_GenericNew,          /* tp_new */
757 758 759 760 761 762 763 764 765 766
    0,                          /* tp_free */
    0,                          /* tp_is_gc */
    0,                          /* tp_bases */
    0,                          /* tp_mro */
    0,                          /* tp_cache */
    0,                          /* tp_subclasses */
    0,                          /* tp_weaklist */
    0,                          /* tp_del */
    0,                          /* tp_version_tag */
    (destructor)iobase_finalize, /* tp_finalize */
767 768 769 770 771 772
};


/*
 * RawIOBase class, Inherits from IOBase.
 */
773
PyDoc_STRVAR(rawiobase_doc,
774 775 776 777 778 779 780 781 782 783 784 785 786 787 788
             "Base class for raw binary I/O.");

/*
 * The read() method is implemented by calling readinto(); derived classes
 * that want to support read() only need to implement readinto() as a
 * primitive operation.  In general, readinto() can be more efficient than
 * read().
 *
 * (It would be tempting to also provide an implementation of readinto() in
 * terms of read(), in case the latter is a more suitable primitive operation,
 * but that would lead to nasty recursion in case a subclass doesn't implement
 * either.)
*/

static PyObject *
789
rawiobase_read(PyObject *self, PyObject *args)
790 791 792 793 794 795 796 797
{
    Py_ssize_t n = -1;
    PyObject *b, *res;

    if (!PyArg_ParseTuple(args, "|n:read", &n)) {
        return NULL;
    }

798
    if (n < 0) {
799
        _Py_IDENTIFIER(readall);
800 801 802

        return _PyObject_CallMethodId(self, &PyId_readall, NULL);
    }
803 804 805 806 807 808 809 810

    /* TODO: allocate a bytes object directly instead and manually construct
       a writable memoryview pointing to it. */
    b = PyByteArray_FromStringAndSize(NULL, n);
    if (b == NULL)
        return NULL;

    res = PyObject_CallMethodObjArgs(self, _PyIO_str_readinto, b, NULL);
811
    if (res == NULL || res == Py_None) {
812
        Py_DECREF(b);
813
        return res;
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828
    }

    n = PyNumber_AsSsize_t(res, PyExc_ValueError);
    Py_DECREF(res);
    if (n == -1 && PyErr_Occurred()) {
        Py_DECREF(b);
        return NULL;
    }

    res = PyBytes_FromStringAndSize(PyByteArray_AsString(b), n);
    Py_DECREF(b);
    return res;
}


829
PyDoc_STRVAR(rawiobase_readall_doc,
830 831 832
             "Read until EOF, using multiple read() call.");

static PyObject *
833
rawiobase_readall(PyObject *self, PyObject *args)
834
{
835 836 837 838 839 840
    int r;
    PyObject *chunks = PyList_New(0);
    PyObject *result;
    
    if (chunks == NULL)
        return NULL;
841 842

    while (1) {
843
        _Py_IDENTIFIER(read);
844 845
        PyObject *data = _PyObject_CallMethodId(self, &PyId_read,
                                                "i", DEFAULT_BUFFER_SIZE);
846
        if (!data) {
847 848 849 850 851
            /* NOTE: PyErr_SetFromErrno() calls PyErr_CheckSignals()
               when EINTR occurs so we needn't do it ourselves. */
            if (_PyIO_trap_eintr()) {
                continue;
            }
852
            Py_DECREF(chunks);
853 854
            return NULL;
        }
855 856 857 858 859 860 861 862
        if (data == Py_None) {
            if (PyList_GET_SIZE(chunks) == 0) {
                Py_DECREF(chunks);
                return data;
            }
            Py_DECREF(data);
            break;
        }
863
        if (!PyBytes_Check(data)) {
864
            Py_DECREF(chunks);
865 866 867 868
            Py_DECREF(data);
            PyErr_SetString(PyExc_TypeError, "read() should return bytes");
            return NULL;
        }
869 870
        if (PyBytes_GET_SIZE(data) == 0) {
            /* EOF */
871 872
            Py_DECREF(data);
            break;
873 874 875 876 877 878 879
        }
        r = PyList_Append(chunks, data);
        Py_DECREF(data);
        if (r < 0) {
            Py_DECREF(chunks);
            return NULL;
        }
880
    }
881 882 883
    result = _PyBytes_Join(_PyIO_empty_bytes, chunks);
    Py_DECREF(chunks);
    return result;
884 885
}

886 887 888
static PyMethodDef rawiobase_methods[] = {
    {"read", rawiobase_read, METH_VARARGS},
    {"readall", rawiobase_readall, METH_NOARGS, rawiobase_readall_doc},
889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911
    {NULL, NULL}
};

PyTypeObject PyRawIOBase_Type = {
    PyVarObject_HEAD_INIT(NULL, 0)
    "_io._RawIOBase",                /*tp_name*/
    0,                          /*tp_basicsize*/
    0,                          /*tp_itemsize*/
    0,                          /*tp_dealloc*/
    0,                          /*tp_print*/
    0,                          /*tp_getattr*/
    0,                          /*tp_setattr*/
    0,                          /*tp_compare */
    0,                          /*tp_repr*/
    0,                          /*tp_as_number*/
    0,                          /*tp_as_sequence*/
    0,                          /*tp_as_mapping*/
    0,                          /*tp_hash */
    0,                          /*tp_call*/
    0,                          /*tp_str*/
    0,                          /*tp_getattro*/
    0,                          /*tp_setattro*/
    0,                          /*tp_as_buffer*/
912
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE | Py_TPFLAGS_HAVE_FINALIZE,  /*tp_flags*/
913
    rawiobase_doc,              /* tp_doc */
914 915 916 917 918 919
    0,                          /* tp_traverse */
    0,                          /* tp_clear */
    0,                          /* tp_richcompare */
    0,                          /* tp_weaklistoffset */
    0,                          /* tp_iter */
    0,                          /* tp_iternext */
920
    rawiobase_methods,          /* tp_methods */
921 922 923 924 925 926 927 928 929 930
    0,                          /* tp_members */
    0,                          /* tp_getset */
    &PyIOBase_Type,             /* tp_base */
    0,                          /* tp_dict */
    0,                          /* tp_descr_get */
    0,                          /* tp_descr_set */
    0,                          /* tp_dictoffset */
    0,                          /* tp_init */
    0,                          /* tp_alloc */
    0,                          /* tp_new */
931 932 933 934 935 936 937 938 939 940
    0,                          /* tp_free */
    0,                          /* tp_is_gc */
    0,                          /* tp_bases */
    0,                          /* tp_mro */
    0,                          /* tp_cache */
    0,                          /* tp_subclasses */
    0,                          /* tp_weaklist */
    0,                          /* tp_del */
    0,                          /* tp_version_tag */
    0,                          /* tp_finalize */
941
};