|
23 | 23 | import io |
24 | 24 | from .lib import dynamically_load_library |
25 | 25 | import mimetypes |
| 26 | +from itertools import count |
26 | 27 |
|
27 | 28 | # Create a module-specific logger |
28 | 29 | logger = logging.getLogger("c2pa") |
@@ -926,16 +927,11 @@ def sign_file( |
926 | 927 |
|
927 | 928 |
|
928 | 929 | class Stream: |
929 | | - # Class-level counter for generating unique stream IDs |
| 930 | + # Class-level atomic counter for generating unique stream IDs |
930 | 931 | # (useful for tracing streams usage in debug) |
931 | | - _next_stream_id = 0 |
| 932 | + _stream_id_counter = count(start=0, step=1) |
| 933 | + |
932 | 934 | # Maximum value for a 32-bit signed integer (2^31 - 1) |
933 | | - # This prevents integer overflow which could cause: |
934 | | - # 1. Unexpected behavior in stream ID generation |
935 | | - # 2. Potential security issues if IDs wrap around |
936 | | - # 3. Memory issues if the number grows too large |
937 | | - # When this limit is reached, we reset to 0 since the timestamp component |
938 | | - # of the stream ID ensures uniqueness even after counter reset |
939 | 935 | _MAX_STREAM_ID = 2**31 - 1 |
940 | 936 |
|
941 | 937 | # Class-level error messages to avoid multiple creation |
@@ -972,11 +968,17 @@ def __init__(self, file_like_stream): |
972 | 968 | self._initialized = False |
973 | 969 | self._stream = None |
974 | 970 |
|
975 | | - # Generate unique stream ID using object ID and counter |
976 | | - if Stream._next_stream_id >= Stream._MAX_STREAM_ID: # pragma: no cover |
977 | | - Stream._next_stream_id = 0 |
978 | | - self._stream_id = f"{id(self)}-{Stream._next_stream_id}" |
979 | | - Stream._next_stream_id += 1 |
| 971 | + # Generate unique stream ID using object ID and atomic counter |
| 972 | + # Get next atomic counter value |
| 973 | + stream_counter = next(Stream._stream_id_counter) |
| 974 | + |
| 975 | + # Handle counter overflow by resetting the counter |
| 976 | + if stream_counter >= Stream._MAX_STREAM_ID: # pragma: no cover |
| 977 | + # Reset the counter to 0 and get the next value |
| 978 | + Stream._stream_id_counter = count(start=0, step=1) |
| 979 | + stream_counter = next(Stream._stream_id_counter) |
| 980 | + |
| 981 | + self._stream_id = f"{id(self)}-{stream_counter}" |
980 | 982 |
|
981 | 983 | # Rest of the existing initialization code... |
982 | 984 | required_methods = ['read', 'write', 'seek', 'tell', 'flush'] |
|
0 commit comments