diff options
author | Matthias Baumgartner <dev@igsor.net> | 2023-02-08 19:51:54 +0100 |
---|---|---|
committer | Matthias Baumgartner <dev@igsor.net> | 2023-02-08 19:51:54 +0100 |
commit | 1365e21ab9f13597d7fdb4feb0825453f32cae4b (patch) | |
tree | 87e1c7ce51ad9aac875dd3d0ff973ed735d88570 | |
parent | 7e0987bcda136a17baea45b8eb22eb5ea668abc0 (diff) | |
download | bsfs-1365e21ab9f13597d7fdb4feb0825453f32cae4b.tar.gz bsfs-1365e21ab9f13597d7fdb4feb0825453f32cae4b.tar.bz2 bsfs-1365e21ab9f13597d7fdb4feb0825453f32cae4b.zip |
ucid from buffer and bytes
-rw-r--r-- | bsfs/utils/uuid.py | 12 | ||||
-rw-r--r-- | test/utils/test_uuid.py | 10 |
2 files changed, 22 insertions, 0 deletions
diff --git a/bsfs/utils/uuid.py b/bsfs/utils/uuid.py index ba5cf52..70e1656 100644 --- a/bsfs/utils/uuid.py +++ b/bsfs/utils/uuid.py @@ -7,6 +7,7 @@ Author: Matthias Baumgartner, 2022 # imports from collections import abc import hashlib +import io import json import os import platform @@ -106,6 +107,17 @@ class UCID(): with open(path, 'rb') as ifile: return HASH(ifile.read()).hexdigest() + @staticmethod + def from_buffer(buffer: io.IOBase) -> str: + """Read the content from a buffer.""" + if isinstance(buffer, io.TextIOBase): + return HASH(buffer.read().encode('utf-8', errors='ignore')).hexdigest() + return HASH(buffer.read()).hexdigest() + + @staticmethod + def from_bytes(content: bytes) -> str: + """Get the content from as bytes.""" + return HASH(content).hexdigest() @staticmethod def from_dict(content: dict) -> str: diff --git a/test/utils/test_uuid.py b/test/utils/test_uuid.py index 0de96ed..804b063 100644 --- a/test/utils/test_uuid.py +++ b/test/utils/test_uuid.py @@ -83,6 +83,16 @@ class TestUCID(unittest.TestCase): def test_from_path(self): self.assertEqual(UCID.from_path(self._path), self._checksum) + def test_from_buffer(self): + with open(self._path, 'rb') as ifile: + self.assertEqual(UCID.from_buffer(ifile), self._checksum) + with open(self._path) as ifile: + self.assertEqual(UCID.from_buffer(ifile), self._checksum) + + def test_from_bytes(self): + with open(self._path, 'rb') as ifile: + self.assertEqual(UCID.from_bytes(ifile.read()), self._checksum) + def test_from_dict(self): self.assertEqual(UCID.from_dict({'hello': 'world', 'foo': 1234, 'bar': False}), '8d2544395a0d2827e3d9ce8cd619d5e3f801e8126bf3f93ee5abd38158959585') |