OSDN Git Service

Basic system, incomplete.
[joypy/Thun.git] / implementations / Python / joy / utils / snippets.py
1 from collections import namedtuple
2 from re import compile as RE
3
4
5 Snippet = namedtuple('Snippet', 'sha offset length')
6
7
8 pat = (
9     '{'
10     '\s*'
11     '(?P<sha>[a-f0-9]+)'
12     '\s+'
13     '(?P<offset>\d+)'
14     '\s+'
15     '(?P<length>\d+)'
16     '\s*'
17     '}'
18     )
19
20
21 _PAT = RE(pat)
22
23
24 def to_string(snip):
25     return _ts(*snip)
26
27
28 def _ts(sha, offset, length):
29     return f'{{{sha.decode("ascii")} {offset} {length}}}'
30
31
32 def from_string(text):
33     m = _PAT.match(text)
34     if not m:
35         raise ValueError
36     return _fs(**m.groupdict())
37
38
39 def _fs(sha, offset, length):
40     return Snippet(sha.encode('ascii'), int(offset), int(length))