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
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
|
use zr_protocol::codec::decode::Decode as DecodeTrait;
use zr_protocol::codec::encode::Encode as EncodeTrait;
use zr_protocol::context::Context;
// ── Test Codec derive (combines Encode + Decode) ───────────────────────
#[derive(zr_protocol::Codec)]
#[context(Ctx)]
pub struct CodecStruct {
id: u8,
#[codec(count(u8))]
items: Vec<u16>,
}
// ── State type for context-aware enums ───────────────────────────────
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum State {
Handshake,
Status,
Play,
}
pub struct Ctx {
pub state: State,
}
// ── Basic struct (no helpers) ────────────────────────────────────────
#[derive(zr_protocol::Encode, zr_protocol::Decode)]
pub struct BasicStruct {
a: u8,
b: u16,
c: u32,
}
// ── Skip ─────────────────────────────────────────────────────────────
#[derive(zr_protocol::Encode)]
pub struct WithSkip {
id: u8,
#[codec(skip)]
_cache: Vec<u8>,
name: u16,
}
// ── Count prefix ─────────────────────────────────────────────────────
#[derive(zr_protocol::Encode, zr_protocol::Decode)]
pub struct WithCount {
#[codec(count(u16))]
items: Vec<u32>,
}
// ── Condition on struct field ────────────────────────────────────────
#[derive(zr_protocol::Encode)]
pub struct WithCondition {
version: u8,
#[codec(if(self.version >= 2))]
extra: Option<u16>,
}
// ── Combined struct helpers ──────────────────────────────────────────
#[derive(zr_protocol::Encode)]
pub struct Combined {
version: u8,
#[codec(count(u16))]
items: Vec<u32>,
#[codec(if(self.items.is_empty()))]
fallback: Option<u8>,
}
// ── Enum with auto IDs (basic) ──────────────────────────────────────
#[derive(zr_protocol::Encode, zr_protocol::Decode)]
pub enum BasicEnum {
A(u8),
B { x: u16, y: u16 },
C,
}
// ── Enum with custom IDs ────────────────────────────────────────────
#[derive(zr_protocol::Encode, zr_protocol::Decode)]
pub enum CustomIdEnum {
#[id(0x10)]
Alpha(u8),
#[id(0x20)]
Beta { val: u16 },
#[id(0x30)]
Gamma,
}
// ── Context-aware enum (same ID, different states) ──────────────────
#[derive(zr_protocol::Encode, zr_protocol::Decode)]
#[context(Ctx)]
pub enum Packet {
#[id(0x00)]
#[codec(if(ctx.data.state == State::Handshake))]
Handshake(u16),
#[id(0x00)]
#[codec(if(ctx.data.state == State::Status))]
Status(u32),
#[id(0x01)]
#[codec(if(ctx.data.state == State::Play))]
PlayData(u8, u8),
#[id(0x02)]
Ping,
}
// ── Context enum with skip ──────────────────────────────────────────
#[derive(zr_protocol::Encode, zr_protocol::Decode)]
#[context(Ctx)]
pub enum WithSkipVariant {
#[id(0x00)]
Visible(u8),
#[codec(skip)]
Internal(u16),
#[id(0x01)]
AlsoVisible,
}
// ── Test runner ──────────────────────────────────────────────────────
fn enc<T: EncodeTrait<Ctx>>(value: &T, state: State) -> Vec<u8> {
let mut buf = Vec::new();
let ctx = Context::new(Ctx { state });
value.encode(&mut buf, &ctx).unwrap();
buf
}
fn dec<T: DecodeTrait<Ctx>>(buf: &[u8], state: State) -> T {
let ctx = Context::new(Ctx { state });
T::decode(&mut &buf[..], &ctx).unwrap()
}
fn main() {
// ── BasicStruct encode ──
let basic = BasicStruct {
a: 1,
b: 0x203,
c: 0x4050607,
};
let bytes = enc(&basic, State::Handshake);
assert_eq!(bytes, vec![0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07]);
println!("BasicStruct encode: OK");
// ── BasicStruct decode ──
let decoded: BasicStruct = dec(&bytes, State::Handshake);
assert_eq!(decoded.a, 1);
assert_eq!(decoded.b, 0x203);
assert_eq!(decoded.c, 0x4050607);
println!("BasicStruct decode: OK");
// ── WithSkip ──
let skip = WithSkip {
id: 0xAA,
_cache: vec![1, 2, 3],
name: 0xBBCC,
};
let bytes = enc(&skip, State::Handshake);
assert_eq!(bytes, vec![0xAA, 0xBB, 0xCC]);
println!("WithSkip: OK");
// ── WithCount encode ──
let count_empty = WithCount { items: vec![] };
let bytes = enc(&count_empty, State::Handshake);
assert_eq!(bytes, vec![0x00, 0x00]);
println!("WithCount (empty): OK");
// ── WithCount decode ──
let decoded: WithCount = dec(&bytes, State::Handshake);
assert_eq!(decoded.items, Vec::<u32>::new());
println!("WithCount (empty) decode: OK");
// ── WithCount with items encode ──
let count_some = WithCount {
items: vec![0x0A, 0x0B],
};
let bytes = enc(&count_some, State::Handshake);
assert_eq!(
bytes,
vec![0x00, 0x02, 0x00, 0x00, 0x00, 0x0A, 0x00, 0x00, 0x00, 0x0B]
);
println!("WithCount (2 items): OK");
// ── WithCount with items decode ──
let decoded: WithCount = dec(&bytes, State::Handshake);
assert_eq!(decoded.items, vec![0x0A, 0x0B]);
println!("WithCount (2 items) decode: OK");
// ── WithCondition encode ──
let cond_false = WithCondition {
version: 1,
extra: None,
};
let bytes = enc(&cond_false, State::Handshake);
assert_eq!(bytes, vec![0x01]);
println!("WithCondition (v1, None): OK");
let cond_true = WithCondition {
version: 2,
extra: Some(0xDEAD),
};
let bytes = enc(&cond_true, State::Handshake);
assert_eq!(bytes, vec![0x02, 0xDE, 0xAD]);
println!("WithCondition (v2, Some): OK");
// ── Combined encode ──
let comb1 = Combined {
version: 1,
items: vec![42],
fallback: Some(99),
};
let bytes = enc(&comb1, State::Handshake);
assert_eq!(bytes, vec![0x01, 0x00, 0x01, 0x00, 0x00, 0x00, 0x2A]);
println!("Combined (items=[42]): OK");
let comb2 = Combined {
version: 1,
items: vec![],
fallback: Some(99),
};
let bytes = enc(&comb2, State::Handshake);
assert_eq!(bytes, vec![0x01, 0x00, 0x00, 0x63]);
println!("Combined (items=[], fallback): OK");
// ── BasicEnum encode ──
let e_a = BasicEnum::A(0xFF);
let bytes = enc(&e_a, State::Handshake);
assert_eq!(bytes, vec![0x00, 0xFF]);
println!("Enum::A encode: OK");
let e_b = BasicEnum::B { x: 1, y: 2 };
let bytes = enc(&e_b, State::Handshake);
assert_eq!(bytes, vec![0x01, 0x00, 0x01, 0x00, 0x02]);
println!("Enum::B encode: OK");
let e_c = BasicEnum::C;
let bytes = enc(&e_c, State::Handshake);
assert_eq!(bytes, vec![0x02]);
println!("Enum::C encode: OK");
// ── BasicEnum decode ──
let decoded: BasicEnum = dec(&[0x00, 0xFF], State::Handshake);
assert!(matches!(decoded, BasicEnum::A(0xFF)));
println!("Enum::A decode: OK");
let decoded: BasicEnum = dec(&[0x01, 0x00, 0x01, 0x00, 0x02], State::Handshake);
assert!(matches!(decoded, BasicEnum::B { x: 1, y: 2 }));
println!("Enum::B decode: OK");
let decoded: BasicEnum = dec(&[0x02], State::Handshake);
assert!(matches!(decoded, BasicEnum::C));
println!("Enum::C decode: OK");
// ── CustomIdEnum encode ──
let bytes = enc(&CustomIdEnum::Alpha(42), State::Handshake);
assert_eq!(bytes, vec![0x10, 42]);
println!("CustomIdEnum::Alpha: OK");
let bytes = enc(&CustomIdEnum::Beta { val: 1234 }, State::Handshake);
assert_eq!(bytes, vec![0x20, 0x04, 0xD2]);
println!("CustomIdEnum::Beta: OK");
let bytes = enc(&CustomIdEnum::Gamma, State::Handshake);
assert_eq!(bytes, vec![0x30]);
println!("CustomIdEnum::Gamma: OK");
// ── CustomIdEnum decode ──
let decoded: CustomIdEnum = dec(&[0x10, 42], State::Handshake);
assert!(matches!(decoded, CustomIdEnum::Alpha(42)));
println!("CustomIdEnum decode Alpha: OK");
let decoded: CustomIdEnum = dec(&[0x20, 0x04, 0xD2], State::Handshake);
assert!(matches!(decoded, CustomIdEnum::Beta { val: 1234 }));
println!("CustomIdEnum decode Beta: OK");
let decoded: CustomIdEnum = dec(&[0x30], State::Handshake);
assert!(matches!(decoded, CustomIdEnum::Gamma));
println!("CustomIdEnum decode Gamma: OK");
// ── Context-aware enum encode ──
// Handshake state → ID 0x00 encodes Handshake
let bytes = enc(&Packet::Handshake(42), State::Handshake);
assert_eq!(bytes, vec![0x00, 0x00, 0x2A]);
println!("Packet Handshake encode: OK ({:02x?}", bytes);
// Status state → ID 0x00 encodes Status
let bytes = enc(&Packet::Status(1000), State::Status);
assert_eq!(bytes, vec![0x00, 0x00, 0x00, 0x03, 0xE8]);
println!("Packet Status encode: OK ({:02x?}", bytes);
// Play state → ID 0x01 encodes PlayData
let bytes = enc(&Packet::PlayData(1, 2), State::Play);
assert_eq!(bytes, vec![0x01, 0x01, 0x02]);
println!("Packet PlayData encode: OK ({:02x?}", bytes);
// Ping → always valid (no condition)
let bytes = enc(&Packet::Ping, State::Handshake);
assert_eq!(bytes, vec![0x02]);
println!("Packet Ping encode: OK");
// ── Context-aware: wrong state → error ──
let result = std::panic::catch_unwind(|| enc(&Packet::Handshake(42), State::Status));
assert!(result.is_err(), "should panic: Handshake in Status state");
println!("Packet Handshake in Status state: correctly errors");
let result = std::panic::catch_unwind(|| enc(&Packet::Status(1000), State::Play));
assert!(result.is_err(), "should panic: Status in Play state");
println!("Packet Status in Play state: correctly errors");
// ── Context-aware enum decode ──
// ID 0x00 in Handshake state → Handshake
let decoded: Packet = dec(&[0x00, 0x00, 0x2A], State::Handshake);
assert!(matches!(decoded, Packet::Handshake(42)));
println!("Packet decode Handshake: OK");
// ID 0x00 in Status state → Status
let decoded: Packet = dec(&[0x00, 0x00, 0x00, 0x03, 0xE8], State::Status);
assert!(matches!(decoded, Packet::Status(1000)));
println!("Packet decode Status: OK");
// ID 0x01 in Play state → PlayData
let decoded: Packet = dec(&[0x01, 0x01, 0x02], State::Play);
assert!(matches!(decoded, Packet::PlayData(1, 2)));
println!("Packet decode PlayData: OK");
// ID 0x02 → Ping (always valid)
let decoded: Packet = dec(&[0x02], State::Handshake);
assert!(matches!(decoded, Packet::Ping));
println!("Packet decode Ping: OK");
// ── Context-aware decode: wrong state → error ──
let result: Result<Packet, _> = {
let ctx = Context::new(Ctx {
state: State::Status,
});
let mut reader = &[0x00, 0x00, 0x2A][..];
Packet::decode(&mut reader, &ctx)
};
assert!(
result.is_err(),
"should error: ID 0x00 in Status decodes as Status, not Handshake"
);
println!("Packet decode wrong context: correctly errors");
// ── WithSkipVariant encode ──
let bytes = enc(&WithSkipVariant::Visible(42), State::Handshake);
assert_eq!(bytes, vec![0x00, 42]);
println!("WithSkipVariant::Visible encode: OK");
let bytes = enc(&WithSkipVariant::AlsoVisible, State::Handshake);
assert_eq!(bytes, vec![0x01]);
println!("WithSkipVariant::AlsoVisible encode: OK");
// ── WithSkipVariant decode ──
let decoded: WithSkipVariant = dec(&[0x00, 42], State::Handshake);
assert!(matches!(decoded, WithSkipVariant::Visible(42)));
println!("WithSkipVariant decode Visible: OK");
let decoded: WithSkipVariant = dec(&[0x01], State::Handshake);
assert!(matches!(decoded, WithSkipVariant::AlsoVisible));
println!("WithSkipVariant decode AlsoVisible: OK");
// Unknown discriminant → error
let result: Result<WithSkipVariant, _> = {
let ctx = Context::new(Ctx {
state: State::Handshake,
});
let mut reader = &[0xFF][..];
WithSkipVariant::decode(&mut reader, &ctx)
};
assert!(result.is_err(), "should error on unknown discriminant");
println!("WithSkipVariant unknown discriminant: correctly errors");
// ── Codec derive test ──
let codec_val = CodecStruct {
id: 0x42,
items: vec![1, 2, 3],
};
let bytes = enc(&codec_val, State::Handshake);
assert_eq!(bytes, vec![0x42, 0x03, 0x00, 0x01, 0x00, 0x02, 0x00, 0x03]);
println!("CodecStruct encode: OK");
let decoded: CodecStruct = dec(&bytes, State::Handshake);
assert_eq!(decoded.id, 0x42);
assert_eq!(decoded.items, vec![1, 2, 3]);
println!("CodecStruct decode: OK");
println!("\nAll tests passed!");
}
|