Files
TransPyC/lib/Shell/Serializer.py
2026-07-18 19:25:40 +08:00

62 lines
1.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
from __future__ import annotations
import json
import struct
from typing import Any
def SerializeSymbolTable(SymbolTable: dict[str, Any]) -> bytes:
"""将符号表序列化为二进制格式
格式:
- 4字节: JSON数据长度小端序
- N字节: JSON数据UTF-8编码
Args:
SymbolTable: 符号表字典
Returns:
二进制字节数据
"""
JsonData: bytes = json.dumps(SymbolTable, ensure_ascii=False).encode('utf-8')
length: int = len(JsonData)
# 使用4字节小端序整数表示长度
header: bytes = struct.pack('<I', length)
return header + JsonData
def deSerializeSymbolTable(data: bytes) -> dict[str, Any]:
"""从二进制数据反序列化符号表
Args:
data: 二进制字节数据
Returns:
符号表字典
"""
if len(data) < 4:
raise ValueError("Invalid symbin file: data too short")
# 解析4字节长度头小端序
length: int = struct.unpack('<I', data[:4])[0]
JsonData: bytes = data[4:4+length]
return json.loads(JsonData.decode('utf-8'))
class SymbolFile:
"""符号文件类,用于解析和存储符号信息"""
def __init__(self, file: str | None = None, string: str | None = None, type: str | None = None, encoding: str = 'utf-8') -> None:
"""初始化SymbolFile对象
Args:
file: 文件路径
string: 代码字符串
type: 文件类型,支持"c""py"
encoding: 文件编码
"""
self.FilePath: str | None = file
self.CodeString: str | None = string
self.FileType: str | None = type
self.encoding: str = encoding
self.symbols: dict[str, Any] = {}