picotron_fs

Types and functions for dealing with the picotron filesystem - including PODs, files, metadata...

  1"""Types and functions for dealing with the picotron filesystem - including PODs, files, metadata..."""
  2
  3from utils import *
  4from pico_defs import Language, encode_luastr, decode_luastr
  5from pico_srcdefs import Source, Error
  6from pico_cart import pico_base64_decode, pico_base64_encode
  7from pico_export import lz4_compress, lz4_uncompress
  8from pico_compress import update_mtf
  9from pico_tokenize import tokenize, TokenType, is_identifier
 10from pico_parse import parse, NodeType
 11from pico_output import format_luanum, format_string_literal
 12
 13# (note - picotron pods have nothing to do with pico8 pods)
 14
 15k_pod = b"pod"
 16k_pod_str = k_pod.decode()
 17k_pod_prefix_str = k_pod_str + ","
 18k_pod_format = b"pod_format"
 19k_pod_prefix_strs = (k_pod_format.decode(), "pod_type")
 20k_pod_raw_format = k_pod_format + b"=\"raw\""
 21k_meta_prefix = b"--[["
 22k_meta_pod_prefix = k_meta_prefix + k_pod
 23k_meta_pod_raw_prefix = k_meta_prefix + k_pod_raw_format
 24k_meta_suffix = b"]]"
 25
 26class UserData(Tuple):
 27    """Represents a picotron userdata"""
 28    type = width = height = data = ...
 29
 30def parse_pod(pod, ud_handler=None):
 31    """Parses a picotron pod from a readable string"""
 32    src = Source("<pod>", pod)
 33    tokens, token_errors = tokenize(src, lang=Language.picotron)
 34    if tokens:
 35        root, parse_errors = parse(src, tokens, lang=Language.picotron, for_expr=True)
 36    else:
 37        root, parse_errors = None, []
 38    
 39    value_errors = []
 40    def add_error(msg, node):
 41        value_errors.append(Error(msg, node))
 42
 43    def node_to_value(node):
 44        if node.type == NodeType.const:
 45            if node.token.type in (TokenType.number, TokenType.string):
 46                return node.token.parsed_value
 47            elif node.token.value == "false":
 48                return False
 49            elif node.token.value == "true":
 50                return True
 51            else:
 52                return None
 53        elif node.type == NodeType.unary_op and node.op == "-" and node.child.type == NodeType.const and node.child.token.type == TokenType.number:
 54            return -node.child.token.parsed_value
 55
 56        elif node.type == NodeType.call and node.func.type == NodeType.var and node.func.name == "userdata":
 57            ud_args = tuple(node_to_value(arg) for arg in node.args)
 58
 59            if len(ud_args) in (3, 4):
 60                type, width, data = ud_args[0], ud_args[1], ud_args[-1]
 61                height = ud_args[2] if len(ud_args) == 4 else 0
 62                if isinstance(type, str) and isinstance(width, int) and isinstance(height, int) and isinstance(data, str):
 63                    return UserData(type, width, height, data)
 64
 65            if len(ud_args) == 0 and ud_handler and (userdata := ud_handler()):
 66                return userdata
 67
 68            add_error(f"unknown userdata params: {ud_args}")
 69
 70        elif node.type == NodeType.table:
 71            table = {}
 72            index = 1
 73            for item in node.items:
 74                if item.type == NodeType.table_index:
 75                    key, value = node_to_value(item.key), node_to_value(item.value)
 76                    if e(key) and e(value):
 77                        table[key] = value
 78                elif item.type == NodeType.table_member:
 79                    value = node_to_value(item.value)
 80                    if e(value):
 81                        table[item.key.name] = value
 82                else:
 83                    value = node_to_value(item)
 84                    if e(value):
 85                        table[index] = value
 86                    index += 1
 87            return table
 88        
 89        elif node.type == NodeType.call and node.func.type == NodeType.var and node.func.name == "unpod" and len(node.args) == 1:
 90            value = node_to_value(node.args[0])
 91            if isinstance(value, str):
 92                return read_pod(encode_luastr(value))
 93                
 94            add_error(f"unknown unpod param: {value}")
 95
 96        else:
 97            add_error(f"unknown pod syntax {node.type}", node)
 98
 99    value = node_to_value(root) if root else None
100
101    if token_errors or parse_errors or value_errors:
102        print(f"Parsing errors for POD:\n{pod}")
103
104        for error in token_errors + parse_errors + value_errors:
105            print(error.format())
106        
107        throw(f"Unrecognized POD format - please report issue and use --keep-pod-compression for now")
108
109    return value
110
111def parse_meta_pod(pod):
112    """Parses a picotron pod as it appears in a file's metadata"""
113    if pod == k_pod_str:
114        return {}
115
116    pod = str_remove_prefix(pod, k_pod_prefix_str)
117    return parse_pod("{" + pod + "}")
118
119def format_pod(value, ud_handler=None):
120    """Formats a picotron pod into a readable string"""
121    if value is None:
122        return "nil"
123    elif value is False:
124        return "false"
125    elif value is True:
126        return "true"
127    elif isinstance(value, (int, float)):
128        return format_luanum(value, base=10, allow_not=False)
129    elif isinstance(value, str):
130        return format_string_literal(value, long=False, quote='"')
131
132    elif isinstance(value, UserData):
133        type, width, height, data = format_pod(value.type), format_pod(value.width), format_pod(value.height), format_pod(value.data)
134        if value.height:
135            result = f"userdata({type},{width},{height},{data})"
136        else:
137            result = f"userdata({type},{width},{data})"
138        
139        if ud_handler and ud_handler(value, result):
140            result = "\0" # to allow unambiguously finding it in the result
141        return result
142
143    elif isinstance(value, dict):
144        index = 1
145        parts = []
146        for key, child in value.items():
147            if key == index:
148                parts.append(format_pod(child, ud_handler))
149                index += 1
150            elif isinstance(key, str) and is_identifier(key, Language.picotron):
151                parts.append(f"{key}={format_pod(child, ud_handler)}")
152            else:
153                parts.append(f"[{format_pod(key, ud_handler)}]={format_pod(child, ud_handler)}")
154        return "{" + ",".join(parts) + "}"
155    else:
156        throw(f"invalid pod value {value}")
157
158def escape_meta(pod):
159    while True:
160        i = pod.rfind("]]")
161        if i < 0:
162            break
163        pod = str_replace_at(pod, i, 2, "\\93]")
164    return pod
165
166def format_meta_pod(value):
167    """Formats a picotron pod as it should appear in a file's metadata"""
168    for pod_prefix_str in k_pod_prefix_strs:
169        if pod_prefix_str in value: # put it first
170            prefix = f"{pod_prefix_str}={format_pod(value[pod_prefix_str])}"
171            value = value.copy()
172            del value[pod_prefix_str]
173            break
174    else:
175        prefix = k_pod_str
176    
177    rest = format_pod(value)[1:-1]
178    return escape_meta(f"{prefix},{rest}" if rest else prefix)
179
180k_lz4_prefix = b"lz4\0"
181k_pxu_prefix = b"pxu\0"
182k_b64_prefix = b"b64:"
183
184class PxuType(Enum):
185    # the ones currently supporting compression
186    u8 = 3
187    i16 = 12
188
189def get_pxu_type_info(type, rw):
190    if type == PxuType.u8:
191        return rw.u8, 2
192    elif type == PxuType.i16:
193        return rw.u16, 4
194    else:
195        throw("unsupported pxu type")
196
197class PxuCompression(Enum):
198    none = 1
199    mtf = 2
200    rle = 8
201
202class PxuFlags(Bitmask):
203    type: PxuType = 0xf
204    has_height = 0x40
205    long_size = 0x800
206    compression: PxuCompression = 0xf000
207
208def read_pxu(data, idx):
209    """Reads the picotron userdata compression format 'pxu' into a UserData."""
210
211    with BinaryReader(BytesIO(data)) as r:
212        r.setpos(idx)
213        check(r.bytes(4) == k_pxu_prefix, "wrong pxu header")
214        try:
215            flags = PxuFlags(r.u16())
216            type, compression = flags.type, flags.compression
217        except ValueError:
218            throw(f"unsupported pxu flags: {flags}")
219
220        width = r.u32() if flags.long_size else r.u8()
221        height = (r.u32() if flags.long_size else r.u8()) if flags.has_height else 1
222        size = width * height
223
224        read_type, type_nybbles = get_pxu_type_info(type, r)
225
226        if compression == PxuCompression.none:
227            data = [read_type() for _ in range(size)]
228
229        elif compression in (PxuCompression.mtf, PxuCompression.rle):
230            bits = r.u8()
231            if compression == PxuCompression.mtf:
232                warn_assert(bits == 4, "unsupported pxu bits")
233            else:
234                warn_assert(bits == 0, "unsupported pxu bits(?)")
235
236            mask = (1 << bits) - 1
237            ext_count = 1 << (8 - bits)
238
239            data = []
240            mapping = [i for i in range(mask)]
241            mtf = [i for i in range(mask)]
242
243            while len(data) < size:
244                b = r.u8()
245                
246                index = b & mask
247                if index == mask:
248                    value = read_type()
249                    if bits:
250                        mapping[mtf[-1]] = value
251                
252                else:
253                    update_mtf(mtf, mtf.index(index), index)
254                    value = mapping[index]
255                
256                count = 1 + (b >> bits)
257                if count == ext_count:
258                    while True:
259                        c = r.u8()
260                        count += c
261                        if c != 0xff:
262                            break
263                
264                for i in range(count):
265                    data.append(value)
266        
267        else:
268            throw(f"unsupported pxu compression: {compression}")
269
270        hexdata = "".join(f"{b:x}".zfill(type_nybbles) for b in data)
271        return UserData(str(type), width, height if flags.has_height else 0, hexdata), r.pos()
272
273def read_pod(value):
274    """Reads a picotron pod from possibly compressed bytes"""
275
276    if value.startswith(k_b64_prefix):
277        value = pico_base64_decode(value[4:])
278
279    if value.startswith(k_lz4_prefix):
280        with BinaryReader(BytesIO(value)) as r:
281            r.addpos(4)
282            size = r.u32()
283            unc_size = r.u32()
284            missing = size - r.remaining()
285            if missing > 0: # (incomplete) hack for some existing broken files
286                warn("truncated lz4 file!")
287                value = lz4_uncompress(r.bytes(r.remaining()) + b"}" * missing)
288            else:
289                value = lz4_uncompress(r.bytes(size))
290            warn_assert(len(value) == unc_size, "wrong lz4 uncompressed size")
291
292    pxu_i = 0
293    userdatas = None
294    while True:
295        pxu_i = value.find(k_pxu_prefix, pxu_i)
296        if pxu_i < 0:
297            break
298        
299        userdatas = userdatas or deque()
300        userdata, end_i = read_pxu(value, pxu_i)
301        value = str_replace_between(value, pxu_i, end_i, b"userdata()")
302        userdatas.append(userdata)
303
304    def handle_userdata():
305        if userdatas:
306            return userdatas.popleft()
307
308    return parse_pod(decode_luastr(value), handle_userdata)
309
310def write_pxu(ud, runtime=sys.maxsize):
311    """Writes userdata via the picotron userdata compression format 'pxu'"""
312    if ud.data.startswith("hex:"):
313        return None
314
315    try:
316        type = PxuType(ud.type)
317    except ValueError:
318        return None
319    
320    with BinaryWriter() as w:
321        if type == PxuType.u8:
322            compression = PxuCompression.mtf
323            bits = 4 # other values are not yet observed/tested
324        elif type == PxuType.i16 and runtime >= 21:
325            compression = PxuCompression.rle
326            bits = 0 # other values are not yet observed/tested
327        else:
328            return None
329
330        flags = PxuFlags(type=type, compression=compression)
331        if ud.height:
332            flags |= PxuFlags.has_height
333        if ud.width >= 0x100 or ud.height >= 0x100:
334            flags |= PxuFlags.long_size
335
336        w.bytes(k_pxu_prefix)
337        w.u16(int(flags))
338        (w.u32 if flags.long_size else w.u8)(ud.width)
339        if flags.has_height:
340            (w.u32 if flags.long_size else w.u8)(ud.height)
341        
342        write_type, type_nybbles = get_pxu_type_info(type, w)
343
344        data = []
345        try:
346            for i in range(0, len(ud.data), type_nybbles):
347                data.append(int(ud.data[i:i+type_nybbles], 16))
348        except ValueError:
349            throw("invalid userdata encountered")
350
351        w.u8(bits)
352        mask = (1 << bits) - 1
353        ext_count = 1 << (8 - bits)
354        
355        mapping = [i for i in range(mask)]
356        mtf = [i for i in range(mask)]
357
358        i = 0
359        while i < len(data):
360            count = 1
361            value = data[i]
362            i += 1
363            while i < len(data) and data[i] == value:
364                count += 1
365                i += 1
366
367            index = list_find(mapping, value)
368            if index < 0:
369                index = mask
370                if bits:
371                    mapping[mtf[-1]] = value
372
373            else:
374                update_mtf(mtf, mtf.index(index), index)
375            
376            w.u8(index | ((min(count, ext_count) - 1) << bits))
377            if index == mask:
378                write_type(value)
379            
380            if count >= ext_count:
381                count -= ext_count
382                while count >= 0xff:
383                    w.u8(0xff)
384                    count -= 0xff
385                w.u8(count)
386
387        return w.f.getvalue()
388
389def write_pod(pod, compress=True, use_pxu=True, use_base64=False, runtime=sys.maxsize):
390    """Writes a picotron pod into optionally compressed bytes"""
391    
392    pxu_datas = None
393    def handle_userdata(ud, str_data):
394        nonlocal pxu_datas
395        if use_pxu:
396            pxu_data = write_pxu(ud, runtime=runtime)
397            if pxu_data and len(pxu_data) < len(str_data):
398                pxu_datas = pxu_datas or deque()
399                pxu_datas.append(pxu_data)
400                return True
401
402    value = encode_luastr(format_pod(pod, handle_userdata))
403
404    pxu_i = 0
405    while pxu_datas:
406        pxu_i = value.find(0, pxu_i)
407        assert pxu_i >= 0
408
409        pxu_data = pxu_datas.popleft()
410        value = str_replace_at(value, pxu_i, 1, pxu_data)
411        pxu_i += len(pxu_data)
412
413    if compress:
414        with BinaryWriter() as w:
415            compressed = lz4_compress(value)
416            w.bytes(k_lz4_prefix)
417            w.u32(len(compressed))
418            w.u32(len(value))
419            w.bytes(compressed)
420            compressed_value = w.f.getvalue()
421            if len(compressed_value) < len(value):
422                value = compressed_value
423    
424    if use_base64:
425        value = k_b64_prefix + pico_base64_encode(value)
426
427    return value
428
429class PicotronFile:
430    """A picotron file or directory in its filesystem - files contain metadata & payload"""
431
432    def __init__(m, data, line=0):
433        """create a picotron file from raw data"""
434        m.data = data
435        m.line = line
436        m._metadata_cache = None
437        m._payload_cache = None
438    
439    @classmethod
440    def create(m, payload, metadata=None):
441        """create a picotron file from a payload (pod object or bytes) and optionally metadata"""
442        file = PicotronFile(b"")
443        if e(metadata):
444            file.metadata = metadata
445        elif not isinstance(payload, bytes):
446            file.raw_metadata = k_pod
447        file.payload = payload
448        return file
449
450    @property
451    def is_raw(m):
452        """whether the file's data is stored raw (as bytes) or as a pod"""
453        return e(m.data) and (not m.data.startswith(k_meta_pod_prefix) or m.data.startswith(k_meta_pod_raw_prefix))
454
455    @property
456    def raw_metadata(m):
457        """the file's metadata as raw bytes"""
458        if m.data is None or not m.data.startswith(k_meta_pod_prefix):
459            return None
460        end_i = m.data.find(k_meta_suffix)
461        if end_i < 0:
462            end_i = len(m.data)
463        return m.data[len(k_meta_prefix):end_i]
464
465    @raw_metadata.setter
466    def raw_metadata(m, value):
467        m._metadata_cache = None
468        assert not m.is_dir
469        if value is None:
470            m.data = m.raw_payload
471        else:
472            m.data = k_meta_prefix + value + k_meta_suffix + m.raw_payload
473
474    @property
475    def metadata(m):
476        """the file's metadata as a pod dict"""
477        if e(m._metadata_cache):
478            return m._metadata_cache
479        metadata = m.raw_metadata
480        if metadata != None:
481            metadata = parse_meta_pod(decode_luastr(metadata))
482        return metadata
483
484    @metadata.setter
485    def metadata(m, value):
486        if value is None:
487            m.raw_metadata = None
488        else:
489            assert isinstance(value, dict)
490            m.raw_metadata = encode_luastr(format_meta_pod(value))
491            m._metadata_cache = value
492
493    @property
494    def raw_payload(m):
495        """the file data (not including metadata) as raw bytes"""
496        if m.data is None:
497            return None
498        if not m.data.startswith(k_meta_pod_prefix):
499            return m.data
500        end_i = m.data.find(k_meta_suffix)
501        if end_i < 0:
502            return b""
503        return m.data[end_i + len(k_meta_suffix):]
504
505    @raw_payload.setter
506    def raw_payload(m, value):
507        m._payload_cache = None
508        assert not m.is_dir
509        metadata = m.raw_metadata
510        if e(metadata):
511            m.data = k_meta_prefix + metadata + k_meta_suffix + value
512        else:
513            m.data = value
514
515    @property
516    def payload(m):
517        """the file data (not including metadata) as a pod object (or as bytes, if raw)"""
518        if e(m._payload_cache):
519            return m._payload_cache
520        elif m.is_raw:
521            return m.raw_payload
522        else:
523            return read_pod(m.raw_payload)
524    
525    @payload.setter
526    def payload(m, value):
527        m.set_payload(value)
528
529    def set_payload(m, value, compress=True, use_pxu=True, use_base64=False, runtime=sys.maxsize):
530        if m.is_raw:
531            m.raw_payload = value
532        else:
533            m.raw_payload = write_pod(value, compress=compress, use_pxu=use_pxu, use_base64=use_base64, runtime=runtime)
534            m._payload_cache = value
535
536    is_dir = False
537
538class PicotronDir(PicotronFile):
539    def __init__(m):
540        super().__init__(None)
541    
542    is_dir = True
k_pod = b'pod'
k_pod_str = 'pod'
k_pod_prefix_str = 'pod,'
k_pod_format = b'pod_format'
k_pod_prefix_strs = ('pod_format', 'pod_type')
k_pod_raw_format = b'pod_format="raw"'
k_meta_prefix = b'--[['
k_meta_pod_prefix = b'--[[pod'
k_meta_pod_raw_prefix = b'--[[pod_format="raw"'
k_meta_suffix = b']]'
class UserData(utils.Tuple):
27class UserData(Tuple):
28    """Represents a picotron userdata"""
29    type = width = height = data = ...

Represents a picotron userdata

type

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

width

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

height

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

data

Return a callable object that fetches the given item(s) from its operand. After f = itemgetter(2), the call f(r) returns r[2]. After g = itemgetter(2, 5, 3), the call g(r) returns (r[2], r[5], r[3])

def parse_pod(pod, ud_handler=None):
 31def parse_pod(pod, ud_handler=None):
 32    """Parses a picotron pod from a readable string"""
 33    src = Source("<pod>", pod)
 34    tokens, token_errors = tokenize(src, lang=Language.picotron)
 35    if tokens:
 36        root, parse_errors = parse(src, tokens, lang=Language.picotron, for_expr=True)
 37    else:
 38        root, parse_errors = None, []
 39    
 40    value_errors = []
 41    def add_error(msg, node):
 42        value_errors.append(Error(msg, node))
 43
 44    def node_to_value(node):
 45        if node.type == NodeType.const:
 46            if node.token.type in (TokenType.number, TokenType.string):
 47                return node.token.parsed_value
 48            elif node.token.value == "false":
 49                return False
 50            elif node.token.value == "true":
 51                return True
 52            else:
 53                return None
 54        elif node.type == NodeType.unary_op and node.op == "-" and node.child.type == NodeType.const and node.child.token.type == TokenType.number:
 55            return -node.child.token.parsed_value
 56
 57        elif node.type == NodeType.call and node.func.type == NodeType.var and node.func.name == "userdata":
 58            ud_args = tuple(node_to_value(arg) for arg in node.args)
 59
 60            if len(ud_args) in (3, 4):
 61                type, width, data = ud_args[0], ud_args[1], ud_args[-1]
 62                height = ud_args[2] if len(ud_args) == 4 else 0
 63                if isinstance(type, str) and isinstance(width, int) and isinstance(height, int) and isinstance(data, str):
 64                    return UserData(type, width, height, data)
 65
 66            if len(ud_args) == 0 and ud_handler and (userdata := ud_handler()):
 67                return userdata
 68
 69            add_error(f"unknown userdata params: {ud_args}")
 70
 71        elif node.type == NodeType.table:
 72            table = {}
 73            index = 1
 74            for item in node.items:
 75                if item.type == NodeType.table_index:
 76                    key, value = node_to_value(item.key), node_to_value(item.value)
 77                    if e(key) and e(value):
 78                        table[key] = value
 79                elif item.type == NodeType.table_member:
 80                    value = node_to_value(item.value)
 81                    if e(value):
 82                        table[item.key.name] = value
 83                else:
 84                    value = node_to_value(item)
 85                    if e(value):
 86                        table[index] = value
 87                    index += 1
 88            return table
 89        
 90        elif node.type == NodeType.call and node.func.type == NodeType.var and node.func.name == "unpod" and len(node.args) == 1:
 91            value = node_to_value(node.args[0])
 92            if isinstance(value, str):
 93                return read_pod(encode_luastr(value))
 94                
 95            add_error(f"unknown unpod param: {value}")
 96
 97        else:
 98            add_error(f"unknown pod syntax {node.type}", node)
 99
100    value = node_to_value(root) if root else None
101
102    if token_errors or parse_errors or value_errors:
103        print(f"Parsing errors for POD:\n{pod}")
104
105        for error in token_errors + parse_errors + value_errors:
106            print(error.format())
107        
108        throw(f"Unrecognized POD format - please report issue and use --keep-pod-compression for now")
109
110    return value

Parses a picotron pod from a readable string

def parse_meta_pod(pod):
112def parse_meta_pod(pod):
113    """Parses a picotron pod as it appears in a file's metadata"""
114    if pod == k_pod_str:
115        return {}
116
117    pod = str_remove_prefix(pod, k_pod_prefix_str)
118    return parse_pod("{" + pod + "}")

Parses a picotron pod as it appears in a file's metadata

def format_pod(value, ud_handler=None):
120def format_pod(value, ud_handler=None):
121    """Formats a picotron pod into a readable string"""
122    if value is None:
123        return "nil"
124    elif value is False:
125        return "false"
126    elif value is True:
127        return "true"
128    elif isinstance(value, (int, float)):
129        return format_luanum(value, base=10, allow_not=False)
130    elif isinstance(value, str):
131        return format_string_literal(value, long=False, quote='"')
132
133    elif isinstance(value, UserData):
134        type, width, height, data = format_pod(value.type), format_pod(value.width), format_pod(value.height), format_pod(value.data)
135        if value.height:
136            result = f"userdata({type},{width},{height},{data})"
137        else:
138            result = f"userdata({type},{width},{data})"
139        
140        if ud_handler and ud_handler(value, result):
141            result = "\0" # to allow unambiguously finding it in the result
142        return result
143
144    elif isinstance(value, dict):
145        index = 1
146        parts = []
147        for key, child in value.items():
148            if key == index:
149                parts.append(format_pod(child, ud_handler))
150                index += 1
151            elif isinstance(key, str) and is_identifier(key, Language.picotron):
152                parts.append(f"{key}={format_pod(child, ud_handler)}")
153            else:
154                parts.append(f"[{format_pod(key, ud_handler)}]={format_pod(child, ud_handler)}")
155        return "{" + ",".join(parts) + "}"
156    else:
157        throw(f"invalid pod value {value}")

Formats a picotron pod into a readable string

def escape_meta(pod):
159def escape_meta(pod):
160    while True:
161        i = pod.rfind("]]")
162        if i < 0:
163            break
164        pod = str_replace_at(pod, i, 2, "\\93]")
165    return pod
def format_meta_pod(value):
167def format_meta_pod(value):
168    """Formats a picotron pod as it should appear in a file's metadata"""
169    for pod_prefix_str in k_pod_prefix_strs:
170        if pod_prefix_str in value: # put it first
171            prefix = f"{pod_prefix_str}={format_pod(value[pod_prefix_str])}"
172            value = value.copy()
173            del value[pod_prefix_str]
174            break
175    else:
176        prefix = k_pod_str
177    
178    rest = format_pod(value)[1:-1]
179    return escape_meta(f"{prefix},{rest}" if rest else prefix)

Formats a picotron pod as it should appear in a file's metadata

k_lz4_prefix = b'lz4\x00'
k_pxu_prefix = b'pxu\x00'
k_b64_prefix = b'b64:'
class PxuType(utils.Enum):
185class PxuType(Enum):
186    # the ones currently supporting compression
187    u8 = 3
188    i16 = 12

If a class has Enum as a baseclass, it's transformed into an enum. All non-private attributes of the class other than functions and descriptors become enum members. Atributes with a value of ... receive values automatically. Inherited classes behave like regular classes unless they have Enum as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter Atributes with a name ending with _ can be referred to without the _.

PxuType(value)
172        def __init__(m, value):
173            if value in full_value_name_map:
174                m.value = value
175            elif value in full_name_value_map:
176                m.value = full_name_value_map[value]
177            else:
178                raise ValueError(f"{value} not value of {cls_name}")
u8 = PxuType.u8
i16 = PxuType.i16
value
def get_pxu_type_info(type, rw):
190def get_pxu_type_info(type, rw):
191    if type == PxuType.u8:
192        return rw.u8, 2
193    elif type == PxuType.i16:
194        return rw.u16, 4
195    else:
196        throw("unsupported pxu type")
class PxuCompression(utils.Enum):
198class PxuCompression(Enum):
199    none = 1
200    mtf = 2
201    rle = 8

If a class has Enum as a baseclass, it's transformed into an enum. All non-private attributes of the class other than functions and descriptors become enum members. Atributes with a value of ... receive values automatically. Inherited classes behave like regular classes unless they have Enum as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter Atributes with a name ending with _ can be referred to without the _.

PxuCompression(value)
172        def __init__(m, value):
173            if value in full_value_name_map:
174                m.value = value
175            elif value in full_name_value_map:
176                m.value = full_name_value_map[value]
177            else:
178                raise ValueError(f"{value} not value of {cls_name}")
value
class PxuFlags(utils.Bitmask):
203class PxuFlags(Bitmask):
204    type: PxuType = 0xf
205    has_height = 0x40
206    long_size = 0x800
207    compression: PxuCompression = 0xf000

If a class has Bitmask as a baseclass, it's transformed into a bitmask. All non-private attributes of the class other than functions and descriptors become bitmask fields. Atributes with a value of ... receive bits automatically. A bitmask is like a struct, but with its fields mapped into a single bitmask integer. Bitmasks can also be manipulated via: & | ^ Inherited classes behave like regular classes unless they have Bitmask as a direct baseclass. Advanced: ExcludeAttr/IncludeAttr, _values keyword parameter Atributes with a name ending with _ can be referred to without the _.

PxuFlags(value=None, **kwargs)
272        def __init__(m, value = None, **kwargs):
273            if value is None:
274                m.value = 0
275            elif isinstance(value, int) and (value & full_mask) == value:
276                m.value = value
277            elif isinstance(value, str) and value in full_name_mask_map:
278                m.value = full_name_mask_map[value]
279            elif isinstance(value, m.__class__):
280                m.value = value.value
281            elif isinstance(value, (tuple, list)):
282                m.value = reduce(lambda x,y:x|y, (full_name_mask_map[part] for part in value), 0)
283            else:
284                raise ValueError(f"{value} not value of {cls_name}")
285        
286            if kwargs:
287                for key, value in kwargs.items():
288                    setattr(m, key, value)
type: PxuType
has_height
long_size
compression: PxuCompression
value
def read_pxu(data, idx):
209def read_pxu(data, idx):
210    """Reads the picotron userdata compression format 'pxu' into a UserData."""
211
212    with BinaryReader(BytesIO(data)) as r:
213        r.setpos(idx)
214        check(r.bytes(4) == k_pxu_prefix, "wrong pxu header")
215        try:
216            flags = PxuFlags(r.u16())
217            type, compression = flags.type, flags.compression
218        except ValueError:
219            throw(f"unsupported pxu flags: {flags}")
220
221        width = r.u32() if flags.long_size else r.u8()
222        height = (r.u32() if flags.long_size else r.u8()) if flags.has_height else 1
223        size = width * height
224
225        read_type, type_nybbles = get_pxu_type_info(type, r)
226
227        if compression == PxuCompression.none:
228            data = [read_type() for _ in range(size)]
229
230        elif compression in (PxuCompression.mtf, PxuCompression.rle):
231            bits = r.u8()
232            if compression == PxuCompression.mtf:
233                warn_assert(bits == 4, "unsupported pxu bits")
234            else:
235                warn_assert(bits == 0, "unsupported pxu bits(?)")
236
237            mask = (1 << bits) - 1
238            ext_count = 1 << (8 - bits)
239
240            data = []
241            mapping = [i for i in range(mask)]
242            mtf = [i for i in range(mask)]
243
244            while len(data) < size:
245                b = r.u8()
246                
247                index = b & mask
248                if index == mask:
249                    value = read_type()
250                    if bits:
251                        mapping[mtf[-1]] = value
252                
253                else:
254                    update_mtf(mtf, mtf.index(index), index)
255                    value = mapping[index]
256                
257                count = 1 + (b >> bits)
258                if count == ext_count:
259                    while True:
260                        c = r.u8()
261                        count += c
262                        if c != 0xff:
263                            break
264                
265                for i in range(count):
266                    data.append(value)
267        
268        else:
269            throw(f"unsupported pxu compression: {compression}")
270
271        hexdata = "".join(f"{b:x}".zfill(type_nybbles) for b in data)
272        return UserData(str(type), width, height if flags.has_height else 0, hexdata), r.pos()

Reads the picotron userdata compression format 'pxu' into a UserData.

def read_pod(value):
274def read_pod(value):
275    """Reads a picotron pod from possibly compressed bytes"""
276
277    if value.startswith(k_b64_prefix):
278        value = pico_base64_decode(value[4:])
279
280    if value.startswith(k_lz4_prefix):
281        with BinaryReader(BytesIO(value)) as r:
282            r.addpos(4)
283            size = r.u32()
284            unc_size = r.u32()
285            missing = size - r.remaining()
286            if missing > 0: # (incomplete) hack for some existing broken files
287                warn("truncated lz4 file!")
288                value = lz4_uncompress(r.bytes(r.remaining()) + b"}" * missing)
289            else:
290                value = lz4_uncompress(r.bytes(size))
291            warn_assert(len(value) == unc_size, "wrong lz4 uncompressed size")
292
293    pxu_i = 0
294    userdatas = None
295    while True:
296        pxu_i = value.find(k_pxu_prefix, pxu_i)
297        if pxu_i < 0:
298            break
299        
300        userdatas = userdatas or deque()
301        userdata, end_i = read_pxu(value, pxu_i)
302        value = str_replace_between(value, pxu_i, end_i, b"userdata()")
303        userdatas.append(userdata)
304
305    def handle_userdata():
306        if userdatas:
307            return userdatas.popleft()
308
309    return parse_pod(decode_luastr(value), handle_userdata)

Reads a picotron pod from possibly compressed bytes

def write_pxu(ud, runtime=9223372036854775807):
311def write_pxu(ud, runtime=sys.maxsize):
312    """Writes userdata via the picotron userdata compression format 'pxu'"""
313    if ud.data.startswith("hex:"):
314        return None
315
316    try:
317        type = PxuType(ud.type)
318    except ValueError:
319        return None
320    
321    with BinaryWriter() as w:
322        if type == PxuType.u8:
323            compression = PxuCompression.mtf
324            bits = 4 # other values are not yet observed/tested
325        elif type == PxuType.i16 and runtime >= 21:
326            compression = PxuCompression.rle
327            bits = 0 # other values are not yet observed/tested
328        else:
329            return None
330
331        flags = PxuFlags(type=type, compression=compression)
332        if ud.height:
333            flags |= PxuFlags.has_height
334        if ud.width >= 0x100 or ud.height >= 0x100:
335            flags |= PxuFlags.long_size
336
337        w.bytes(k_pxu_prefix)
338        w.u16(int(flags))
339        (w.u32 if flags.long_size else w.u8)(ud.width)
340        if flags.has_height:
341            (w.u32 if flags.long_size else w.u8)(ud.height)
342        
343        write_type, type_nybbles = get_pxu_type_info(type, w)
344
345        data = []
346        try:
347            for i in range(0, len(ud.data), type_nybbles):
348                data.append(int(ud.data[i:i+type_nybbles], 16))
349        except ValueError:
350            throw("invalid userdata encountered")
351
352        w.u8(bits)
353        mask = (1 << bits) - 1
354        ext_count = 1 << (8 - bits)
355        
356        mapping = [i for i in range(mask)]
357        mtf = [i for i in range(mask)]
358
359        i = 0
360        while i < len(data):
361            count = 1
362            value = data[i]
363            i += 1
364            while i < len(data) and data[i] == value:
365                count += 1
366                i += 1
367
368            index = list_find(mapping, value)
369            if index < 0:
370                index = mask
371                if bits:
372                    mapping[mtf[-1]] = value
373
374            else:
375                update_mtf(mtf, mtf.index(index), index)
376            
377            w.u8(index | ((min(count, ext_count) - 1) << bits))
378            if index == mask:
379                write_type(value)
380            
381            if count >= ext_count:
382                count -= ext_count
383                while count >= 0xff:
384                    w.u8(0xff)
385                    count -= 0xff
386                w.u8(count)
387
388        return w.f.getvalue()

Writes userdata via the picotron userdata compression format 'pxu'

def write_pod( pod, compress=True, use_pxu=True, use_base64=False, runtime=9223372036854775807):
390def write_pod(pod, compress=True, use_pxu=True, use_base64=False, runtime=sys.maxsize):
391    """Writes a picotron pod into optionally compressed bytes"""
392    
393    pxu_datas = None
394    def handle_userdata(ud, str_data):
395        nonlocal pxu_datas
396        if use_pxu:
397            pxu_data = write_pxu(ud, runtime=runtime)
398            if pxu_data and len(pxu_data) < len(str_data):
399                pxu_datas = pxu_datas or deque()
400                pxu_datas.append(pxu_data)
401                return True
402
403    value = encode_luastr(format_pod(pod, handle_userdata))
404
405    pxu_i = 0
406    while pxu_datas:
407        pxu_i = value.find(0, pxu_i)
408        assert pxu_i >= 0
409
410        pxu_data = pxu_datas.popleft()
411        value = str_replace_at(value, pxu_i, 1, pxu_data)
412        pxu_i += len(pxu_data)
413
414    if compress:
415        with BinaryWriter() as w:
416            compressed = lz4_compress(value)
417            w.bytes(k_lz4_prefix)
418            w.u32(len(compressed))
419            w.u32(len(value))
420            w.bytes(compressed)
421            compressed_value = w.f.getvalue()
422            if len(compressed_value) < len(value):
423                value = compressed_value
424    
425    if use_base64:
426        value = k_b64_prefix + pico_base64_encode(value)
427
428    return value

Writes a picotron pod into optionally compressed bytes

class PicotronFile:
430class PicotronFile:
431    """A picotron file or directory in its filesystem - files contain metadata & payload"""
432
433    def __init__(m, data, line=0):
434        """create a picotron file from raw data"""
435        m.data = data
436        m.line = line
437        m._metadata_cache = None
438        m._payload_cache = None
439    
440    @classmethod
441    def create(m, payload, metadata=None):
442        """create a picotron file from a payload (pod object or bytes) and optionally metadata"""
443        file = PicotronFile(b"")
444        if e(metadata):
445            file.metadata = metadata
446        elif not isinstance(payload, bytes):
447            file.raw_metadata = k_pod
448        file.payload = payload
449        return file
450
451    @property
452    def is_raw(m):
453        """whether the file's data is stored raw (as bytes) or as a pod"""
454        return e(m.data) and (not m.data.startswith(k_meta_pod_prefix) or m.data.startswith(k_meta_pod_raw_prefix))
455
456    @property
457    def raw_metadata(m):
458        """the file's metadata as raw bytes"""
459        if m.data is None or not m.data.startswith(k_meta_pod_prefix):
460            return None
461        end_i = m.data.find(k_meta_suffix)
462        if end_i < 0:
463            end_i = len(m.data)
464        return m.data[len(k_meta_prefix):end_i]
465
466    @raw_metadata.setter
467    def raw_metadata(m, value):
468        m._metadata_cache = None
469        assert not m.is_dir
470        if value is None:
471            m.data = m.raw_payload
472        else:
473            m.data = k_meta_prefix + value + k_meta_suffix + m.raw_payload
474
475    @property
476    def metadata(m):
477        """the file's metadata as a pod dict"""
478        if e(m._metadata_cache):
479            return m._metadata_cache
480        metadata = m.raw_metadata
481        if metadata != None:
482            metadata = parse_meta_pod(decode_luastr(metadata))
483        return metadata
484
485    @metadata.setter
486    def metadata(m, value):
487        if value is None:
488            m.raw_metadata = None
489        else:
490            assert isinstance(value, dict)
491            m.raw_metadata = encode_luastr(format_meta_pod(value))
492            m._metadata_cache = value
493
494    @property
495    def raw_payload(m):
496        """the file data (not including metadata) as raw bytes"""
497        if m.data is None:
498            return None
499        if not m.data.startswith(k_meta_pod_prefix):
500            return m.data
501        end_i = m.data.find(k_meta_suffix)
502        if end_i < 0:
503            return b""
504        return m.data[end_i + len(k_meta_suffix):]
505
506    @raw_payload.setter
507    def raw_payload(m, value):
508        m._payload_cache = None
509        assert not m.is_dir
510        metadata = m.raw_metadata
511        if e(metadata):
512            m.data = k_meta_prefix + metadata + k_meta_suffix + value
513        else:
514            m.data = value
515
516    @property
517    def payload(m):
518        """the file data (not including metadata) as a pod object (or as bytes, if raw)"""
519        if e(m._payload_cache):
520            return m._payload_cache
521        elif m.is_raw:
522            return m.raw_payload
523        else:
524            return read_pod(m.raw_payload)
525    
526    @payload.setter
527    def payload(m, value):
528        m.set_payload(value)
529
530    def set_payload(m, value, compress=True, use_pxu=True, use_base64=False, runtime=sys.maxsize):
531        if m.is_raw:
532            m.raw_payload = value
533        else:
534            m.raw_payload = write_pod(value, compress=compress, use_pxu=use_pxu, use_base64=use_base64, runtime=runtime)
535            m._payload_cache = value
536
537    is_dir = False

A picotron file or directory in its filesystem - files contain metadata & payload

PicotronFile(data, line=0)
433    def __init__(m, data, line=0):
434        """create a picotron file from raw data"""
435        m.data = data
436        m.line = line
437        m._metadata_cache = None
438        m._payload_cache = None

create a picotron file from raw data

@classmethod
def create(m, payload, metadata=None):
440    @classmethod
441    def create(m, payload, metadata=None):
442        """create a picotron file from a payload (pod object or bytes) and optionally metadata"""
443        file = PicotronFile(b"")
444        if e(metadata):
445            file.metadata = metadata
446        elif not isinstance(payload, bytes):
447            file.raw_metadata = k_pod
448        file.payload = payload
449        return file

create a picotron file from a payload (pod object or bytes) and optionally metadata

is_raw
451    @property
452    def is_raw(m):
453        """whether the file's data is stored raw (as bytes) or as a pod"""
454        return e(m.data) and (not m.data.startswith(k_meta_pod_prefix) or m.data.startswith(k_meta_pod_raw_prefix))

whether the file's data is stored raw (as bytes) or as a pod

raw_metadata
456    @property
457    def raw_metadata(m):
458        """the file's metadata as raw bytes"""
459        if m.data is None or not m.data.startswith(k_meta_pod_prefix):
460            return None
461        end_i = m.data.find(k_meta_suffix)
462        if end_i < 0:
463            end_i = len(m.data)
464        return m.data[len(k_meta_prefix):end_i]

the file's metadata as raw bytes

metadata
475    @property
476    def metadata(m):
477        """the file's metadata as a pod dict"""
478        if e(m._metadata_cache):
479            return m._metadata_cache
480        metadata = m.raw_metadata
481        if metadata != None:
482            metadata = parse_meta_pod(decode_luastr(metadata))
483        return metadata

the file's metadata as a pod dict

raw_payload
494    @property
495    def raw_payload(m):
496        """the file data (not including metadata) as raw bytes"""
497        if m.data is None:
498            return None
499        if not m.data.startswith(k_meta_pod_prefix):
500            return m.data
501        end_i = m.data.find(k_meta_suffix)
502        if end_i < 0:
503            return b""
504        return m.data[end_i + len(k_meta_suffix):]

the file data (not including metadata) as raw bytes

payload
516    @property
517    def payload(m):
518        """the file data (not including metadata) as a pod object (or as bytes, if raw)"""
519        if e(m._payload_cache):
520            return m._payload_cache
521        elif m.is_raw:
522            return m.raw_payload
523        else:
524            return read_pod(m.raw_payload)

the file data (not including metadata) as a pod object (or as bytes, if raw)

def set_payload( m, value, compress=True, use_pxu=True, use_base64=False, runtime=9223372036854775807):
530    def set_payload(m, value, compress=True, use_pxu=True, use_base64=False, runtime=sys.maxsize):
531        if m.is_raw:
532            m.raw_payload = value
533        else:
534            m.raw_payload = write_pod(value, compress=compress, use_pxu=use_pxu, use_base64=use_base64, runtime=runtime)
535            m._payload_cache = value
is_dir = False
class PicotronDir(PicotronFile):
539class PicotronDir(PicotronFile):
540    def __init__(m):
541        super().__init__(None)
542    
543    is_dir = True

A picotron file or directory in its filesystem - files contain metadata & payload

PicotronDir()
540    def __init__(m):
541        super().__init__(None)

create a picotron file from raw data

is_dir = True