# Copyright 2016-2018 The NATS Authors# Licensed under the Apache License, Version 2.0 (the "License");# you may not use this file except in compliance with the License.# You may obtain a copy of the License at## http://www.apache.org/licenses/LICENSE-2.0## Unless required by applicable law or agreed to in writing, software# distributed under the License is distributed on an "AS IS" BASIS,# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.# See the License for the specific language governing permissions and# limitations under the License.#from__future__importannotationsfromrandomimportRandomfromsecretsimportrandbelow,token_bytesfromsysimportmaxsizeasMaxIntDIGITS=b"0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"BASE=62PREFIX_LENGTH=12SEQ_LENGTH=10MAX_SEQ=839299365868340224# BASE**10MIN_INC=33MAX_INC=333INC=MAX_INC-MIN_INCTOTAL_LENGTH=PREFIX_LENGTH+SEQ_LENGTH
[docs]classNUID:""" NUID is an implementation of the approach for fast generation of unique identifiers used for inboxes in NATS. """def__init__(self)->None:self._prand=Random(randbelow(MaxInt))self._seq=self._prand.randint(0,MAX_SEQ)self._inc=MIN_INC+self._prand.randint(BASE+1,INC)self._prefix=bytearray()self.randomize_prefix()
[docs]defnext(self)->bytearray:""" next returns the next unique identifier. """self._seq+=self._incifself._seq>=MAX_SEQ:self.randomize_prefix()self.reset_sequential()l=self._seqprefix=self._prefix[:]suffix=bytearray(SEQ_LENGTH)foriinreversed(range(SEQ_LENGTH)):suffix[i]=DIGITS[int(l)%BASE]l//=BASEprefix.extend(suffix)returnprefix