Skip to content

Commit ba27fe0

Browse files
committed
Merge branch 'main' into writer_resize2
2 parents 4b4bcfb + fd569ea commit ba27fe0

10 files changed

Lines changed: 96 additions & 38 deletions

File tree

Doc/whatsnew/3.16.rst

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -412,9 +412,9 @@ io
412412
ipaddress
413413
---------
414414

415-
* Add :meth:`~ipaddress.IPv4Network.next_network` and
416-
:meth:`~ipaddress.IPv6Network.next_network` methods to find the next nearest
417-
network with a specific prefix size.
415+
* Add :meth:`IPv4Network.next_network() <ipaddress.IPv4Network.next_network>`
416+
and :meth:`IPv6Network.next_network() <ipaddress.IPv6Network.next_network>`
417+
methods to find the next nearest network with a specific prefix size.
418418
(Contributed by Faisal Mahmood in :gh:`87027`.)
419419

420420

Lib/ipaddress.py

Lines changed: 9 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1124,11 +1124,15 @@ def next_network(self, next_prefix=None):
11241124
11251125
Args:
11261126
next_prefix: The desired next prefix length, if not specified the
1127-
same self.prefixlen will be used
1127+
same self.prefixlen will be used.
11281128
11291129
Returns:
11301130
An IPv(4|6) Network object of the next closest network.
11311131
1132+
Raises:
1133+
ValueError: If next_prefix is outside the range of valid prefix
1134+
lengths, or if no further network of that size exists.
1135+
11321136
"""
11331137
if next_prefix is None:
11341138
next_prefix = self.prefixlen
@@ -1150,15 +1154,13 @@ def next_network(self, next_prefix=None):
11501154
((new_netmask._ip & self.network_address._ip) >> bit_shift) + 1
11511155
) << bit_shift
11521156

1153-
try:
1154-
return self.__class__(
1155-
f"{self._string_from_ip_int(next_ip)}/{next_prefix}"
1156-
)
1157-
except OverflowError:
1157+
if next_ip > self._ALL_ONES:
11581158
raise ValueError(
11591159
f"out of address space, cannot make another /{next_prefix} "
11601160
"network"
1161-
) from None
1161+
)
1162+
1163+
return self.__class__((next_ip, next_prefix))
11621164

11631165

11641166
class _BaseConstants:

Lib/test/test_bytes.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1639,6 +1639,14 @@ def test_take_bytes(self):
16391639
self.assertRaises(BufferError, ba.take_bytes)
16401640
self.assertEqual(ba.take_bytes(), b'abc')
16411641

1642+
# Leaving one byte must not adopt the shared single-byte bytes object
1643+
# as the buffer.
1644+
ba = bytearray(b'abc')
1645+
self.assertEqual(ba.take_bytes(2), b'ab')
1646+
ba[0] = ord('A')
1647+
self.assertEqual(ba, bytearray(b'A'))
1648+
self.assertEqual(ord(b'c'), ord('c'))
1649+
16421650
@support.cpython_only # tests an implementation detail
16431651
def test_take_bytes_optimization(self):
16441652
# Validate optimization around taking lots of little chunks out of a
@@ -3083,5 +3091,18 @@ def resize_stress(ba):
30833091
with threading_helper.start_threads(threads):
30843092
pass
30853093

3094+
@threading_helper.reap_threads
3095+
@threading_helper.requires_working_threading()
3096+
def test_free_threading_bytearray_resize_other_thread(self):
3097+
# Shrinking a bytearray whose buffer another thread owns must not
3098+
# adopt the immortal single-byte bytes object a the buffer.
3099+
ba = bytearray(b'abc')
3100+
thread = threading.Thread(target=ba.resize, args=(1,))
3101+
with threading_helper.start_threads([thread]):
3102+
pass
3103+
ba[0] = ord('X')
3104+
self.assertEqual(ba, bytearray(b'X'))
3105+
self.assertEqual(ord(b'a'), ord('a'))
3106+
30863107
if __name__ == "__main__":
30873108
unittest.main()

Lib/test/test_capi/test_bytes.py

Lines changed: 34 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import sys
12
import unittest
23
from test.support import import_helper
34

@@ -231,26 +232,41 @@ def test_decodeescape(self):
231232

232233
def test_resize(self):
233234
"""Test _PyBytes_Resize()"""
234-
resize = _testcapi.bytes_resize
235+
_resize = _testcapi.bytes_resize
236+
237+
def resize(obj, size, new):
238+
result = _resize(obj, size, new)
239+
if 1 <= len(result):
240+
if new or size != len(obj):
241+
# gh-156995: Make sure that the result is a fresh object.
242+
# Previously, _PyBytes_Resize(&obj, 1) returned a singleton
243+
# if _PyObject_IsUniquelyReferenced() is false.
244+
self.assertEqual(sys.getrefcount(result), 1)
245+
self.assertFalse(sys._is_immortal(result))
246+
else:
247+
# check that the result is the empty bytes string singleton
248+
self.assertTrue(sys._is_immortal(result))
249+
return result
235250

236251
for new in True, False:
237-
self.assertEqual(resize(b'abc', 0, new), b'')
238-
self.assertEqual(resize(b'abc', 1, new), b'a')
239-
self.assertEqual(resize(b'abc', 2, new), b'ab')
240-
self.assertEqual(resize(b'abc', 3, new), b'abc')
241-
b = resize(b'abc', 4, new)
242-
self.assertEqual(len(b), 4)
243-
self.assertEqual(b[:3], b'abc')
244-
245-
self.assertEqual(resize(b'a', 0, new), b'')
246-
self.assertEqual(resize(b'a', 1, new), b'a')
247-
b = resize(b'a', 2, new)
248-
self.assertEqual(len(b), 2)
249-
self.assertEqual(b[:1], b'a')
250-
251-
self.assertEqual(resize(b'', 0, new), b'')
252-
self.assertEqual(len(resize(b'', 1, new)), 1)
253-
self.assertEqual(len(resize(b'', 2, new)), 2)
252+
with self.subTest(new=new):
253+
self.assertEqual(resize(b'abc', 0, new), b'')
254+
self.assertEqual(resize(b'abc', 1, new), b'a')
255+
self.assertEqual(resize(b'abc', 2, new), b'ab')
256+
self.assertEqual(resize(b'abc', 3, new), b'abc')
257+
b = resize(b'abc', 4, new)
258+
self.assertEqual(len(b), 4)
259+
self.assertEqual(b[:3], b'abc')
260+
261+
self.assertEqual(resize(b'a', 0, new), b'')
262+
self.assertEqual(resize(b'a', 1, new), b'a')
263+
b = resize(b'a', 2, new)
264+
self.assertEqual(len(b), 2)
265+
self.assertEqual(b[:1], b'a')
266+
267+
self.assertEqual(resize(b'', 0, new), b'')
268+
self.assertEqual(len(resize(b'', 1, new)), 1)
269+
self.assertEqual(len(resize(b'', 2, new)), 2)
254270

255271
self.assertRaises(SystemError, resize, b'abc', -1, False)
256272
self.assertRaises(SystemError, resize, bytearray(b'abc'), 3, False)

Lib/test/test_ipaddress.py

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1596,9 +1596,15 @@ def testNextNetworkWithBadPrefix(self):
15961596

15971597
def testNextNetworkOutOfAddressSpace(self):
15981598
ipv4 = ipaddress.IPv4Network('255.255.255.0/24')
1599-
self.assertRaises(ValueError, ipv4.next_network)
1599+
self.assertRaisesRegex(
1600+
ValueError,
1601+
'out of address space, cannot make another /24 network',
1602+
ipv4.next_network)
16001603
ipv6 = ipaddress.IPv6Network('ffff:ffff:ffff:ffff:ffff:ffff:ffff:0/112')
1601-
self.assertRaises(ValueError, ipv6.next_network)
1604+
self.assertRaisesRegex(
1605+
ValueError,
1606+
'out of address space, cannot make another /112 network',
1607+
ipv6.next_network)
16021608

16031609
def testFancySubnetting(self):
16041610
self.assertEqual(sorted(self.ipv4_network.subnets(prefixlen_diff=3)),
Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
Fix :class:`bytearray` sharing its buffer with the single-byte :class:`bytes`
2+
object of the same value, so that writing to the bytearray modified that
3+
:class:`bytes` object. This happened with :meth:`bytearray.take_bytes` when
4+
exactly one byte remained, and on the free-threaded build when a bytearray was
5+
shrunk to one byte from another thread.
Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,2 +1,3 @@
1-
Add :meth:`~ipaddress.IPv4Network.next_network` and
2-
:meth:`~ipaddress.IPv6Network.next_network`. Patch by Faisal Mahmood.
1+
Add :meth:`IPv4Network.next_network() <ipaddress.IPv4Network.next_network>`
2+
and :meth:`IPv6Network.next_network() <ipaddress.IPv6Network.next_network>`.
3+
Patch by Faisal Mahmood.

Misc/NEWS.d/next/Library/2026-06-11-06-56-31.gh-issue-150994.gd1wVw.rst

Lines changed: 0 additions & 1 deletion
This file was deleted.

Objects/bytearrayobject.c

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,10 @@ _getbytevalue(PyObject* arg, int *value)
4545

4646
static void
4747
bytearray_reinit_from_bytes(PyByteArrayObject *self, Py_ssize_t size,
48-
Py_ssize_t alloc) {
48+
Py_ssize_t alloc)
49+
{
50+
/* Only the empty bytes may be immortal. */
51+
assert((alloc == 0) == _Py_IsImmortal(self->ob_bytes_object));
4952
self->ob_bytes = self->ob_start = PyBytes_AS_STRING(self->ob_bytes_object);
5053
Py_SET_SIZE(self, size);
5154
FT_ATOMIC_STORE_SSIZE_RELAXED(self->ob_alloc, alloc);
@@ -1618,12 +1621,14 @@ bytearray_take_bytes_impl(PyByteArrayObject *self, PyObject *n)
16181621
return ret;
16191622
}
16201623

1621-
// Copy remaining bytes to a new bytes.
1622-
PyObject *remaining = PyBytes_FromStringAndSize(self->ob_start + to_take,
1623-
remaining_length);
1624+
// Copy remaining bytes to a new bytes. Allocate and then copy
1625+
// so we don't get a shared immortal one-character singleton!
1626+
PyObject *remaining = PyBytes_FromStringAndSize(NULL, remaining_length);
16241627
if (remaining == NULL) {
16251628
return NULL;
16261629
}
1630+
memcpy(PyBytes_AS_STRING(remaining), self->ob_start + to_take,
1631+
remaining_length);
16271632

16281633
// If the bytes are offset inside the buffer must first align.
16291634
if (self->ob_start != self->ob_bytes) {

Objects/bytesobject.c

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3379,12 +3379,15 @@ _PyBytes_ResizeKeepOnError(PyObject **pv, Py_ssize_t newsize)
33793379
}
33803380

33813381
if (!_PyObject_IsUniquelyReferenced(v)) {
3382+
// Allocate and then copy so we don't get a shared immortal
3383+
// one-character singleton!
33823384
result = _PyBytes_FromSize(newsize, 0);
33833385
if (!result) {
33843386
return -1;
33853387
}
33863388

3387-
memcpy(PyBytes_AS_STRING(result), PyBytes_AS_STRING(v), Py_MIN(oldsize, newsize));
3389+
memcpy(PyBytes_AS_STRING(result), PyBytes_AS_STRING(v),
3390+
Py_MIN(oldsize, newsize));
33883391
*pv = result;
33893392
Py_DECREF(v);
33903393
return 0;

0 commit comments

Comments
 (0)