https://github.com/python/cpython/commit/0bfee223909adc113ece862cb8d7d807c35e201c
commit: 0bfee223909adc113ece862cb8d7d807c35e201c
branch: main
author: Cody Maloney <[email protected]>
committer: StanFromIreland <[email protected]>
date: 2026-10-29T13:52:42Z
summary:

gh-160781: Fix `StringIO.truncate()` rejecting sizes above `2**31 - 1` on 
Windows (#160784)

files:
A Misc/NEWS.d/next/Library/2026-10-27-15-27-32.gh-issue-160781.kARuHu.rst
M Lib/test/test_io/test_memoryio.py
M Modules/_io/stringio.c

diff --git a/Lib/test/test_io/test_memoryio.py 
b/Lib/test/test_io/test_memoryio.py
index 6a286e5a62ef44c..349c7281230eeba 100644
--- a/Lib/test/test_io/test_memoryio.py
+++ b/Lib/test/test_io/test_memoryio.py
@@ -1150,6 +1150,12 @@ def __index__(self):
         with self.assertRaises(ValueError):
             stream.truncate(Size())
 
+        # Sizes above 2**31 - 1 must work where C long is 32-bit.
+        if sys.maxsize > 2**31:
+            stream = self.ioclass("abc")
+            self.assertEqual(stream.truncate(2**31), 2**31)
+            self.assertEqual(stream.getvalue(), "abc")
+
     # XXX: For the Python version of io.StringIO, this is highly
     # dependent on the encoding used for the underlying buffer.
     def test_widechar(self):
diff --git 
a/Misc/NEWS.d/next/Library/2026-10-27-15-27-32.gh-issue-160781.kARuHu.rst 
b/Misc/NEWS.d/next/Library/2026-10-27-15-27-32.gh-issue-160781.kARuHu.rst
new file mode 100644
index 000000000000000..1f1e25d8b461b4e
--- /dev/null
+++ b/Misc/NEWS.d/next/Library/2026-10-27-15-27-32.gh-issue-160781.kARuHu.rst
@@ -0,0 +1,2 @@
+Fix :class:`io.StringIO` implementation of :meth:`io.IOBase.truncate`
+rejecting sizes larger than ``2**31 - 1`` on Windows.
diff --git a/Modules/_io/stringio.c b/Modules/_io/stringio.c
index 558fd57aa93c954..7800a4fcfca4dd8 100644
--- a/Modules/_io/stringio.c
+++ b/Modules/_io/stringio.c
@@ -490,7 +490,7 @@ _io_StringIO_truncate_impl(stringio *self, PyObject *pos)
         size = self->pos;
     }
     else {
-        size = PyLong_AsLong(pos);
+        size = PyNumber_AsSsize_t(pos, PyExc_OverflowError);
         if (size == -1 && PyErr_Occurred()) {
             return NULL;
         }

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to