-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path06_struct_serde.mojo
More file actions
143 lines (107 loc) · 4.27 KB
/
06_struct_serde.mojo
File metadata and controls
143 lines (107 loc) · 4.27 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
"""Example: Struct serialization and deserialization with traits.
This example shows how to implement Serializable and Deserializable traits
for your structs to enable clean serialize/deserialize functions.
"""
from mojson import loads, Value
from mojson.serialize import Serializable, serialize, to_json_value
from mojson.deserialize import Deserializable, deserialize, get_string, get_int, get_bool
@fieldwise_init
struct Person(Serializable, Deserializable, Copyable, Movable):
"""A person with name, age, and active status.
Implements both Serializable and Deserializable for full round-trip support.
"""
var name: String
var age: Int
var active: Bool
fn to_json(self) -> String:
"""Serialize to JSON string."""
return (
'{"name":'
+ to_json_value(self.name)
+ ',"age":'
+ to_json_value(self.age)
+ ',"active":'
+ to_json_value(self.active)
+ '}'
)
@staticmethod
fn from_json(json: Value) raises -> Self:
"""Deserialize from JSON Value."""
return Self(
name=get_string(json, "name"),
age=get_int(json, "age"),
active=get_bool(json, "active"),
)
fn example_serialize():
"""Demonstrate serialization."""
print("=== Serialization ===\n")
var person = Person(name="Alice", age=30, active=True)
print("Original object:", person.name, person.age, person.active)
# Serialize using the serialize() helper
var json_str = serialize(person)
print("Serialized JSON:", json_str)
print()
fn example_deserialize() raises:
"""Demonstrate deserialization."""
print("=== Deserialization ===\n")
var json_str = '{"name":"Bob","age":25,"active":false}'
print("JSON string:", json_str)
# Deserialize using the deserialize() helper
var person = deserialize[Person](json_str)
print("Deserialized object:", person.name, person.age, person.active)
print()
fn example_round_trip() raises:
"""Demonstrate full round-trip."""
print("=== Round-Trip ===\n")
var original = Person(name="Charlie", age=35, active=True)
print("Original:", original.name, original.age, original.active)
# Serialize
var json_str = serialize(original)
print("JSON:", json_str)
# Deserialize
var restored = deserialize[Person](json_str)
print("Restored:", restored.name, restored.age, restored.active)
# Verify
var matches = (
restored.name == original.name
and restored.age == original.age
and restored.active == original.active
)
print("Round-trip successful:", matches)
print()
fn example_gpu_deserialize() raises:
"""Demonstrate GPU-accelerated deserialization."""
print("=== GPU-Accelerated Deserialization ===\n")
var json_str = '{"name":"Dave","age":40,"active":true}'
print("JSON string:", json_str)
# Use GPU backend for parsing (useful for large JSON)
var person = deserialize[Person, target="gpu"](json_str)
print("Deserialized (GPU):", person.name, person.age, person.active)
print()
fn example_direct_method_calls() raises:
"""Show that you can also call methods directly."""
print("=== Direct Method Calls ===\n")
# You don't have to use serialize/deserialize helpers
# You can call to_json/from_json directly
var person = Person(name="Eve", age=28, active=False)
print("Original:", person.name)
# Direct serialization
var json_str = person.to_json()
print("JSON:", json_str)
# Direct deserialization
var json = loads(json_str)
var restored = Person.from_json(json)
print("Restored:", restored.name)
print()
fn main() raises:
print("\n╔════════════════════════════════════════════╗")
print("║ Struct Serialization/Deserialization ║")
print("╚════════════════════════════════════════════╝\n")
example_serialize()
example_deserialize()
example_round_trip()
example_gpu_deserialize()
example_direct_method_calls()
print("═" * 46)
print("✓ All examples completed successfully!")
print("═" * 46)