Skip to content

Commit 36ac9a8

Browse files
committed
fix: Stream Id
1 parent 1d4ee35 commit 36ac9a8

File tree

1 file changed

+15
-13
lines changed

1 file changed

+15
-13
lines changed

src/c2pa/c2pa.py

Lines changed: 15 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@
2323
import io
2424
from .lib import dynamically_load_library
2525
import mimetypes
26+
from itertools import count
2627

2728
# Create a module-specific logger
2829
logger = logging.getLogger("c2pa")
@@ -926,16 +927,11 @@ def sign_file(
926927

927928

928929
class Stream:
929-
# Class-level counter for generating unique stream IDs
930+
# Class-level atomic counter for generating unique stream IDs
930931
# (useful for tracing streams usage in debug)
931-
_next_stream_id = 0
932+
_stream_id_counter = count(start=0, step=1)
933+
932934
# 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
939935
_MAX_STREAM_ID = 2**31 - 1
940936

941937
# Class-level error messages to avoid multiple creation
@@ -972,11 +968,17 @@ def __init__(self, file_like_stream):
972968
self._initialized = False
973969
self._stream = None
974970

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}"
980982

981983
# Rest of the existing initialization code...
982984
required_methods = ['read', 'write', 'seek', 'tell', 'flush']

0 commit comments

Comments
 (0)