from__future__importannotationsimporthashlibfrompathlibimportPathfromtypingimport(ByteString,Iterable,)def_chunk_as_bytes(chunk:int|ByteString)->ByteString:""" In some scenarios python converts single bytes to integers: >>> chunks = [type(chunk) for chunk in b"abc"] >>> chunks ... [<class 'int'>, <class 'int'>, <class 'int'>] in order to cope with this transparently this wrapper can be used. """ifnotisinstance(chunk,Iterable):chunk=bytes([chunk])returnchunkdef_bytes(chunks:Iterable[ByteString])->ByteString:chunks=(_chunk_as_bytes(c)forcinchunks)data=bytearray()forchunkinchunks:data.extend(chunk)returndata
[docs]defas_bytes(chunks:Iterable[ByteString])->ByteString:""" Transforms a set of byte chunks into a bytes like object. Args: chunks: which shall be concatenated. Return: A single continues byte like object. """return_bytes(chunks)
[docs]defas_string(chunks:Iterable[ByteString],encoding:str="utf-8")->str:""" Transforms a set of byte chunks into a string. Args: chunks: which shall be converted into a single string. encoding: which shall be used to convert the bytes to a string. Return: A string representation of the converted bytes. """return_bytes(chunks).decode(encoding)
[docs]defas_file(chunks:Iterable[ByteString],filename:str|Path)->Path:""" Transforms a set of byte chunks into a string. Args: chunks: which shall be written to file. filename: for the file which is to be created. Return: A path to the created file. """chunks=(_chunk_as_bytes(c)forcinchunks)filename=Path(filename)withopen(filename,"wb")asf:forchunkinchunks:f.write(chunk)returnfilename
[docs]defas_hash(chunks:Iterable[ByteString],algorithm:str="sha1")->ByteString:""" Calculate the hash for a set of byte chunks. Args: chunks: which shall be used as input for the checksum. algorithm: which shall be used for calculating the checksum. Return: A string representing the hex digest. """try:hasher=hashlib.new(algorithm)exceptValueErrorasex:raiseBucketFsError("Algorithm ({algorithm}) is not available, please use [{algorithms}]".format(algorithm=algorithm,algorithms=",".join(hashlib.algorithms_available)))fromexchunks=(_chunk_as_bytes(c)forcinchunks)forchunkinchunks:hasher.update(chunk)returnhasher.digest()