bytesio.c 24.6 KB
Newer Older
1
#include "Python.h"
2 3
#include "structmember.h"       /* for offsetof() */
#include "_iomodule.h"
4 5 6 7 8 9 10

typedef struct {
    PyObject_HEAD
    char *buf;
    Py_ssize_t pos;
    Py_ssize_t string_size;
    size_t buf_size;
11 12 13
    PyObject *dict;
    PyObject *weakreflist;
} bytesio;
14 15 16 17 18 19 20 21 22 23 24 25

#define CHECK_CLOSED(self)                                  \
    if ((self)->buf == NULL) {                              \
        PyErr_SetString(PyExc_ValueError,                   \
                        "I/O operation on closed file.");   \
        return NULL;                                        \
    }

/* Internal routine to get a line from the buffer of a BytesIO
   object. Returns the length between the current position to the
   next newline character. */
static Py_ssize_t
26
get_line(bytesio *self, char **output)
27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58
{
    char *n;
    const char *str_end;
    Py_ssize_t len;

    assert(self->buf != NULL);

    /* Move to the end of the line, up to the end of the string, s. */
    str_end = self->buf + self->string_size;
    for (n = self->buf + self->pos;
         n < str_end && *n != '\n';
         n++);

    /* Skip the newline character */
    if (n < str_end)
        n++;

    /* Get the length from the current position to the end of the line. */
    len = n - (self->buf + self->pos);
    *output = self->buf + self->pos;

    assert(len >= 0);
    assert(self->pos < PY_SSIZE_T_MAX - len);
    self->pos += len;

    return len;
}

/* Internal routine for changing the size of the buffer of BytesIO objects.
   The caller should ensure that the 'size' argument is non-negative.  Returns
   0 on success, -1 otherwise. */
static int
59
resize_buffer(bytesio *self, size_t size)
60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110
{
    /* Here, unsigned types are used to avoid dealing with signed integer
       overflow, which is undefined in C. */
    size_t alloc = self->buf_size;
    char *new_buf = NULL;

    assert(self->buf != NULL);

    /* For simplicity, stay in the range of the signed type. Anyway, Python
       doesn't allow strings to be longer than this. */
    if (size > PY_SSIZE_T_MAX)
        goto overflow;

    if (size < alloc / 2) {
        /* Major downsize; resize down to exact size. */
        alloc = size + 1;
    }
    else if (size < alloc) {
        /* Within allocated size; quick exit */
        return 0;
    }
    else if (size <= alloc * 1.125) {
        /* Moderate upsize; overallocate similar to list_resize() */
        alloc = size + (size >> 3) + (size < 9 ? 3 : 6);
    }
    else {
        /* Major upsize; resize up to exact size */
        alloc = size + 1;
    }

    if (alloc > ((size_t)-1) / sizeof(char))
        goto overflow;
    new_buf = (char *)PyMem_Realloc(self->buf, alloc * sizeof(char));
    if (new_buf == NULL) {
        PyErr_NoMemory();
        return -1;
    }
    self->buf_size = alloc;
    self->buf = new_buf;

    return 0;

  overflow:
    PyErr_SetString(PyExc_OverflowError,
                    "new buffer size too large");
    return -1;
}

/* Internal routine for writing a string of bytes to the buffer of a BytesIO
   object. Returns the number of bytes wrote, or -1 on error. */
static Py_ssize_t
111
write_bytes(bytesio *self, const char *bytes, Py_ssize_t len)
112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
{
    assert(self->buf != NULL);
    assert(self->pos >= 0);
    assert(len >= 0);

    if ((size_t)self->pos + len > self->buf_size) {
        if (resize_buffer(self, (size_t)self->pos + len) < 0)
            return -1;
    }

    if (self->pos > self->string_size) {
        /* In case of overseek, pad with null bytes the buffer region between
           the end of stream and the current position.

          0   lo      string_size                           hi
          |   |<---used--->|<----------available----------->|
          |   |            <--to pad-->|<---to write--->    |
          0   buf                   position
        */
        memset(self->buf + self->string_size, '\0',
               (self->pos - self->string_size) * sizeof(char));
    }

    /* Copy the data to the internal buffer, overwriting some of the existing
       data if self->pos < self->string_size. */
    memcpy(self->buf + self->pos, bytes, len);
    self->pos += len;

    /* Set the new length of the internal string if it has changed. */
    if (self->string_size < self->pos) {
        self->string_size = self->pos;
    }

    return len;
}

static PyObject *
149
bytesio_get_closed(bytesio *self)
150
{
151
    if (self->buf == NULL) {
152
        Py_RETURN_TRUE;
153 154
    }
    else {
155
        Py_RETURN_FALSE;
156
    }
157 158 159 160
}

/* Generic getter for the writable, readable and seekable properties */
static PyObject *
161
return_true(bytesio *self)
162 163 164 165 166 167 168 169
{
    Py_RETURN_TRUE;
}

PyDoc_STRVAR(flush_doc,
"flush() -> None.  Does nothing.");

static PyObject *
170
bytesio_flush(bytesio *self)
171 172 173 174 175 176 177 178 179 180
{
    Py_RETURN_NONE;
}

PyDoc_STRVAR(getval_doc,
"getvalue() -> bytes.\n"
"\n"
"Retrieve the entire contents of the BytesIO object.");

static PyObject *
181
bytesio_getvalue(bytesio *self)
182 183
{
    CHECK_CLOSED(self);
184
    return PyBytes_FromStringAndSize(self->buf, self->string_size);
185 186 187 188 189 190 191 192 193
}

PyDoc_STRVAR(isatty_doc,
"isatty() -> False.\n"
"\n"
"Always returns False since BytesIO objects are not connected\n"
"to a tty-like device.");

static PyObject *
194
bytesio_isatty(bytesio *self)
195 196 197 198 199 200 201 202 203
{
    CHECK_CLOSED(self);
    Py_RETURN_FALSE;
}

PyDoc_STRVAR(tell_doc,
"tell() -> current file position, an integer\n");

static PyObject *
204
bytesio_tell(bytesio *self)
205 206
{
    CHECK_CLOSED(self);
207
    return PyLong_FromSsize_t(self->pos);
208 209 210 211 212 213 214 215 216
}

PyDoc_STRVAR(read_doc,
"read([size]) -> read at most size bytes, returned as a string.\n"
"\n"
"If the size argument is negative, read until EOF is reached.\n"
"Return an empty string at EOF.");

static PyObject *
217
bytesio_read(bytesio *self, PyObject *args)
218 219 220 221 222 223 224 225 226 227
{
    Py_ssize_t size, n;
    char *output;
    PyObject *arg = Py_None;

    CHECK_CLOSED(self);

    if (!PyArg_ParseTuple(args, "|O:read", &arg))
        return NULL;

228 229
    if (PyNumber_Check(arg)) {
        size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
230 231
        if (size == -1 && PyErr_Occurred())
            return NULL;
232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254
    }
    else if (arg == Py_None) {
        /* Read until EOF is reached, by default. */
        size = -1;
    }
    else {
        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
                     Py_TYPE(arg)->tp_name);
        return NULL;
    }

    /* adjust invalid sizes */
    n = self->string_size - self->pos;
    if (size < 0 || size > n) {
        size = n;
        if (size < 0)
            size = 0;
    }

    assert(self->buf != NULL);
    output = self->buf + self->pos;
    self->pos += size;

255
    return PyBytes_FromStringAndSize(output, size);
256 257 258 259 260 261 262 263 264 265
}


PyDoc_STRVAR(read1_doc,
"read1(size) -> read at most size bytes, returned as a string.\n"
"\n"
"If the size argument is negative or omitted, read until EOF is reached.\n"
"Return an empty string at EOF.");

static PyObject *
266
bytesio_read1(bytesio *self, PyObject *n)
267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
{
    PyObject *arg, *res;

    arg = PyTuple_Pack(1, n);
    if (arg == NULL)
        return NULL;
    res  = bytesio_read(self, arg);
    Py_DECREF(arg);
    return res;
}

PyDoc_STRVAR(readline_doc,
"readline([size]) -> next line from the file, as a string.\n"
"\n"
"Retain newline.  A non-negative size argument limits the maximum\n"
"number of bytes to return (an incomplete line may be returned then).\n"
"Return an empty string at EOF.\n");

static PyObject *
286
bytesio_readline(bytesio *self, PyObject *args)
287 288 289 290 291 292 293 294 295 296
{
    Py_ssize_t size, n;
    char *output;
    PyObject *arg = Py_None;

    CHECK_CLOSED(self);

    if (!PyArg_ParseTuple(args, "|O:readline", &arg))
        return NULL;

297 298
    if (PyNumber_Check(arg)) {
        size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
299 300
        if (size == -1 && PyErr_Occurred())
            return NULL;
301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319
    }
    else if (arg == Py_None) {
        /* No size limit, by default. */
        size = -1;
    }
    else {
        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
                     Py_TYPE(arg)->tp_name);
        return NULL;
    }

    n = get_line(self, &output);

    if (size >= 0 && size < n) {
        size = n - size;
        n -= size;
        self->pos -= size;
    }

320
    return PyBytes_FromStringAndSize(output, n);
321 322 323 324 325 326 327 328 329 330
}

PyDoc_STRVAR(readlines_doc,
"readlines([size]) -> list of strings, each a line from the file.\n"
"\n"
"Call readline() repeatedly and return a list of the lines so read.\n"
"The optional size argument, if given, is an approximate bound on the\n"
"total number of bytes in the lines returned.\n");

static PyObject *
331
bytesio_readlines(bytesio *self, PyObject *args)
332 333 334 335 336 337 338 339 340 341 342
{
    Py_ssize_t maxsize, size, n;
    PyObject *result, *line;
    char *output;
    PyObject *arg = Py_None;

    CHECK_CLOSED(self);

    if (!PyArg_ParseTuple(args, "|O:readlines", &arg))
        return NULL;

343 344
    if (PyNumber_Check(arg)) {
        maxsize = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
345 346
        if (maxsize == -1 && PyErr_Occurred())
            return NULL;
347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
    }
    else if (arg == Py_None) {
        /* No size limit, by default. */
        maxsize = -1;
    }
    else {
        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
                     Py_TYPE(arg)->tp_name);
        return NULL;
    }

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

    while ((n = get_line(self, &output)) != 0) {
364
        line = PyBytes_FromStringAndSize(output, n);
365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389
        if (!line)
            goto on_error;
        if (PyList_Append(result, line) == -1) {
            Py_DECREF(line);
            goto on_error;
        }
        Py_DECREF(line);
        size += n;
        if (maxsize > 0 && size >= maxsize)
            break;
    }
    return result;

  on_error:
    Py_DECREF(result);
    return NULL;
}

PyDoc_STRVAR(readinto_doc,
"readinto(bytearray) -> int.  Read up to len(b) bytes into b.\n"
"\n"
"Returns number of bytes read (0 for EOF), or None if the object\n"
"is set not to block as has no data to read.");

static PyObject *
390
bytesio_readinto(bytesio *self, PyObject *args)
391
{
392
    Py_buffer buf;
393 394 395 396
    Py_ssize_t len;

    CHECK_CLOSED(self);

397
    if (!PyArg_ParseTuple(args, "w*", &buf))
398 399
        return NULL;

400
    len = buf.len;
401 402 403
    if (self->pos + len > self->string_size)
        len = self->string_size - self->pos;

404
    memcpy(buf.buf, self->buf + self->pos, len);
405 406 407 408
    assert(self->pos + len < PY_SSIZE_T_MAX);
    assert(len >= 0);
    self->pos += len;

409 410
    PyBuffer_Release(&buf);
    return PyLong_FromSsize_t(len);
411 412 413 414 415 416
}

PyDoc_STRVAR(truncate_doc,
"truncate([size]) -> int.  Truncate the file to at most size bytes.\n"
"\n"
"Size defaults to the current file position, as returned by tell().\n"
417
"The current file position is unchanged.  Returns the new size.\n");
418 419

static PyObject *
420
bytesio_truncate(bytesio *self, PyObject *args)
421 422 423 424 425 426 427 428 429
{
    Py_ssize_t size;
    PyObject *arg = Py_None;

    CHECK_CLOSED(self);

    if (!PyArg_ParseTuple(args, "|O:truncate", &arg))
        return NULL;

430 431
    if (PyNumber_Check(arg)) {
        size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);
432 433
        if (size == -1 && PyErr_Occurred())
            return NULL;
434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
    }
    else if (arg == Py_None) {
        /* Truncate to current position if no argument is passed. */
        size = self->pos;
    }
    else {
        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",
                     Py_TYPE(arg)->tp_name);
        return NULL;
    }

    if (size < 0) {
        PyErr_Format(PyExc_ValueError,
                     "negative size value %zd", size);
        return NULL;
    }

    if (size < self->string_size) {
        self->string_size = size;
        if (resize_buffer(self, size) < 0)
            return NULL;
    }

457
    return PyLong_FromSsize_t(size);
458 459 460
}

static PyObject *
461
bytesio_iternext(bytesio *self)
462 463 464 465 466 467 468 469 470 471 472
{
    char *next;
    Py_ssize_t n;

    CHECK_CLOSED(self);

    n = get_line(self, &next);

    if (!next || n == 0)
        return NULL;

473
    return PyBytes_FromStringAndSize(next, n);
474 475 476 477 478 479 480 481 482 483 484 485
}

PyDoc_STRVAR(seek_doc,
"seek(pos, whence=0) -> int.  Change stream position.\n"
"\n"
"Seek to byte offset pos relative to position indicated by whence:\n"
"     0  Start of stream (the default).  pos should be >= 0;\n"
"     1  Current position - pos may be negative;\n"
"     2  End of stream - pos usually negative.\n"
"Returns the new absolute position.");

static PyObject *
486
bytesio_seek(bytesio *self, PyObject *args)
487
{
488
    PyObject *posobj;
489 490 491 492 493
    Py_ssize_t pos;
    int mode = 0;

    CHECK_CLOSED(self);

494
    if (!PyArg_ParseTuple(args, "O|i:seek", &posobj, &mode))
495 496
        return NULL;

497 498
    pos = PyNumber_AsSsize_t(posobj, PyExc_OverflowError);
    if (pos == -1 && PyErr_Occurred())
499
        return NULL;
500
    
501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535
    if (pos < 0 && mode == 0) {
        PyErr_Format(PyExc_ValueError,
                     "negative seek value %zd", pos);
        return NULL;
    }

    /* mode 0: offset relative to beginning of the string.
       mode 1: offset relative to current position.
       mode 2: offset relative the end of the string. */
    if (mode == 1) {
        if (pos > PY_SSIZE_T_MAX - self->pos) {
            PyErr_SetString(PyExc_OverflowError,
                            "new position too large");
            return NULL;
        }
        pos += self->pos;
    }
    else if (mode == 2) {
        if (pos > PY_SSIZE_T_MAX - self->string_size) {
            PyErr_SetString(PyExc_OverflowError,
                            "new position too large");
            return NULL;
        }
        pos += self->string_size;
    }
    else if (mode != 0) {
        PyErr_Format(PyExc_ValueError,
                     "invalid whence (%i, should be 0, 1 or 2)", mode);
        return NULL;
    }

    if (pos < 0)
        pos = 0;
    self->pos = pos;

536
    return PyLong_FromSsize_t(self->pos);
537 538 539 540 541 542 543 544
}

PyDoc_STRVAR(write_doc,
"write(bytes) -> int.  Write bytes to file.\n"
"\n"
"Return the number of bytes written.");

static PyObject *
545
bytesio_write(bytesio *self, PyObject *obj)
546 547
{
    Py_ssize_t n = 0;
548 549
    Py_buffer buf;
    PyObject *result = NULL;
550 551 552

    CHECK_CLOSED(self);

553
    if (PyObject_GetBuffer(obj, &buf, PyBUF_CONTIG_RO) < 0)
554 555
        return NULL;

556 557 558 559
    if (buf.len != 0)
        n = write_bytes(self, buf.buf, buf.len);
    if (n >= 0)
        result = PyLong_FromSsize_t(n);
560

561 562
    PyBuffer_Release(&buf);
    return result;
563 564 565 566 567 568 569 570 571 572
}

PyDoc_STRVAR(writelines_doc,
"writelines(sequence_of_strings) -> None.  Write strings to the file.\n"
"\n"
"Note that newlines are not added.  The sequence can be any iterable\n"
"object producing strings. This is equivalent to calling write() for\n"
"each string.");

static PyObject *
573
bytesio_writelines(bytesio *self, PyObject *v)
574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
{
    PyObject *it, *item;
    PyObject *ret;

    CHECK_CLOSED(self);

    it = PyObject_GetIter(v);
    if (it == NULL)
        return NULL;

    while ((item = PyIter_Next(it)) != NULL) {
        ret = bytesio_write(self, item);
        Py_DECREF(item);
        if (ret == NULL) {
            Py_DECREF(it);
            return NULL;
        }
        Py_DECREF(ret);
    }
    Py_DECREF(it);

    /* See if PyIter_Next failed */
    if (PyErr_Occurred())
        return NULL;

    Py_RETURN_NONE;
}

PyDoc_STRVAR(close_doc,
"close() -> None.  Disable all I/O operations.");

static PyObject *
606
bytesio_close(bytesio *self)
607 608 609 610 611 612 613 614
{
    if (self->buf != NULL) {
        PyMem_Free(self->buf);
        self->buf = NULL;
    }
    Py_RETURN_NONE;
}

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 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728
/* Pickling support.

   Note that only pickle protocol 2 and onward are supported since we use
   extended __reduce__ API of PEP 307 to make BytesIO instances picklable.

   Providing support for protocol < 2 would require the __reduce_ex__ method
   which is notably long-winded when defined properly.

   For BytesIO, the implementation would similar to one coded for
   object.__reduce_ex__, but slightly less general. To be more specific, we
   could call bytesio_getstate directly and avoid checking for the presence of
   a fallback __reduce__ method. However, we would still need a __newobj__
   function to use the efficient instance representation of PEP 307.
 */

static PyObject *
bytesio_getstate(bytesio *self)
{
    PyObject *initvalue = bytesio_getvalue(self);
    PyObject *dict;
    PyObject *state;

    if (initvalue == NULL)
        return NULL;
    if (self->dict == NULL) {
        Py_INCREF(Py_None);
        dict = Py_None;
    }
    else {
        dict = PyDict_Copy(self->dict);
        if (dict == NULL)
            return NULL;
    }

    state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);
    Py_DECREF(initvalue);
    return state;
}

static PyObject *
bytesio_setstate(bytesio *self, PyObject *state)
{
    PyObject *result;
    PyObject *position_obj;
    PyObject *dict;
    Py_ssize_t pos;

    assert(state != NULL);

    /* We allow the state tuple to be longer than 3, because we may need
       someday to extend the object's state without breaking
       backward-compatibility. */
    if (!PyTuple_Check(state) || Py_SIZE(state) < 3) {
        PyErr_Format(PyExc_TypeError,
                     "%.200s.__setstate__ argument should be 3-tuple, got %.200s",
                     Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);
        return NULL;
    }
    /* Reset the object to its default state. This is only needed to handle
       the case of repeated calls to __setstate__. */
    self->string_size = 0;
    self->pos = 0;

    /* Set the value of the internal buffer. If state[0] does not support the
       buffer protocol, bytesio_write will raise the appropriate TypeError. */
    result = bytesio_write(self, PyTuple_GET_ITEM(state, 0));
    if (result == NULL)
        return NULL;
    Py_DECREF(result);

    /* Set carefully the position value. Alternatively, we could use the seek
       method instead of modifying self->pos directly to better protect the
       object internal state against errneous (or malicious) inputs. */
    position_obj = PyTuple_GET_ITEM(state, 1);
    if (!PyIndex_Check(position_obj)) {
        PyErr_Format(PyExc_TypeError,
                     "second item of state must be an integer, not %.200s",
                     Py_TYPE(position_obj)->tp_name);
        return NULL;
    }
    pos = PyNumber_AsSsize_t(position_obj, PyExc_OverflowError);
    if (pos == -1 && PyErr_Occurred())
        return NULL;
    if (pos < 0) {
        PyErr_SetString(PyExc_ValueError,
                        "position value cannot be negative");
        return NULL;
    }
    self->pos = pos;

    /* Set the dictionary of the instance variables. */
    dict = PyTuple_GET_ITEM(state, 2);
    if (dict != Py_None) {
        if (!PyDict_Check(dict)) {
            PyErr_Format(PyExc_TypeError,
                         "third item of state should be a dict, got a %.200s",
                         Py_TYPE(dict)->tp_name);
            return NULL;
        }
        if (self->dict) {
            /* Alternatively, we could replace the internal dictionary
               completely. However, it seems more practical to just update it. */
            if (PyDict_Update(self->dict, dict) < 0)
                return NULL;
        }
        else {
            Py_INCREF(dict);
            self->dict = dict;
        }
    }

    Py_RETURN_NONE;
}

729
static void
730
bytesio_dealloc(bytesio *self)
731
{
732
    _PyObject_GC_UNTRACK(self);
733 734 735 736
    if (self->buf != NULL) {
        PyMem_Free(self->buf);
        self->buf = NULL;
    }
737 738 739
    Py_CLEAR(self->dict);
    if (self->weakreflist != NULL)
        PyObject_ClearWeakRefs((PyObject *) self);
740 741 742 743 744 745
    Py_TYPE(self)->tp_free(self);
}

static PyObject *
bytesio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
746
    bytesio *self;
747 748

    assert(type != NULL && type->tp_alloc != NULL);
749
    self = (bytesio *)type->tp_alloc(type, 0);
750 751 752
    if (self == NULL)
        return NULL;

753 754 755
    /* tp_alloc initializes all the fields to zero. So we don't have to
       initialize them here. */

756 757 758 759 760 761 762 763 764 765
    self->buf = (char *)PyMem_Malloc(0);
    if (self->buf == NULL) {
        Py_DECREF(self);
        return PyErr_NoMemory();
    }

    return (PyObject *)self;
}

static int
766
bytesio_init(bytesio *self, PyObject *args, PyObject *kwds)
767
{
768
    char *kwlist[] = {"initial_bytes", NULL};
769 770
    PyObject *initvalue = NULL;

771 772
    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:BytesIO", kwlist,
                                     &initvalue))
773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790
        return -1;

    /* In case, __init__ is called multiple times. */
    self->string_size = 0;
    self->pos = 0;

    if (initvalue && initvalue != Py_None) {
        PyObject *res;
        res = bytesio_write(self, initvalue);
        if (res == NULL)
            return -1;
        Py_DECREF(res);
        self->pos = 0;
    }

    return 0;
}

791 792 793 794 795 796 797 798 799 800 801 802 803 804 805
static int
bytesio_traverse(bytesio *self, visitproc visit, void *arg)
{
    Py_VISIT(self->dict);
    return 0;
}

static int
bytesio_clear(bytesio *self)
{
    Py_CLEAR(self->dict);
    return 0;
}


806 807 808
static PyGetSetDef bytesio_getsetlist[] = {
    {"closed",  (getter)bytesio_get_closed, NULL,
     "True if the file is closed."},
809
    {NULL},            /* sentinel */
810 811 812 813 814 815 816 817 818 819 820 821 822
};

static struct PyMethodDef bytesio_methods[] = {
    {"readable",   (PyCFunction)return_true,        METH_NOARGS, NULL},
    {"seekable",   (PyCFunction)return_true,        METH_NOARGS, NULL},
    {"writable",   (PyCFunction)return_true,        METH_NOARGS, NULL},
    {"close",      (PyCFunction)bytesio_close,      METH_NOARGS, close_doc},
    {"flush",      (PyCFunction)bytesio_flush,      METH_NOARGS, flush_doc},
    {"isatty",     (PyCFunction)bytesio_isatty,     METH_NOARGS, isatty_doc},
    {"tell",       (PyCFunction)bytesio_tell,       METH_NOARGS, tell_doc},
    {"write",      (PyCFunction)bytesio_write,      METH_O, write_doc},
    {"writelines", (PyCFunction)bytesio_writelines, METH_O, writelines_doc},
    {"read1",      (PyCFunction)bytesio_read1,      METH_O, read1_doc},
823
    {"readinto",   (PyCFunction)bytesio_readinto,   METH_VARARGS, readinto_doc},
824 825 826 827 828 829
    {"readline",   (PyCFunction)bytesio_readline,   METH_VARARGS, readline_doc},
    {"readlines",  (PyCFunction)bytesio_readlines,  METH_VARARGS, readlines_doc},
    {"read",       (PyCFunction)bytesio_read,       METH_VARARGS, read_doc},
    {"getvalue",   (PyCFunction)bytesio_getvalue,   METH_VARARGS, getval_doc},
    {"seek",       (PyCFunction)bytesio_seek,       METH_VARARGS, seek_doc},
    {"truncate",   (PyCFunction)bytesio_truncate,   METH_VARARGS, truncate_doc},
830 831
    {"__getstate__",  (PyCFunction)bytesio_getstate,  METH_NOARGS, NULL},
    {"__setstate__",  (PyCFunction)bytesio_setstate,  METH_O, NULL},
832 833 834 835 836 837 838 839 840
    {NULL, NULL}        /* sentinel */
};

PyDoc_STRVAR(bytesio_doc,
"BytesIO([buffer]) -> object\n"
"\n"
"Create a buffered I/O implementation using an in-memory bytes\n"
"buffer, ready for reading and writing.");

841
PyTypeObject PyBytesIO_Type = {
842
    PyVarObject_HEAD_INIT(NULL, 0)
843 844
    "_io.BytesIO",                             /*tp_name*/
    sizeof(bytesio),                     /*tp_basicsize*/
845 846 847 848 849
    0,                                         /*tp_itemsize*/
    (destructor)bytesio_dealloc,               /*tp_dealloc*/
    0,                                         /*tp_print*/
    0,                                         /*tp_getattr*/
    0,                                         /*tp_setattr*/
850
    0,                                         /*tp_reserved*/
851 852 853 854 855 856 857 858 859 860
    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*/
861 862
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
    Py_TPFLAGS_HAVE_GC,                        /*tp_flags*/
863
    bytesio_doc,                               /*tp_doc*/
864 865
    (traverseproc)bytesio_traverse,            /*tp_traverse*/
    (inquiry)bytesio_clear,                    /*tp_clear*/
866
    0,                                         /*tp_richcompare*/
867
    offsetof(bytesio, weakreflist),      /*tp_weaklistoffset*/
868 869 870 871 872 873 874 875 876
    PyObject_SelfIter,                         /*tp_iter*/
    (iternextfunc)bytesio_iternext,            /*tp_iternext*/
    bytesio_methods,                           /*tp_methods*/
    0,                                         /*tp_members*/
    bytesio_getsetlist,                        /*tp_getset*/
    0,                                         /*tp_base*/
    0,                                         /*tp_dict*/
    0,                                         /*tp_descr_get*/
    0,                                         /*tp_descr_set*/
877
    offsetof(bytesio, dict),             /*tp_dictoffset*/
878 879 880 881
    (initproc)bytesio_init,                    /*tp_init*/
    0,                                         /*tp_alloc*/
    bytesio_new,                               /*tp_new*/
};