JCE Encode/Decode
Project description
Jce Struct
Tencent JCE Encode/Decode with fully pydantic support
Before Using
JceStruct
is base on python type hint (doc) and Pydantic.
Data validation and IDE type checking are all supported.
Installation
pip install JceStruct
or install from source (using poetry)
poetry add git+https://github.com/yanyongyu/JceStruct.git
or clone and install
git clone https://github.com/yanyongyu/JceStruct.git
cd JceStruct
poetry install
Usage
Create Struct
Create your struct by inheriting JceStruct
and define your fields with JceField
from jce import types, JceStruct, JceField
class ExampleStruct(JceStruct):
# normal definition
field1: types.INT32 = JceField(jce_id=1)
# define type in options
field2: float = JceField(jce_id=2, jce_type=types.DOUBLE)
# define an optional field with default value
field3: Optional[types.BOOL] = JceField(None, jce_id=3)
# nested struct supported
field4: types.LIST[OtherStruct] = JceField(types.LIST(), jce_id=4)
# optional other pydantic field
extra_pydantic_field: str = "extra_pydantic_field"
Encode/Decode
# simple encode decode
example: ExampleStruct = ExampleStruct(
field1=1, field2=2., field4=types.LIST[OtherStruct()]
)
bytes = example.encode()
example: ExampleStruct = ExampleStruct.decode(bytes, extra_pydantic_field="extra")
# decode list from example struct
others: List[OtherStruct] = OtherStruct.decode_list(bytes, jce_id=3, **extra)
Custom Encoder/Decoder
Just inherit JceEncoder/JceDecoder and add it to your struct configuration
from jce import JceStruct, JceEncoder
class CustomEncoder(JceEncoder):
pass
class ExampleStruct(JceStruct):
class Config:
jce_encoder = CustomEncoder
# jce_decoder = CustomDecoder
Custom types
Just inherit JceType and implement abstruct methods
from jce import types
class CustomType(types.JceType):
...
Change default types
By default, head bytes are treated like this:
{
0: BYTE,
1: INT16,
2: INT32,
3: INT64,
4: FLOAT,
5: DOUBLE,
6: STRING1,
7: STRING4,
8: MAP,
9: LIST,
10: STRUCT_START,
11: STRUCT_END,
12: ZERO_TAG,
13: BYTES
}
field will be converted to the type defined in struct when validate.
to change it:
class ExampleStruct(JceStruct):
class Config:
jce_default_type = {
# add all types here
}
Command Line Usage
python -m jce 1f2e3d4c5b6a79
Project details
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
JceStruct-0.1.2.tar.gz
(9.3 kB
view hashes)
Built Distribution
Close
Hashes for JceStruct-0.1.2-py3-none-any.whl
Algorithm | Hash digest | |
---|---|---|
SHA256 | 8a858c055921c65c98133a20129c77e10c53258b9703223714974e729ecb6dc1 |
|
MD5 | ea8d0f4c6e7ab2c71fca6f2eace3f213 |
|
BLAKE2b-256 | d45e4ff8e487caf8b3ef6836a17fcb03c49f1b332a3d520e7b4118a4e89d48e9 |