Last active
December 6, 2022 07:02
-
-
Save EpicWink/fdcf56091145fd135739c7d9abada704 to your computer and use it in GitHub Desktop.
Python increment function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ctypes | |
_bases = (ctypes.Structure,) | |
PyLongPointer = ctypes.POINTER( | |
type("PyLong", _bases, dict(_fields_=[ | |
("ob_base", type("PyVarObject", _bases, dict(_fields_=[ | |
("ob_base", type("PyObject", _bases, dict(_fields_=[ | |
("ob_refcnt", ctypes.c_ssize_t), | |
("ob_type", ctypes.c_void_p), | |
]))), | |
("ob_size", ctypes.c_ssize_t), | |
]))), | |
("ob_digit", ctypes.c_uint32 * 1000), | |
])), | |
) | |
def inc(x: int) -> None: | |
"""Increment value of x by one. | |
Note: if x is one less than 2 ^ (30 * n) (for n any positive | |
integer), the integer may overflow to 0. | |
Note: uses CPython (<= 3.10) long-integer internals. May not work | |
in other implementations. | |
""" | |
p = ctypes.cast(id(x), PyLongPointer) | |
if p.contents.ob_base.ob_size > 0: | |
amount = 1 | |
overflow = 2 ** 30 | |
reset = 0 | |
else: | |
amount = -1 | |
overflow = 2 ** 32 - 1 | |
reset = 2 ** 30 - 1 | |
p.contents.ob_digit[0] += amount | |
i = 0 | |
while p.contents.ob_digit[i] == overflow: | |
p.contents.ob_digit[i] = reset | |
i += 1 | |
if i < abs(p.contents.ob_base.ob_size): | |
p.contents.ob_digit[i] += amount | |
a = 3 | |
print(a) # 3 | |
inc(a) | |
print(a) # 4 | |
print(3) # 4 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment