From 142d6e53b03203758318bc828c24659a93589923 Mon Sep 17 00:00:00 2001 From: Simon Forman Date: Tue, 1 Mar 2022 14:13:07 -0800 Subject: [PATCH] Let's try out the "snippets" idea. Represent strings (byte strings) as three-tuples of (git sha hash, offset, length) immutable datastructures. --- implementations/Python/joy/utils/snippets.py | 34 ++++++++++++++++++++ 1 file changed, 34 insertions(+) create mode 100644 implementations/Python/joy/utils/snippets.py diff --git a/implementations/Python/joy/utils/snippets.py b/implementations/Python/joy/utils/snippets.py new file mode 100644 index 0000000..843c325 --- /dev/null +++ b/implementations/Python/joy/utils/snippets.py @@ -0,0 +1,34 @@ +from collections import namedtuple +from re import compile as RE + +Snippet = namedtuple('Snippet', 'sha offset length') +fmt = '{%s %i %i}' +pat = ( + '{' + '\s*' + '(?P[a-f0-9]+)' + '\s+' + '(?P\d+)' + '\s+' + '(?P\d+)' + '\s*' + '}' + ) +PAT = RE(pat) + + +def to_string(snip): + return fmt % _ts(*snip) + +def _ts(sha, offset, length): + return sha.decode('ascii'), offset, length + +def from_string(text): + m = PAT.match(text) + if not m: + raise ValueError + return _fs(**m.groupdict()) + +def _fs(sha, offset, length): + return Snippet(sha.encode('ascii'), int(offset), int(length)) +