commit ad22db488923dc8cbefd5c678ad0b1688aa1c93e
parent e9b2bfc5f4aab2b00c9c53e728127319caf0695e
Author: lash <dev@holbrook.no>
Date: Tue, 29 Aug 2023 13:16:57 +0100
Add uuid hex wrapper
Diffstat:
3 files changed, 92 insertions(+), 1 deletion(-)
diff --git a/leveldir/hex.py b/leveldir/hex.py
@@ -96,7 +96,6 @@ class HexDir(LevelDir):
def get(self, idx):
cursor = self.__cursor(idx)
- print('cursor {}'.format(cursor))
f = open(self.master_file, 'rb')
f.seek(cursor)
prefix = f.read(self.prefix_length)
diff --git a/leveldir/uuid.py b/leveldir/uuid.py
@@ -0,0 +1,44 @@
+# standard imports
+import uuid
+
+# local imports
+from .hex import HexDir
+from .hex import default_formatter
+
+
+class UUIDDir(HexDir):
+
+ def __init__(self, root_path, levels=2, prefix_length=0, formatter=default_formatter):
+ super(UUIDDir, self).__init__(root_path, 16, prefix_length=prefix_length, levels=levels, formatter=formatter)
+
+
+ # TODO: refactor __check in parent to reduce required computation
+ def __convert(self, key, as_hex=False):
+ u = key
+ if type(key) == str:
+ u = uuid.UUID(key)
+ elif type(key) == bytes:
+ u = uuid.UUID(bytes=key)
+ if as_hex:
+ return u.hex
+ return u.bytes
+
+
+ def add(self, key, content, prefix=b''):
+ key = self.__convert(key, as_hex=False)
+ return super(UUIDDir, self).add(key, content, prefix=prefix)
+
+
+ def key_to_string(self, k):
+ return self.__convert(k, as_hex=True)
+
+
+ def add_dir(self, key, content, prefix=b''):
+ key = self.__convert(key, as_hex=False)
+ return super(UUIDDir, self).add_dir(key, content, prefix=prefix)
+
+
+ def have(self, key):
+ key = self.__convert(key, as_hex=True)
+ return super(UUIDDir, self).have(key)
+
diff --git a/tests/test_uuiddir.py b/tests/test_uuiddir.py
@@ -0,0 +1,48 @@
+# standard imports
+import uuid
+import unittest
+import tempfile
+import shutil
+import logging
+import os
+
+# local imports
+from leveldir.uuid import UUIDDir
+
+logging.basicConfig(level=logging.DEBUG)
+logg = logging.getLogger()
+
+
+class HexDirTest(unittest.TestCase):
+
+ def setUp(self):
+ self.dir = tempfile.mkdtemp()
+ self.uuiddir = UUIDDir(os.path.join(self.dir, 'q'), 3, 2)
+ logg.debug('setup uuiddir root {}'.format(self.dir))
+
+
+ def tearDown(self):
+ shutil.rmtree(self.dir)
+ logg.debug('cleaned hexdir root {}'.format(self.dir))
+
+
+ def test_add_types(self):
+ content = b'cdef'
+ prefix = b'ab'
+ label = uuid.uuid4()
+ (c, entry_path) = self.uuiddir.add(label, content, prefix=prefix)
+
+ label = uuid.uuid4()
+ label = label.hex
+ (c, entry_path) = self.uuiddir.add(label, content, prefix=prefix)
+
+ label = uuid.uuid4()
+ label = label.bytes
+ (c, entry_path) = self.uuiddir.add(label, content, prefix=prefix)
+
+ self.assertTrue(self.uuiddir.have(label))
+
+
+
+if __name__ == '__main__':
+ unittest.main()