Skip to content

Commit 91d1975

Browse files
committed
Added helper function zeropad
1 parent 2aff7d8 commit 91d1975

File tree

5 files changed

+50
-3
lines changed

5 files changed

+50
-3
lines changed

docs/pages/helpers.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -110,6 +110,7 @@ It also provides some other utility functions, decorators, context managers and
110110
`ts.xor` | repeated XOR function, also allowing to apply an ordinal offset on XORed characters
111111
`ts.xor_file` | XOR a file with a given key
112112
`ts.withrepr` | decorator for modifying the representation of a function
113+
`ts.zeropad` | decorator for zero-padding the result of either an input function or a value, depending on the output value (binary string is padded with "`0`", normal string is padded with "`\x00`", etc).
113114

114115
-----
115116

src/tinyscript/VERSION.txt

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
1.30.7
1+
1.30.8

src/tinyscript/helpers/common.py

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212

1313
__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"]
1515

1616

1717
def human_readable_size(size, precision=0):
@@ -181,6 +181,42 @@ def xor_file(filename, key, offset=0):
181181
cursor += l
182182

183183

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+
184220
# https://stackoverflow.com/questions/10875442/possible-to-change-a-functions-repr-in-python
185221
class __reprwrapper(object):
186222
def __init__(self, repr, func):

src/tinyscript/helpers/path.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
import sys
88
from mimetypes import guess_type
99
from pathlib2 import Path as BasePath
10-
from pyminizip import compress_multiple, uncompress
1110
from shutil import copy, copy2, copytree, rmtree
1211
from tempfile import gettempdir, NamedTemporaryFile as TempFile
1312

@@ -506,6 +505,7 @@ def archive(self, path=None, password=None, ask=False, remove=True, **kwargs):
506505
dst_list.append(str(f.relative_to(self).dirname))
507506
# Pyminizip changes the current working directory after creation of an archive ; so backup the current
508507
# working directory to restore it after compression
508+
from pyminizip import compress_multiple, uncompress
509509
cwd = os.getcwd()
510510
compress_multiple(src_list, dst_list, str(dst), password or "", 9)
511511
os.chdir(cwd)
@@ -538,6 +538,7 @@ def load(self, path=None, password=None, ask=False, remove=True, **kwargs):
538538
dst = Path(path or str(self.dirname.joinpath(self.stem)), create=True)
539539
# Pyminizip changes the current working directory after extraction of an archive ; so backup the current
540540
# working directory to restore it after decompression
541+
from pyminizip import uncompress
541542
cwd = os.getcwd()
542543
uncompress(str(self), password or "", str(dst), False)
543544
os.chdir(cwd)

tests/test_helpers_common.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,15 @@ def test_func():
6262
def test_func2():
6363
pass
6464
self.assertTrue(repr(test_func2).startswith("<test_function "))
65+
self.assertEqual(zeropad(5)("ok"), "ok\x00\x00\x00")
66+
self.assertEqual(zeropad(5)("011"), "01100")
67+
self.assertEqual(zeropad(5)([0,1,1]), [0,1,1,0,0])
68+
self.assertEqual(zeropad(5)(["0","1","1"]), ["0","1","1","0","0"])
69+
self.assertEqual(zeropad(5)(lambda: "ok")(), "ok\x00\x00\x00")
70+
self.assertEqual(zeropad(5)(lambda: "011")(), "01100")
71+
self.assertEqual(zeropad(5)([]), ["\x00","\x00","\x00","\x00","\x00"])
72+
self.assertEqual(zeropad(5, default=0)([]), [0,0,0,0,0])
73+
self.assertEqual(zeropad(5, default="0")(""), "00000")
6574

6675
def test_lazy_load_functions(self):
6776
global DUMMY_CONST

0 commit comments

Comments
 (0)