@@ -1827,6 +1827,8 @@ def test_repeat_after_setslice(self):
18271827 self .assertEqual (b3 , b'xcxcxc' )
18281828
18291829 def test_mutating_index (self ):
1830+ # bytearray slice assignment can call into python code
1831+ # that reallocates the internal buffer
18301832 # See gh-91153
18311833
18321834 class Boom :
@@ -1844,6 +1846,39 @@ def __index__(self):
18441846 with self .assertRaises (IndexError ):
18451847 self ._testlimitedcapi .sequence_setitem (b , 0 , Boom ())
18461848
1849+ def test_mutating_index_inbounds (self ):
1850+ # gh-91153 continued
1851+ # Ensure buffer is not broken even if length is correct
1852+
1853+ class MutatesOnIndex :
1854+ def __init__ (self ):
1855+ self .ba = bytearray (0x180 )
1856+
1857+ def __index__ (self ):
1858+ self .ba .clear ()
1859+ self .new_ba = bytearray (0x180 ) # to catch out-of-bounds writes
1860+ self .ba .extend ([0 ] * 0x180 ) # to check bounds checks
1861+ return 0
1862+
1863+ with self .subTest ("skip_bounds_safety" ):
1864+ instance = MutatesOnIndex ()
1865+ instance .ba [instance ] = ord ("?" )
1866+ self .assertEqual (instance .ba [0 ], ord ("?" ), "Assigned bytearray not altered" )
1867+ self .assertEqual (instance .new_ba , bytearray (0x180 ), "Wrong object altered" )
1868+
1869+ with self .subTest ("skip_bounds_safety_capi" ):
1870+ instance = MutatesOnIndex ()
1871+ instance .ba [instance ] = ord ("?" )
1872+ self ._testlimitedcapi .sequence_setitem (instance .ba , instance , ord ("?" ))
1873+ self .assertEqual (instance .ba [0 ], ord ("?" ), "Assigned bytearray not altered" )
1874+ self .assertEqual (instance .new_ba , bytearray (0x180 ), "Wrong object altered" )
1875+
1876+ with self .subTest ("skip_bounds_safety_slice" ):
1877+ instance = MutatesOnIndex ()
1878+ instance .ba [instance :1 ] = [ord ("?" )]
1879+ self .assertEqual (instance .ba [0 ], ord ("?" ), "Assigned bytearray not altered" )
1880+ self .assertEqual (instance .new_ba , bytearray (0x180 ), "Wrong object altered" )
1881+
18471882
18481883class AssortedBytesTest (unittest .TestCase ):
18491884 #
0 commit comments