Coverage for python/lsst/daf/butler/registry/nameShrinker.py: 35%
21 statements
« prev ^ index » next coverage.py v7.2.5, created at 2023-05-02 18:18 -0700
« prev ^ index » next coverage.py v7.2.5, created at 2023-05-02 18:18 -0700
1# This file is part of daf_butler.
2#
3# Developed for the LSST Data Management System.
4# This product includes software developed by the LSST Project
5# (http://www.lsst.org).
6# See the COPYRIGHT file at the top-level directory of this distribution
7# for details of code ownership.
8#
9# This program is free software: you can redistribute it and/or modify
10# it under the terms of the GNU General Public License as published by
11# the Free Software Foundation, either version 3 of the License, or
12# (at your option) any later version.
13#
14# This program is distributed in the hope that it will be useful,
15# but WITHOUT ANY WARRANTY; without even the implied warranty of
16# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17# GNU General Public License for more details.
18#
19# You should have received a copy of the GNU General Public License
20# along with this program. If not, see <http://www.gnu.org/licenses/>.
21from __future__ import annotations
23__all__ = ["NameShrinker"]
25import hashlib
26from typing import Dict
29class NameShrinker:
30 """A utility class for `Database` implementations that need a nontrivial
31 implementation of `Database.shrinkDatabaseEntityName` and
32 `Database.expandDatabaseEntityName`.
34 Parameters
35 ----------
36 maxLength : `int`
37 The maximum number of characters in a database entity name.
38 hashSize : `int`, optional
39 The size of the hash (in bytes) to use for the tail of the shortened
40 name. The hash is written in hexadecimal and prefixed with a "_", so
41 the number of characters the hash occupies is ``hashSize*2 + 1``, and
42 hence the number of characters preserved from the beginning of the
43 original name is ``maxLength - hashSize*2 - 1``.
44 """
46 def __init__(self, maxLength: int, hashSize: int = 4):
47 self.maxLength = maxLength
48 self.hashSize = hashSize
49 self._names: Dict[str, str] = {}
51 def shrink(self, original: str) -> str:
52 """Shrink a name and remember the mapping between the original name and
53 its shrunk form.
54 """
55 if len(original) <= self.maxLength:
56 return original
57 message = hashlib.blake2b(digest_size=self.hashSize)
58 message.update(original.encode("ascii"))
59 trunc = self.maxLength - 2 * self.hashSize - 1
60 shrunk = f"{original[:trunc]}_{message.digest().hex()}"
61 assert len(shrunk) == self.maxLength
62 self._names[shrunk] = original
63 return shrunk
65 def expand(self, shrunk: str) -> str:
66 """Return the original name that was passed to a previous call to
67 `shrink`.
69 If the given name was not passed to `shrink` or was not modified by
70 it, it is returned unmodified.
71 """
72 return self._names.get(shrunk, shrunk)