|
11 | 11 |
|
12 | 12 |
|
13 | 13 | __all__ = __features__ = ["dateparse", "human_readable_size", "is_admin", "set_exception", "strings", |
14 | | - "strings_from_file", "urlparse", "urlparse_query", "xor", "xor_file", "withrepr"] |
| 14 | + "strings_from_file", "urlparse", "urlparse_query", "xor", "xor_file", "withrepr", "zeropad"] |
15 | 15 |
|
16 | 16 |
|
17 | 17 | def human_readable_size(size, precision=0): |
@@ -181,6 +181,42 @@ def xor_file(filename, key, offset=0): |
181 | 181 | cursor += l |
182 | 182 |
|
183 | 183 |
|
| 184 | +def zeropad(length, default="\x00"): |
| 185 | + """ Simple decorator to zero-pad the result of the input function regarding its output type. |
| 186 | + |
| 187 | + :param length: desired length |
| 188 | + |
| 189 | + Examples: |
| 190 | + zeropad(5)("ok") => "ok\x00\x00\x00" |
| 191 | + zeropad(5)("011") => "01100" |
| 192 | + zeropad(5)([0,1,1]) => [0,1,1,0,0] |
| 193 | + zeropad(5)(["0","1","1"]) => ["0","1","1","0","0"] |
| 194 | + |
| 195 | + @zeropad(5) |
| 196 | + def test(...): |
| 197 | + ... # e.g. return "ok" => "ok\x00\x00\x00" |
| 198 | + """ |
| 199 | + from tinyscript.helpers import is_bin, is_function, is_list |
| 200 | + def _pad(v): |
| 201 | + l = len(v) |
| 202 | + if l == 0: |
| 203 | + return length * ([default] if is_list(v) else default) |
| 204 | + if l >= length: |
| 205 | + return v |
| 206 | + return v + (length - l) * (["\x00", "0"][l > 0 and is_bin(v)] if isinstance(v, str) else \ |
| 207 | + [[["\x00", "0"][l > 0 and is_bin(v)]], [0]][l > 0 and isinstance(v[0], int)] \ |
| 208 | + if is_list(v) else None) |
| 209 | + def _zeropad(f): |
| 210 | + if not is_function(f): |
| 211 | + return _pad(f) |
| 212 | + from functools import wraps |
| 213 | + @wraps(f) |
| 214 | + def _wrapper(*a, **kw): |
| 215 | + return _pad(f(*a, **kw)) |
| 216 | + return _wrapper |
| 217 | + return _zeropad |
| 218 | + |
| 219 | + |
184 | 220 | # https://stackoverflow.com/questions/10875442/possible-to-change-a-functions-repr-in-python |
185 | 221 | class __reprwrapper(object): |
186 | 222 | def __init__(self, repr, func): |
|
0 commit comments