Shorten VDU names
[osm/SO.git] / common / python / rift / mano / utils / short_name.py
1 #!/usr/bin/python
2
3 #
4 # Copyright 2017 RIFT.IO Inc
5 #
6 # Licensed under the Apache License, Version 2.0 (the "License");
7 # you may not use this file except in compliance with the License.
8 # You may obtain a copy of the License at
9 #
10 # http://www.apache.org/licenses/LICENSE-2.0
11 #
12 # Unless required by applicable law or agreed to in writing, software
13 # distributed under the License is distributed on an "AS IS" BASIS,
14 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 # See the License for the specific language governing permissions and
16 # limitations under the License.
17 #
18 # Author: Aniruddha Atale
19
20 import hashlib
21 import basehash
22
23
24 class StringShortner(object):
25 FOLDS = 3
26 STRING_LEN=9
27 def __init__(self, string = None):
28 self._string = string
29
30 @property
31 def string(self):
32 return self._string
33
34 @string.setter
35 def string(self, string):
36 self._string = string
37
38 @property
39 def short_string(self):
40 if self._string:
41 return StringShortner._get_short_string(self._string)
42 else:
43 return str()
44
45 @staticmethod
46 def _fold_hex_series(series):
47 length = len(series)
48 result = list()
49 for i in range(int(length/2)):
50 result.append(series[i] ^ series[(length - 1) - i])
51
52 if length % 2:
53 result.append(series[int(length/2) + 1])
54
55 return result
56
57 @staticmethod
58 def _num_from_hex_series(series):
59 result = 0
60 for i in range(len(series)):
61 result = result * 256
62 result += series[i]
63 return result
64
65 @staticmethod
66 def _get_short_string(string):
67 sha = hashlib.sha384(string.encode())
68 digest = sha.digest()
69 for i in range(StringShortner.FOLDS):
70 digest = StringShortner._fold_hex_series(digest)
71
72 number = StringShortner._num_from_hex_series(digest)
73 base62 = basehash.base62(length=StringShortner.STRING_LEN)
74 return base62.hash(number)