diff options
| author | troido <troido@protonmail.com> | 2020-03-06 11:26:59 +0100 |
|---|---|---|
| committer | troido <troido@protonmail.com> | 2020-03-06 11:26:59 +0100 |
| commit | dd07ff4d686f07cdc9736627dd0ef099ef5e4e4f (patch) | |
| tree | f43310b3779a95efd74a40ba8139cf146ad49051 /asciifarmclient/common/utils.py | |
| parent | c9366616079240cd7ee3d243c9f6897d40b4267d (diff) | |
new directory structure for the separate client repo
Diffstat (limited to 'asciifarmclient/common/utils.py')
| -rw-r--r-- | asciifarmclient/common/utils.py | 47 |
1 files changed, 47 insertions, 0 deletions
diff --git a/asciifarmclient/common/utils.py b/asciifarmclient/common/utils.py new file mode 100644 index 0000000..95ac32b --- /dev/null +++ b/asciifarmclient/common/utils.py @@ -0,0 +1,47 @@ + +import os + +def clamp(val, lower, upper): + """ val if it's between lower and upper, else the closest of the two""" + return max(min(val, upper), lower) + + +def concat(arr): + """Takes a list of sequences, returns the concatenation of the sequences """ + if isinstance(arr[0], str): + return "".join(arr) + if isinstance(arr[0], bytes): + return b"".join(arr) + if isinstance(arr[0], list): + l = [] + for s in arr: + l += s + return l + if isinstance(arr[0], tuple): + l = [] + for s in arr: + l += s + return tuple(l) + else: + raise ValueError("type {} can't be concatenated".format(type(arr[0]))) + + +def writeFileSafe(filename, data, tempname=None): + if tempname is None: + tempname = filename + ".tempfile" + with open(tempname, 'w') as f: + f.write(data) + os.rename(tempname, filename) + + +def readFile(filepath): + with open(filepath, "r") as f: + text = f.read() + return text + + +def get(collection, i, default=None): + """ Get an element in an indexed collection, or the default in case the index is out of bounds """ + if i < 0 or i >= len(collection): + return default + return collection[i] |
