(self)
| 353 | self.assertEqual(buffer.count(0), len(buffer) - 1) |
| 354 | |
| 355 | def test_long_asnativebytes(self): |
| 356 | import math |
| 357 | from _testcapi import ( |
| 358 | pylong_asnativebytes as asnativebytes, |
| 359 | SIZE_MAX, |
| 360 | ) |
| 361 | |
| 362 | # Abbreviate sizeof(Py_ssize_t) to SZ because we use it a lot |
| 363 | SZ = int(math.ceil(math.log(SIZE_MAX + 1) / math.log(2)) / 8) |
| 364 | MAX_SSIZE = 2 ** (SZ * 8 - 1) - 1 |
| 365 | MAX_USIZE = 2 ** (SZ * 8) - 1 |
| 366 | if support.verbose: |
| 367 | print(f"SIZEOF_SIZE={SZ}\n{MAX_SSIZE=:016X}\n{MAX_USIZE=:016X}") |
| 368 | |
| 369 | # These tests check that the requested buffer size is correct. |
| 370 | # This matches our current implementation: We only specify that the |
| 371 | # return value is a size *sufficient* to hold the result when queried |
| 372 | # using n_bytes=0. If our implementation changes, feel free to update |
| 373 | # the expectations here -- or loosen them to be range checks. |
| 374 | # (i.e. 0 *could* be stored in 1 byte and 512 in 2) |
| 375 | for v, expect in [ |
| 376 | (0, SZ), |
| 377 | (512, SZ), |
| 378 | (-512, SZ), |
| 379 | (MAX_SSIZE, SZ), |
| 380 | (MAX_USIZE, SZ + 1), |
| 381 | (-MAX_SSIZE, SZ), |
| 382 | (-MAX_USIZE, SZ + 1), |
| 383 | (2**255-1, 32), |
| 384 | (-(2**255-1), 32), |
| 385 | (2**255, 33), |
| 386 | (-(2**255), 33), # if you ask, we'll say 33, but 32 would do |
| 387 | (2**256-1, 33), |
| 388 | (-(2**256-1), 33), |
| 389 | (2**256, 33), |
| 390 | (-(2**256), 33), |
| 391 | ]: |
| 392 | with self.subTest(f"sizeof-{v:X}"): |
| 393 | buffer = bytearray(b"\x5a") |
| 394 | self.assertEqual(expect, asnativebytes(v, buffer, 0, -1), |
| 395 | "PyLong_AsNativeBytes(v, <unknown>, 0, -1)") |
| 396 | self.assertEqual(buffer, b"\x5a", |
| 397 | "buffer overwritten when it should not have been") |
| 398 | # Also check via the __index__ path. |
| 399 | # We pass Py_ASNATIVEBYTES_NATIVE_ENDIAN | ALLOW_INDEX |
| 400 | self.assertEqual(expect, asnativebytes(Index(v), buffer, 0, 3 | 16), |
| 401 | "PyLong_AsNativeBytes(Index(v), <unknown>, 0, -1)") |
| 402 | self.assertEqual(buffer, b"\x5a", |
| 403 | "buffer overwritten when it should not have been") |
| 404 | |
| 405 | # Test that we populate n=2 bytes but do not overwrite more. |
| 406 | buffer = bytearray(b"\x99"*3) |
| 407 | self.assertEqual(2, asnativebytes(4, buffer, 2, 0), # BE |
| 408 | "PyLong_AsNativeBytes(v, <3 byte buffer>, 2, 0) // BE") |
| 409 | self.assertEqual(buffer, b"\x00\x04\x99") |
| 410 | self.assertEqual(2, asnativebytes(4, buffer, 2, 1), # LE |
| 411 | "PyLong_AsNativeBytes(v, <3 byte buffer>, 2, 1) // LE") |
| 412 | self.assertEqual(buffer, b"\x04\x00\x99") |
nothing calls this directly
no test coverage detected