Coverage for faststream/_internal/utils/nuid.py: 88%

36 statements  

« prev     ^ index     » next       coverage.py v7.17.3, created at 2026-11-17 21:20 +0000

1# Copyright 2016-2018 The NATS Authors 

2# Licensed under the Apache License, Version 2.0 (the "License"); 

3# you may not use this file except in compliance with the License. 

4# You may obtain a copy of the License at 

5# 

6# http://www.apache.org/licenses/LICENSE-2.0 

7# 

8# Unless required by applicable law or agreed to in writing, software 

9# distributed under the License is distributed on an "AS IS" BASIS, 

10# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

11# See the License for the specific language governing permissions and 

12# limitations under the License. 

13 

14from __future__ import annotations 

15 

16from random import Random 

17from secrets import randbelow, token_bytes 

18from sys import maxsize as max_int 

19 

20DIGITS = b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" 

21BASE = 62 

22PREFIX_LENGTH = 12 

23SEQ_LENGTH = 10 

24MAX_SEQ = BASE**10 

25MIN_INC = 33 

26MAX_INC = 333 

27INC = MAX_INC - MIN_INC 

28TOTAL_LENGTH = PREFIX_LENGTH + SEQ_LENGTH 

29 

30 

31class NUID: 

32 """NUID created is a utility to create a new id. 

33 

34 NUID is an implementation of the approach for fast generation 

35 of unique identifiers used for inboxes in NATS. 

36 """ 

37 

38 __slots__ = ( 

39 "_inc", 

40 "_prand", 

41 "_prefix", 

42 "_seq", 

43 ) 

44 

45 def __init__(self) -> None: 

46 self._prand = Random(randbelow(max_int)) # nosec B311 # ruff: ignore[suspicious-non-cryptographic-random-usage] 

47 self._seq = self._prand.randint(0, MAX_SEQ) 

48 self._inc = MIN_INC + self._prand.randint(BASE + 1, INC) 

49 self._prefix = bytearray() 

50 self.randomize_prefix() 

51 

52 def next(self) -> bytearray: 

53 """Next returns the next unique identifier.""" 

54 self._seq += self._inc 

55 if self._seq >= MAX_SEQ: 55 ↛ 56line 55 didn't jump to line 56 because the condition on line 55 was never true

56 self.randomize_prefix() 

57 self.reset_sequential() 

58 

59 l_seq = self._seq 

60 prefix = self._prefix[:] 

61 suffix = bytearray(SEQ_LENGTH) 

62 for i in reversed(range(SEQ_LENGTH)): 

63 suffix[i] = DIGITS[int(l_seq) % BASE] 

64 l_seq //= BASE 

65 

66 prefix.extend(suffix) 

67 return prefix 

68 

69 def randomize_prefix(self) -> None: 

70 random_bytes = token_bytes(PREFIX_LENGTH) 

71 self._prefix = bytearray(DIGITS[c % BASE] for c in random_bytes) 

72 

73 def reset_sequential(self) -> None: 

74 self._seq = self._prand.randint(0, MAX_SEQ) 

75 self._inc = MIN_INC + self._prand.randint(0, INC)