]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.10/Modules/_io/bytesio.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 / bytesio.c
diff --git a/AppPkg/Applications/Python/Python-2.7.10/Modules/_io/bytesio.c b/AppPkg/Applications/Python/Python-2.7.10/Modules/_io/bytesio.c
new file mode 100644 (file)
index 0000000..36cfb76
--- /dev/null
@@ -0,0 +1,909 @@
+#include "Python.h"\r
+#include "structmember.h"       /* for offsetof() */\r
+#include "_iomodule.h"\r
+\r
+typedef struct {\r
+    PyObject_HEAD\r
+    char *buf;\r
+    Py_ssize_t pos;\r
+    Py_ssize_t string_size;\r
+    size_t buf_size;\r
+    PyObject *dict;\r
+    PyObject *weakreflist;\r
+} bytesio;\r
+\r
+#define CHECK_CLOSED(self)                                  \\r
+    if ((self)->buf == NULL) {                              \\r
+        PyErr_SetString(PyExc_ValueError,                   \\r
+                        "I/O operation on closed file.");   \\r
+        return NULL;                                        \\r
+    }\r
+\r
+/* Internal routine to get a line from the buffer of a BytesIO\r
+   object. Returns the length between the current position to the\r
+   next newline character. */\r
+static Py_ssize_t\r
+get_line(bytesio *self, char **output)\r
+{\r
+    char *n;\r
+    const char *str_end;\r
+    Py_ssize_t len;\r
+\r
+    assert(self->buf != NULL);\r
+\r
+    /* Move to the end of the line, up to the end of the string, s. */\r
+    str_end = self->buf + self->string_size;\r
+    for (n = self->buf + self->pos;\r
+         n < str_end && *n != '\n';\r
+         n++);\r
+\r
+    /* Skip the newline character */\r
+    if (n < str_end)\r
+        n++;\r
+\r
+    /* Get the length from the current position to the end of the line. */\r
+    len = n - (self->buf + self->pos);\r
+    *output = self->buf + self->pos;\r
+\r
+    assert(len >= 0);\r
+    assert(self->pos < PY_SSIZE_T_MAX - len);\r
+    self->pos += len;\r
+\r
+    return len;\r
+}\r
+\r
+/* Internal routine for changing the size of the buffer of BytesIO objects.\r
+   The caller should ensure that the 'size' argument is non-negative.  Returns\r
+   0 on success, -1 otherwise. */\r
+static int\r
+resize_buffer(bytesio *self, size_t size)\r
+{\r
+    /* Here, unsigned types are used to avoid dealing with signed integer\r
+       overflow, which is undefined in C. */\r
+    size_t alloc = self->buf_size;\r
+    char *new_buf = NULL;\r
+\r
+    assert(self->buf != NULL);\r
+\r
+    /* For simplicity, stay in the range of the signed type. Anyway, Python\r
+       doesn't allow strings to be longer than this. */\r
+    if (size > PY_SSIZE_T_MAX)\r
+        goto overflow;\r
+\r
+    if (size < alloc / 2) {\r
+        /* Major downsize; resize down to exact size. */\r
+        alloc = size + 1;\r
+    }\r
+    else if (size < alloc) {\r
+        /* Within allocated size; quick exit */\r
+        return 0;\r
+    }\r
+    else if (size <= alloc * 1.125) {\r
+        /* Moderate upsize; overallocate similar to list_resize() */\r
+        alloc = size + (size >> 3) + (size < 9 ? 3 : 6);\r
+    }\r
+    else {\r
+        /* Major upsize; resize up to exact size */\r
+        alloc = size + 1;\r
+    }\r
+\r
+    if (alloc > ((size_t)-1) / sizeof(char))\r
+        goto overflow;\r
+    new_buf = (char *)PyMem_Realloc(self->buf, alloc * sizeof(char));\r
+    if (new_buf == NULL) {\r
+        PyErr_NoMemory();\r
+        return -1;\r
+    }\r
+    self->buf_size = alloc;\r
+    self->buf = new_buf;\r
+\r
+    return 0;\r
+\r
+  overflow:\r
+    PyErr_SetString(PyExc_OverflowError,\r
+                    "new buffer size too large");\r
+    return -1;\r
+}\r
+\r
+/* Internal routine for writing a string of bytes to the buffer of a BytesIO\r
+   object. Returns the number of bytes written, or -1 on error. */\r
+static Py_ssize_t\r
+write_bytes(bytesio *self, const char *bytes, Py_ssize_t len)\r
+{\r
+    assert(self->buf != NULL);\r
+    assert(self->pos >= 0);\r
+    assert(len >= 0);\r
+\r
+    if ((size_t)self->pos + len > self->buf_size) {\r
+        if (resize_buffer(self, (size_t)self->pos + len) < 0)\r
+            return -1;\r
+    }\r
+\r
+    if (self->pos > self->string_size) {\r
+        /* In case of overseek, pad with null bytes the buffer region between\r
+           the end of stream and the current position.\r
+\r
+          0   lo      string_size                           hi\r
+          |   |<---used--->|<----------available----------->|\r
+          |   |            <--to pad-->|<---to write--->    |\r
+          0   buf                   position\r
+        */\r
+        memset(self->buf + self->string_size, '\0',\r
+               (self->pos - self->string_size) * sizeof(char));\r
+    }\r
+\r
+    /* Copy the data to the internal buffer, overwriting some of the existing\r
+       data if self->pos < self->string_size. */\r
+    memcpy(self->buf + self->pos, bytes, len);\r
+    self->pos += len;\r
+\r
+    /* Set the new length of the internal string if it has changed. */\r
+    if (self->string_size < self->pos) {\r
+        self->string_size = self->pos;\r
+    }\r
+\r
+    return len;\r
+}\r
+\r
+static PyObject *\r
+bytesio_get_closed(bytesio *self)\r
+{\r
+    if (self->buf == NULL) {\r
+        Py_RETURN_TRUE;\r
+    }\r
+    else {\r
+        Py_RETURN_FALSE;\r
+    }\r
+}\r
+\r
+PyDoc_STRVAR(readable_doc,\r
+"readable() -> bool. Returns True if the IO object can be read.");\r
+\r
+PyDoc_STRVAR(writable_doc,\r
+"writable() -> bool. Returns True if the IO object can be written.");\r
+\r
+PyDoc_STRVAR(seekable_doc,\r
+"seekable() -> bool. Returns True if the IO object can be seeked.");\r
+\r
+/* Generic getter for the writable, readable and seekable properties */\r
+static PyObject *\r
+return_not_closed(bytesio *self)\r
+{\r
+    CHECK_CLOSED(self);\r
+    Py_RETURN_TRUE;\r
+}\r
+\r
+PyDoc_STRVAR(flush_doc,\r
+"flush() -> None.  Does nothing.");\r
+\r
+static PyObject *\r
+bytesio_flush(bytesio *self)\r
+{\r
+    CHECK_CLOSED(self);\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+PyDoc_STRVAR(getval_doc,\r
+"getvalue() -> bytes.\n"\r
+"\n"\r
+"Retrieve the entire contents of the BytesIO object.");\r
+\r
+static PyObject *\r
+bytesio_getvalue(bytesio *self)\r
+{\r
+    CHECK_CLOSED(self);\r
+    return PyBytes_FromStringAndSize(self->buf, self->string_size);\r
+}\r
+\r
+PyDoc_STRVAR(isatty_doc,\r
+"isatty() -> False.\n"\r
+"\n"\r
+"Always returns False since BytesIO objects are not connected\n"\r
+"to a tty-like device.");\r
+\r
+static PyObject *\r
+bytesio_isatty(bytesio *self)\r
+{\r
+    CHECK_CLOSED(self);\r
+    Py_RETURN_FALSE;\r
+}\r
+\r
+PyDoc_STRVAR(tell_doc,\r
+"tell() -> current file position, an integer\n");\r
+\r
+static PyObject *\r
+bytesio_tell(bytesio *self)\r
+{\r
+    CHECK_CLOSED(self);\r
+    return PyLong_FromSsize_t(self->pos);\r
+}\r
+\r
+PyDoc_STRVAR(read_doc,\r
+"read([size]) -> read at most size bytes, returned as a string.\n"\r
+"\n"\r
+"If the size argument is negative, read until EOF is reached.\n"\r
+"Return an empty string at EOF.");\r
+\r
+static PyObject *\r
+bytesio_read(bytesio *self, PyObject *args)\r
+{\r
+    Py_ssize_t size, n;\r
+    char *output;\r
+    PyObject *arg = Py_None;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    if (!PyArg_ParseTuple(args, "|O:read", &arg))\r
+        return NULL;\r
+\r
+    if (PyNumber_Check(arg)) {\r
+        size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);\r
+        if (size == -1 && PyErr_Occurred())\r
+            return NULL;\r
+    }\r
+    else if (arg == Py_None) {\r
+        /* Read until EOF is reached, by default. */\r
+        size = -1;\r
+    }\r
+    else {\r
+        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",\r
+                     Py_TYPE(arg)->tp_name);\r
+        return NULL;\r
+    }\r
+\r
+    /* adjust invalid sizes */\r
+    n = self->string_size - self->pos;\r
+    if (size < 0 || size > n) {\r
+        size = n;\r
+        if (size < 0)\r
+            size = 0;\r
+    }\r
+\r
+    assert(self->buf != NULL);\r
+    output = self->buf + self->pos;\r
+    self->pos += size;\r
+\r
+    return PyBytes_FromStringAndSize(output, size);\r
+}\r
+\r
+\r
+PyDoc_STRVAR(read1_doc,\r
+"read1(size) -> read at most size bytes, returned as a string.\n"\r
+"\n"\r
+"If the size argument is negative or omitted, read until EOF is reached.\n"\r
+"Return an empty string at EOF.");\r
+\r
+static PyObject *\r
+bytesio_read1(bytesio *self, PyObject *n)\r
+{\r
+    PyObject *arg, *res;\r
+\r
+    arg = PyTuple_Pack(1, n);\r
+    if (arg == NULL)\r
+        return NULL;\r
+    res  = bytesio_read(self, arg);\r
+    Py_DECREF(arg);\r
+    return res;\r
+}\r
+\r
+PyDoc_STRVAR(readline_doc,\r
+"readline([size]) -> next line from the file, as a string.\n"\r
+"\n"\r
+"Retain newline.  A non-negative size argument limits the maximum\n"\r
+"number of bytes to return (an incomplete line may be returned then).\n"\r
+"Return an empty string at EOF.\n");\r
+\r
+static PyObject *\r
+bytesio_readline(bytesio *self, PyObject *args)\r
+{\r
+    Py_ssize_t size, n;\r
+    char *output;\r
+    PyObject *arg = Py_None;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    if (!PyArg_ParseTuple(args, "|O:readline", &arg))\r
+        return NULL;\r
+\r
+    if (PyNumber_Check(arg)) {\r
+        size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);\r
+        if (size == -1 && PyErr_Occurred())\r
+            return NULL;\r
+    }\r
+    else if (arg == Py_None) {\r
+        /* No size limit, by default. */\r
+        size = -1;\r
+    }\r
+    else {\r
+        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",\r
+                     Py_TYPE(arg)->tp_name);\r
+        return NULL;\r
+    }\r
+\r
+    n = get_line(self, &output);\r
+\r
+    if (size >= 0 && size < n) {\r
+        size = n - size;\r
+        n -= size;\r
+        self->pos -= size;\r
+    }\r
+\r
+    return PyBytes_FromStringAndSize(output, n);\r
+}\r
+\r
+PyDoc_STRVAR(readlines_doc,\r
+"readlines([size]) -> list of strings, each a line from the file.\n"\r
+"\n"\r
+"Call readline() repeatedly and return a list of the lines so read.\n"\r
+"The optional size argument, if given, is an approximate bound on the\n"\r
+"total number of bytes in the lines returned.\n");\r
+\r
+static PyObject *\r
+bytesio_readlines(bytesio *self, PyObject *args)\r
+{\r
+    Py_ssize_t maxsize, size, n;\r
+    PyObject *result, *line;\r
+    char *output;\r
+    PyObject *arg = Py_None;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    if (!PyArg_ParseTuple(args, "|O:readlines", &arg))\r
+        return NULL;\r
+\r
+    if (PyNumber_Check(arg)) {\r
+        maxsize = PyNumber_AsSsize_t(arg, PyExc_OverflowError);\r
+        if (maxsize == -1 && PyErr_Occurred())\r
+            return NULL;\r
+    }\r
+    else if (arg == Py_None) {\r
+        /* No size limit, by default. */\r
+        maxsize = -1;\r
+    }\r
+    else {\r
+        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",\r
+                     Py_TYPE(arg)->tp_name);\r
+        return NULL;\r
+    }\r
+\r
+    size = 0;\r
+    result = PyList_New(0);\r
+    if (!result)\r
+        return NULL;\r
+\r
+    while ((n = get_line(self, &output)) != 0) {\r
+        line = PyBytes_FromStringAndSize(output, n);\r
+        if (!line)\r
+            goto on_error;\r
+        if (PyList_Append(result, line) == -1) {\r
+            Py_DECREF(line);\r
+            goto on_error;\r
+        }\r
+        Py_DECREF(line);\r
+        size += n;\r
+        if (maxsize > 0 && size >= maxsize)\r
+            break;\r
+    }\r
+    return result;\r
+\r
+  on_error:\r
+    Py_DECREF(result);\r
+    return NULL;\r
+}\r
+\r
+PyDoc_STRVAR(readinto_doc,\r
+"readinto(bytearray) -> int.  Read up to len(b) bytes into b.\n"\r
+"\n"\r
+"Returns number of bytes read (0 for EOF), or None if the object\n"\r
+"is set not to block as has no data to read.");\r
+\r
+static PyObject *\r
+bytesio_readinto(bytesio *self, PyObject *args)\r
+{\r
+    Py_buffer buf;\r
+    Py_ssize_t len, n;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    if (!PyArg_ParseTuple(args, "w*", &buf))\r
+        return NULL;\r
+\r
+    len = buf.len;\r
+    /* adjust invalid sizes */\r
+    n = self->string_size - self->pos;\r
+    if (len > n) {\r
+        len = n;\r
+        if (len < 0)\r
+            len = 0;\r
+    }\r
+\r
+    memcpy(buf.buf, self->buf + self->pos, len);\r
+    assert(self->pos + len < PY_SSIZE_T_MAX);\r
+    assert(len >= 0);\r
+    self->pos += len;\r
+\r
+    PyBuffer_Release(&buf);\r
+    return PyLong_FromSsize_t(len);\r
+}\r
+\r
+PyDoc_STRVAR(truncate_doc,\r
+"truncate([size]) -> int.  Truncate the file to at most size bytes.\n"\r
+"\n"\r
+"Size defaults to the current file position, as returned by tell().\n"\r
+"The current file position is unchanged.  Returns the new size.\n");\r
+\r
+static PyObject *\r
+bytesio_truncate(bytesio *self, PyObject *args)\r
+{\r
+    Py_ssize_t size;\r
+    PyObject *arg = Py_None;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    if (!PyArg_ParseTuple(args, "|O:truncate", &arg))\r
+        return NULL;\r
+\r
+    if (PyNumber_Check(arg)) {\r
+        size = PyNumber_AsSsize_t(arg, PyExc_OverflowError);\r
+        if (size == -1 && PyErr_Occurred())\r
+            return NULL;\r
+    }\r
+    else if (arg == Py_None) {\r
+        /* Truncate to current position if no argument is passed. */\r
+        size = self->pos;\r
+    }\r
+    else {\r
+        PyErr_Format(PyExc_TypeError, "integer argument expected, got '%s'",\r
+                     Py_TYPE(arg)->tp_name);\r
+        return NULL;\r
+    }\r
+\r
+    if (size < 0) {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "negative size value %zd", size);\r
+        return NULL;\r
+    }\r
+\r
+    if (size < self->string_size) {\r
+        self->string_size = size;\r
+        if (resize_buffer(self, size) < 0)\r
+            return NULL;\r
+    }\r
+\r
+    return PyLong_FromSsize_t(size);\r
+}\r
+\r
+static PyObject *\r
+bytesio_iternext(bytesio *self)\r
+{\r
+    char *next;\r
+    Py_ssize_t n;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    n = get_line(self, &next);\r
+\r
+    if (!next || n == 0)\r
+        return NULL;\r
+\r
+    return PyBytes_FromStringAndSize(next, n);\r
+}\r
+\r
+PyDoc_STRVAR(seek_doc,\r
+"seek(pos, whence=0) -> int.  Change stream position.\n"\r
+"\n"\r
+"Seek to byte offset pos relative to position indicated by whence:\n"\r
+"     0  Start of stream (the default).  pos should be >= 0;\n"\r
+"     1  Current position - pos may be negative;\n"\r
+"     2  End of stream - pos usually negative.\n"\r
+"Returns the new absolute position.");\r
+\r
+static PyObject *\r
+bytesio_seek(bytesio *self, PyObject *args)\r
+{\r
+    PyObject *posobj;\r
+    Py_ssize_t pos;\r
+    int mode = 0;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    if (!PyArg_ParseTuple(args, "O|i:seek", &posobj, &mode))\r
+        return NULL;\r
+\r
+    pos = PyNumber_AsSsize_t(posobj, PyExc_OverflowError);\r
+    if (pos == -1 && PyErr_Occurred())\r
+        return NULL;\r
+    \r
+    if (pos < 0 && mode == 0) {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "negative seek value %zd", pos);\r
+        return NULL;\r
+    }\r
+\r
+    /* mode 0: offset relative to beginning of the string.\r
+       mode 1: offset relative to current position.\r
+       mode 2: offset relative the end of the string. */\r
+    if (mode == 1) {\r
+        if (pos > PY_SSIZE_T_MAX - self->pos) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "new position too large");\r
+            return NULL;\r
+        }\r
+        pos += self->pos;\r
+    }\r
+    else if (mode == 2) {\r
+        if (pos > PY_SSIZE_T_MAX - self->string_size) {\r
+            PyErr_SetString(PyExc_OverflowError,\r
+                            "new position too large");\r
+            return NULL;\r
+        }\r
+        pos += self->string_size;\r
+    }\r
+    else if (mode != 0) {\r
+        PyErr_Format(PyExc_ValueError,\r
+                     "invalid whence (%i, should be 0, 1 or 2)", mode);\r
+        return NULL;\r
+    }\r
+\r
+    if (pos < 0)\r
+        pos = 0;\r
+    self->pos = pos;\r
+\r
+    return PyLong_FromSsize_t(self->pos);\r
+}\r
+\r
+PyDoc_STRVAR(write_doc,\r
+"write(bytes) -> int.  Write bytes to file.\n"\r
+"\n"\r
+"Return the number of bytes written.");\r
+\r
+static PyObject *\r
+bytesio_write(bytesio *self, PyObject *obj)\r
+{\r
+    Py_ssize_t n = 0;\r
+    Py_buffer buf;\r
+    PyObject *result = NULL;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    if (PyObject_GetBuffer(obj, &buf, PyBUF_CONTIG_RO) < 0)\r
+        return NULL;\r
+\r
+    if (buf.len != 0)\r
+        n = write_bytes(self, buf.buf, buf.len);\r
+    if (n >= 0)\r
+        result = PyLong_FromSsize_t(n);\r
+\r
+    PyBuffer_Release(&buf);\r
+    return result;\r
+}\r
+\r
+PyDoc_STRVAR(writelines_doc,\r
+"writelines(sequence_of_strings) -> None.  Write strings to the file.\n"\r
+"\n"\r
+"Note that newlines are not added.  The sequence can be any iterable\n"\r
+"object producing strings. This is equivalent to calling write() for\n"\r
+"each string.");\r
+\r
+static PyObject *\r
+bytesio_writelines(bytesio *self, PyObject *v)\r
+{\r
+    PyObject *it, *item;\r
+    PyObject *ret;\r
+\r
+    CHECK_CLOSED(self);\r
+\r
+    it = PyObject_GetIter(v);\r
+    if (it == NULL)\r
+        return NULL;\r
+\r
+    while ((item = PyIter_Next(it)) != NULL) {\r
+        ret = bytesio_write(self, item);\r
+        Py_DECREF(item);\r
+        if (ret == NULL) {\r
+            Py_DECREF(it);\r
+            return NULL;\r
+        }\r
+        Py_DECREF(ret);\r
+    }\r
+    Py_DECREF(it);\r
+\r
+    /* See if PyIter_Next failed */\r
+    if (PyErr_Occurred())\r
+        return NULL;\r
+\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+PyDoc_STRVAR(close_doc,\r
+"close() -> None.  Disable all I/O operations.");\r
+\r
+static PyObject *\r
+bytesio_close(bytesio *self)\r
+{\r
+    if (self->buf != NULL) {\r
+        PyMem_Free(self->buf);\r
+        self->buf = NULL;\r
+    }\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+/* Pickling support.\r
+\r
+   Note that only pickle protocol 2 and onward are supported since we use\r
+   extended __reduce__ API of PEP 307 to make BytesIO instances picklable.\r
+\r
+   Providing support for protocol < 2 would require the __reduce_ex__ method\r
+   which is notably long-winded when defined properly.\r
+\r
+   For BytesIO, the implementation would similar to one coded for\r
+   object.__reduce_ex__, but slightly less general. To be more specific, we\r
+   could call bytesio_getstate directly and avoid checking for the presence of\r
+   a fallback __reduce__ method. However, we would still need a __newobj__\r
+   function to use the efficient instance representation of PEP 307.\r
+ */\r
+\r
+static PyObject *\r
+bytesio_getstate(bytesio *self)\r
+{\r
+    PyObject *initvalue = bytesio_getvalue(self);\r
+    PyObject *dict;\r
+    PyObject *state;\r
+\r
+    if (initvalue == NULL)\r
+        return NULL;\r
+    if (self->dict == NULL) {\r
+        Py_INCREF(Py_None);\r
+        dict = Py_None;\r
+    }\r
+    else {\r
+        dict = PyDict_Copy(self->dict);\r
+        if (dict == NULL)\r
+            return NULL;\r
+    }\r
+\r
+    state = Py_BuildValue("(OnN)", initvalue, self->pos, dict);\r
+    Py_DECREF(initvalue);\r
+    return state;\r
+}\r
+\r
+static PyObject *\r
+bytesio_setstate(bytesio *self, PyObject *state)\r
+{\r
+    PyObject *result;\r
+    PyObject *position_obj;\r
+    PyObject *dict;\r
+    Py_ssize_t pos;\r
+\r
+    assert(state != NULL);\r
+\r
+    /* We allow the state tuple to be longer than 3, because we may need\r
+       someday to extend the object's state without breaking\r
+       backward-compatibility. */\r
+    if (!PyTuple_Check(state) || Py_SIZE(state) < 3) {\r
+        PyErr_Format(PyExc_TypeError,\r
+                     "%.200s.__setstate__ argument should be 3-tuple, got %.200s",\r
+                     Py_TYPE(self)->tp_name, Py_TYPE(state)->tp_name);\r
+        return NULL;\r
+    }\r
+    /* Reset the object to its default state. This is only needed to handle\r
+       the case of repeated calls to __setstate__. */\r
+    self->string_size = 0;\r
+    self->pos = 0;\r
+\r
+    /* Set the value of the internal buffer. If state[0] does not support the\r
+       buffer protocol, bytesio_write will raise the appropriate TypeError. */\r
+    result = bytesio_write(self, PyTuple_GET_ITEM(state, 0));\r
+    if (result == NULL)\r
+        return NULL;\r
+    Py_DECREF(result);\r
+\r
+    /* Set carefully the position value. Alternatively, we could use the seek\r
+       method instead of modifying self->pos directly to better protect the\r
+       object internal state against errneous (or malicious) inputs. */\r
+    position_obj = PyTuple_GET_ITEM(state, 1);\r
+    if (!PyIndex_Check(position_obj)) {\r
+        PyErr_Format(PyExc_TypeError,\r
+                     "second item of state must be an integer, not %.200s",\r
+                     Py_TYPE(position_obj)->tp_name);\r
+        return NULL;\r
+    }\r
+    pos = PyNumber_AsSsize_t(position_obj, PyExc_OverflowError);\r
+    if (pos == -1 && PyErr_Occurred())\r
+        return NULL;\r
+    if (pos < 0) {\r
+        PyErr_SetString(PyExc_ValueError,\r
+                        "position value cannot be negative");\r
+        return NULL;\r
+    }\r
+    self->pos = pos;\r
+\r
+    /* Set the dictionary of the instance variables. */\r
+    dict = PyTuple_GET_ITEM(state, 2);\r
+    if (dict != Py_None) {\r
+        if (!PyDict_Check(dict)) {\r
+            PyErr_Format(PyExc_TypeError,\r
+                         "third item of state should be a dict, got a %.200s",\r
+                         Py_TYPE(dict)->tp_name);\r
+            return NULL;\r
+        }\r
+        if (self->dict) {\r
+            /* Alternatively, we could replace the internal dictionary\r
+               completely. However, it seems more practical to just update it. */\r
+            if (PyDict_Update(self->dict, dict) < 0)\r
+                return NULL;\r
+        }\r
+        else {\r
+            Py_INCREF(dict);\r
+            self->dict = dict;\r
+        }\r
+    }\r
+\r
+    Py_RETURN_NONE;\r
+}\r
+\r
+static void\r
+bytesio_dealloc(bytesio *self)\r
+{\r
+    _PyObject_GC_UNTRACK(self);\r
+    if (self->buf != NULL) {\r
+        PyMem_Free(self->buf);\r
+        self->buf = NULL;\r
+    }\r
+    Py_CLEAR(self->dict);\r
+    if (self->weakreflist != NULL)\r
+        PyObject_ClearWeakRefs((PyObject *) self);\r
+    Py_TYPE(self)->tp_free(self);\r
+}\r
+\r
+static PyObject *\r
+bytesio_new(PyTypeObject *type, PyObject *args, PyObject *kwds)\r
+{\r
+    bytesio *self;\r
+\r
+    assert(type != NULL && type->tp_alloc != NULL);\r
+    self = (bytesio *)type->tp_alloc(type, 0);\r
+    if (self == NULL)\r
+        return NULL;\r
+\r
+    /* tp_alloc initializes all the fields to zero. So we don't have to\r
+       initialize them here. */\r
+\r
+    self->buf = (char *)PyMem_Malloc(0);\r
+    if (self->buf == NULL) {\r
+        Py_DECREF(self);\r
+        return PyErr_NoMemory();\r
+    }\r
+\r
+    return (PyObject *)self;\r
+}\r
+\r
+static int\r
+bytesio_init(bytesio *self, PyObject *args, PyObject *kwds)\r
+{\r
+    char *kwlist[] = {"initial_bytes", NULL};\r
+    PyObject *initvalue = NULL;\r
+\r
+    if (!PyArg_ParseTupleAndKeywords(args, kwds, "|O:BytesIO", kwlist,\r
+                                     &initvalue))\r
+        return -1;\r
+\r
+    /* In case, __init__ is called multiple times. */\r
+    self->string_size = 0;\r
+    self->pos = 0;\r
+\r
+    if (initvalue && initvalue != Py_None) {\r
+        PyObject *res;\r
+        res = bytesio_write(self, initvalue);\r
+        if (res == NULL)\r
+            return -1;\r
+        Py_DECREF(res);\r
+        self->pos = 0;\r
+    }\r
+\r
+    return 0;\r
+}\r
+\r
+static PyObject *\r
+bytesio_sizeof(bytesio *self, void *unused)\r
+{\r
+    Py_ssize_t res;\r
+\r
+    res = sizeof(bytesio);\r
+    if (self->buf)\r
+        res += self->buf_size;\r
+    return PyLong_FromSsize_t(res);\r
+}\r
+\r
+static int\r
+bytesio_traverse(bytesio *self, visitproc visit, void *arg)\r
+{\r
+    Py_VISIT(self->dict);\r
+    return 0;\r
+}\r
+\r
+static int\r
+bytesio_clear(bytesio *self)\r
+{\r
+    Py_CLEAR(self->dict);\r
+    return 0;\r
+}\r
+\r
+\r
+static PyGetSetDef bytesio_getsetlist[] = {\r
+    {"closed",  (getter)bytesio_get_closed, NULL,\r
+     "True if the file is closed."},\r
+    {NULL},            /* sentinel */\r
+};\r
+\r
+static struct PyMethodDef bytesio_methods[] = {\r
+    {"readable",   (PyCFunction)return_not_closed,  METH_NOARGS, readable_doc},\r
+    {"seekable",   (PyCFunction)return_not_closed,  METH_NOARGS, seekable_doc},\r
+    {"writable",   (PyCFunction)return_not_closed,  METH_NOARGS, writable_doc},\r
+    {"close",      (PyCFunction)bytesio_close,      METH_NOARGS, close_doc},\r
+    {"flush",      (PyCFunction)bytesio_flush,      METH_NOARGS, flush_doc},\r
+    {"isatty",     (PyCFunction)bytesio_isatty,     METH_NOARGS, isatty_doc},\r
+    {"tell",       (PyCFunction)bytesio_tell,       METH_NOARGS, tell_doc},\r
+    {"write",      (PyCFunction)bytesio_write,      METH_O, write_doc},\r
+    {"writelines", (PyCFunction)bytesio_writelines, METH_O, writelines_doc},\r
+    {"read1",      (PyCFunction)bytesio_read1,      METH_O, read1_doc},\r
+    {"readinto",   (PyCFunction)bytesio_readinto,   METH_VARARGS, readinto_doc},\r
+    {"readline",   (PyCFunction)bytesio_readline,   METH_VARARGS, readline_doc},\r
+    {"readlines",  (PyCFunction)bytesio_readlines,  METH_VARARGS, readlines_doc},\r
+    {"read",       (PyCFunction)bytesio_read,       METH_VARARGS, read_doc},\r
+    {"getvalue",   (PyCFunction)bytesio_getvalue,   METH_NOARGS,  getval_doc},\r
+    {"seek",       (PyCFunction)bytesio_seek,       METH_VARARGS, seek_doc},\r
+    {"truncate",   (PyCFunction)bytesio_truncate,   METH_VARARGS, truncate_doc},\r
+    {"__getstate__",  (PyCFunction)bytesio_getstate,  METH_NOARGS, NULL},\r
+    {"__setstate__",  (PyCFunction)bytesio_setstate,  METH_O, NULL},\r
+    {"__sizeof__", (PyCFunction)bytesio_sizeof,     METH_NOARGS, NULL},\r
+    {NULL, NULL}        /* sentinel */\r
+};\r
+\r
+PyDoc_STRVAR(bytesio_doc,\r
+"BytesIO([buffer]) -> object\n"\r
+"\n"\r
+"Create a buffered I/O implementation using an in-memory bytes\n"\r
+"buffer, ready for reading and writing.");\r
+\r
+PyTypeObject PyBytesIO_Type = {\r
+    PyVarObject_HEAD_INIT(NULL, 0)\r
+    "_io.BytesIO",                             /*tp_name*/\r
+    sizeof(bytesio),                     /*tp_basicsize*/\r
+    0,                                         /*tp_itemsize*/\r
+    (destructor)bytesio_dealloc,               /*tp_dealloc*/\r
+    0,                                         /*tp_print*/\r
+    0,                                         /*tp_getattr*/\r
+    0,                                         /*tp_setattr*/\r
+    0,                                         /*tp_reserved*/\r
+    0,                                         /*tp_repr*/\r
+    0,                                         /*tp_as_number*/\r
+    0,                                         /*tp_as_sequence*/\r
+    0,                                         /*tp_as_mapping*/\r
+    0,                                         /*tp_hash*/\r
+    0,                                         /*tp_call*/\r
+    0,                                         /*tp_str*/\r
+    0,                                         /*tp_getattro*/\r
+    0,                                         /*tp_setattro*/\r
+    0,                                         /*tp_as_buffer*/\r
+    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |\r
+    Py_TPFLAGS_HAVE_GC,                        /*tp_flags*/\r
+    bytesio_doc,                               /*tp_doc*/\r
+    (traverseproc)bytesio_traverse,            /*tp_traverse*/\r
+    (inquiry)bytesio_clear,                    /*tp_clear*/\r
+    0,                                         /*tp_richcompare*/\r
+    offsetof(bytesio, weakreflist),      /*tp_weaklistoffset*/\r
+    PyObject_SelfIter,                         /*tp_iter*/\r
+    (iternextfunc)bytesio_iternext,            /*tp_iternext*/\r
+    bytesio_methods,                           /*tp_methods*/\r
+    0,                                         /*tp_members*/\r
+    bytesio_getsetlist,                        /*tp_getset*/\r
+    0,                                         /*tp_base*/\r
+    0,                                         /*tp_dict*/\r
+    0,                                         /*tp_descr_get*/\r
+    0,                                         /*tp_descr_set*/\r
+    offsetof(bytesio, dict),             /*tp_dictoffset*/\r
+    (initproc)bytesio_init,                    /*tp_init*/\r
+    0,                                         /*tp_alloc*/\r
+    bytesio_new,                               /*tp_new*/\r
+};\r