@@ -1899,6 +1899,8 @@ def test_repeat_after_setslice(self):
18991899 self .assertEqual (b3 , b'xcxcxc' )
19001900
19011901 def test_mutating_index (self ):
1902+ # bytearray slice assignment can call into python code
1903+ # that reallocates the internal buffer
19021904 # See gh-91153
19031905
19041906 class Boom :
@@ -1916,6 +1918,39 @@ def __index__(self):
19161918 with self .assertRaises (IndexError ):
19171919 self ._testlimitedcapi .sequence_setitem (b , 0 , Boom ())
19181920
1921+ def test_mutating_index_inbounds (self ):
1922+ # gh-91153 continued
1923+ # Ensure buffer is not broken even if length is correct
1924+
1925+ class MutatesOnIndex :
1926+ def __init__ (self ):
1927+ self .ba = bytearray (0x180 )
1928+
1929+ def __index__ (self ):
1930+ self .ba .clear ()
1931+ self .new_ba = bytearray (0x180 ) # to catch out-of-bounds writes
1932+ self .ba .extend ([0 ] * 0x180 ) # to check bounds checks
1933+ return 0
1934+
1935+ with self .subTest ("skip_bounds_safety" ):
1936+ instance = MutatesOnIndex ()
1937+ instance .ba [instance ] = ord ("?" )
1938+ self .assertEqual (instance .ba [0 ], ord ("?" ), "Assigned bytearray not altered" )
1939+ self .assertEqual (instance .new_ba , bytearray (0x180 ), "Wrong object altered" )
1940+
1941+ with self .subTest ("skip_bounds_safety_capi" ):
1942+ instance = MutatesOnIndex ()
1943+ instance .ba [instance ] = ord ("?" )
1944+ self ._testlimitedcapi .sequence_setitem (instance .ba , instance , ord ("?" ))
1945+ self .assertEqual (instance .ba [0 ], ord ("?" ), "Assigned bytearray not altered" )
1946+ self .assertEqual (instance .new_ba , bytearray (0x180 ), "Wrong object altered" )
1947+
1948+ with self .subTest ("skip_bounds_safety_slice" ):
1949+ instance = MutatesOnIndex ()
1950+ instance .ba [instance :1 ] = [ord ("?" )]
1951+ self .assertEqual (instance .ba [0 ], ord ("?" ), "Assigned bytearray not altered" )
1952+ self .assertEqual (instance .new_ba , bytearray (0x180 ), "Wrong object altered" )
1953+
19191954
19201955class AssortedBytesTest (unittest .TestCase ):
19211956 #
0 commit comments