1
#[allow(unused_imports)]
2
use tokio::time::sleep;
3
use {
4
    jetstream_9p::*,
5
    jetstream_macros::JetStreamWireFormat,
6
    jetstream_wireformat::*,
7
    std::{
8
        io::{self, Cursor},
9
        mem,
10
        pin::Pin,
11
        string::String,
12
        time::Duration,
13
    },
14
    tokio::io::{AsyncRead, AsyncWrite},
15
    wire_format_extensions::tokio::AsyncWireFormatExt,
16
};
17

            
18
use wire_format_extensions::ConvertWireFormat;
19

            
20
#[test]
21
2
fn integer_byte_size() {
22
2
    assert_eq!(1, 0u8.byte_size());
23
2
    assert_eq!(2, 0u16.byte_size());
24
2
    assert_eq!(4, 0u32.byte_size());
25
2
    assert_eq!(8, 0u64.byte_size());
26
2
}
27

            
28
#[test]
29
2
fn integer_decode() {
30
2
    let buf: [u8; 8] = [0xef, 0xbe, 0xad, 0xde, 0x0d, 0xf0, 0xad, 0x8b];
31
2

            
32
2
    assert_eq!(0xef_u8, u8::decode(&mut Cursor::new(&buf)).unwrap());
33
2
    assert_eq!(0xbeef_u16, u16::decode(&mut Cursor::new(&buf)).unwrap());
34
2
    assert_eq!(0xdeadbeef_u32, u32::decode(&mut Cursor::new(&buf)).unwrap());
35
2
    assert_eq!(
36
2
        0x8bad_f00d_dead_beef_u64,
37
2
        u64::decode(&mut Cursor::new(&buf)).unwrap()
38
2
    );
39
2
}
40

            
41
#[test]
42
2
fn integer_encode() {
43
2
    let value: u64 = 0x8bad_f00d_dead_beef;
44
2
    let expected: [u8; 8] = [0xef, 0xbe, 0xad, 0xde, 0x0d, 0xf0, 0xad, 0x8b];
45
2

            
46
2
    let mut buf = vec![0; 8];
47
2

            
48
2
    (value as u8).encode(&mut Cursor::new(&mut *buf)).unwrap();
49
2
    assert_eq!(expected[0..1], buf[0..1]);
50

            
51
2
    (value as u16).encode(&mut Cursor::new(&mut *buf)).unwrap();
52
2
    assert_eq!(expected[0..2], buf[0..2]);
53

            
54
2
    (value as u32).encode(&mut Cursor::new(&mut *buf)).unwrap();
55
2
    assert_eq!(expected[0..4], buf[0..4]);
56

            
57
2
    value.encode(&mut Cursor::new(&mut *buf)).unwrap();
58
2
    assert_eq!(expected[0..8], buf[0..8]);
59
2
}
60

            
61
#[test]
62
2
fn string_byte_size() {
63
2
    let values = [
64
2
        String::from("Google Video"),
65
2
        String::from("网页 图片 资讯更多 »"),
66
2
        String::from("Παγκόσμιος Ιστός"),
67
2
        String::from("Поиск страниц на русском"),
68
2
        String::from("전체서비스"),
69
2
    ];
70
2

            
71
2
    let exp = values
72
2
        .iter()
73
11
        .map(|v| (mem::size_of::<u16>() + v.len()) as u32);
74

            
75
10
    for (value, expected) in values.iter().zip(exp) {
76
10
        assert_eq!(expected, value.byte_size());
77
    }
78
2
}
79

            
80
#[test]
81
2
fn zero_length_string() {
82
2
    let s = String::from("");
83
2
    assert_eq!(s.byte_size(), mem::size_of::<u16>() as u32);
84

            
85
2
    let mut buf = [0xffu8; 4];
86
2

            
87
2
    s.encode(&mut Cursor::new(&mut buf[..]))
88
2
        .expect("failed to encode empty string");
89
2
    assert_eq!(&[0, 0, 0xff, 0xff], &buf);
90

            
91
2
    assert_eq!(
92
2
        s,
93
2
        <String as WireFormat>::decode(&mut Cursor::new(&[0, 0, 0x61, 0x61][..]))
94
2
            .expect("failed to decode empty string")
95
2
    );
96
2
}
97

            
98
#[test]
99
2
fn string_encode() {
100
2
    let values = [
101
2
        String::from("Google Video"),
102
2
        String::from("网页 图片 资讯更多 »"),
103
2
        String::from("Παγκόσμιος Ιστός"),
104
2
        String::from("Поиск страниц на русском"),
105
2
        String::from("전체서비스"),
106
2
    ];
107
2

            
108
11
    let expected = values.iter().map(|v| {
109
10
        let len = v.len();
110
10
        let mut buf = Vec::with_capacity(len + mem::size_of::<u16>());
111
10

            
112
10
        buf.push(len as u8);
113
10
        buf.push((len >> 8) as u8);
114
10

            
115
10
        buf.extend_from_slice(v.as_bytes());
116
10

            
117
10
        buf
118
11
    });
119

            
120
10
    for (val, exp) in values.iter().zip(expected) {
121
10
        let mut buf = vec![0; exp.len()];
122
10

            
123
10
        WireFormat::encode(val, &mut Cursor::new(&mut *buf)).unwrap();
124
10
        assert_eq!(exp, buf);
125
    }
126
2
}
127

            
128
#[test]
129
2
fn string_decode() {
130
2
    assert_eq!(
131
2
        String::from("Google Video"),
132
2
        <String as WireFormat>::decode(&mut Cursor::new(
133
2
            &[0x0c, 0x00, 0x47, 0x6F, 0x6F, 0x67, 0x6C, 0x65, 0x20, 0x56, 0x69, 0x64, 0x65, 0x6F,]
134
2
                [..]
135
2
        ))
136
2
        .unwrap()
137
2
    );
138
2
    assert_eq!(
139
2
        String::from("网页 图片 资讯更多 »"),
140
2
        <String as WireFormat>::decode(&mut Cursor::new(
141
2
            &[
142
2
                0x1d, 0x00, 0xE7, 0xBD, 0x91, 0xE9, 0xA1, 0xB5, 0x20, 0xE5, 0x9B, 0xBE, 0xE7, 0x89,
143
2
                0x87, 0x20, 0xE8, 0xB5, 0x84, 0xE8, 0xAE, 0xAF, 0xE6, 0x9B, 0xB4, 0xE5, 0xA4, 0x9A,
144
2
                0x20, 0xC2, 0xBB,
145
2
            ][..]
146
2
        ))
147
2
        .unwrap()
148
2
    );
149
2
    assert_eq!(
150
2
        String::from("Παγκόσμιος Ιστός"),
151
2
        <String as WireFormat>::decode(&mut Cursor::new(
152
2
            &[
153
2
                0x1f, 0x00, 0xCE, 0xA0, 0xCE, 0xB1, 0xCE, 0xB3, 0xCE, 0xBA, 0xCF, 0x8C, 0xCF, 0x83,
154
2
                0xCE, 0xBC, 0xCE, 0xB9, 0xCE, 0xBF, 0xCF, 0x82, 0x20, 0xCE, 0x99, 0xCF, 0x83, 0xCF,
155
2
                0x84, 0xCF, 0x8C, 0xCF, 0x82,
156
2
            ][..]
157
2
        ))
158
2
        .unwrap()
159
2
    );
160
2
    assert_eq!(
161
2
        String::from("Поиск страниц на русском"),
162
2
        <String as WireFormat>::decode(&mut Cursor::new(
163
2
            &[
164
2
                0x2d, 0x00, 0xD0, 0x9F, 0xD0, 0xBE, 0xD0, 0xB8, 0xD1, 0x81, 0xD0, 0xBA, 0x20, 0xD1,
165
2
                0x81, 0xD1, 0x82, 0xD1, 0x80, 0xD0, 0xB0, 0xD0, 0xBD, 0xD0, 0xB8, 0xD1, 0x86, 0x20,
166
2
                0xD0, 0xBD, 0xD0, 0xB0, 0x20, 0xD1, 0x80, 0xD1, 0x83, 0xD1, 0x81, 0xD1, 0x81, 0xD0,
167
2
                0xBA, 0xD0, 0xBE, 0xD0, 0xBC,
168
2
            ][..]
169
2
        ))
170
2
        .unwrap()
171
2
    );
172
2
    assert_eq!(
173
2
        String::from("전체서비스"),
174
2
        <String as WireFormat>::decode(&mut Cursor::new(
175
2
            &[
176
2
                0x0f, 0x00, 0xEC, 0xA0, 0x84, 0xEC, 0xB2, 0xB4, 0xEC, 0x84, 0x9C, 0xEB, 0xB9, 0x84,
177
2
                0xEC, 0x8A, 0xA4,
178
2
            ][..]
179
2
        ))
180
2
        .unwrap()
181
2
    );
182
2
}
183

            
184
#[test]
185
2
fn invalid_string_decode() {
186
2
    let _ = <String as WireFormat>::decode(&mut Cursor::new(&[
187
2
        0x06, 0x00, 0xed, 0xa0, 0x80, 0xed, 0xbf, 0xbf,
188
2
    ]))
189
2
    .expect_err("surrogate code point");
190
2

            
191
2
    let _ = <String as WireFormat>::decode(&mut Cursor::new(&[
192
2
        0x05, 0x00, 0xf8, 0x80, 0x80, 0x80, 0xbf,
193
2
    ]))
194
2
    .expect_err("overlong sequence");
195
2

            
196
2
    let _ = <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0xf4, 0x90, 0x80, 0x80]))
197
2
        .expect_err("out of range");
198
2

            
199
2
    let _ = <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0x63, 0x61, 0x66, 0xe9]))
200
2
        .expect_err("ISO-8859-1");
201
2

            
202
2
    let _ = <String as WireFormat>::decode(&mut Cursor::new(&[0x04, 0x00, 0xb0, 0xa1, 0xb0, 0xa2]))
203
2
        .expect_err("EUC-KR");
204
2
}
205

            
206
#[test]
207
2
fn vector_encode() {
208
2
    let values: Vec<u32> = vec![291, 18_916, 2_497, 22, 797_162, 2_119_732, 3_213_929_716];
209
2
    let mut expected: Vec<u8> =
210
2
        Vec::with_capacity(values.len() * mem::size_of::<u32>() + mem::size_of::<u16>());
211
2
    expected.push(values.len() as u8);
212
2
    expected.push((values.len() >> 8) as u8);
213

            
214
    const MASK: u32 = 0xff;
215
16
    for val in &values {
216
14
        expected.push((val & MASK) as u8);
217
14
        expected.push(((val >> 8) & MASK) as u8);
218
14
        expected.push(((val >> 16) & MASK) as u8);
219
14
        expected.push(((val >> 24) & MASK) as u8);
220
14
    }
221

            
222
2
    let mut actual: Vec<u8> = vec![0; expected.len()];
223
2

            
224
2
    WireFormat::encode(&values, &mut Cursor::new(&mut *actual)).expect("failed to encode vector");
225
2
    assert_eq!(expected, actual);
226
2
}
227

            
228
#[test]
229
2
fn vector_decode() {
230
2
    let expected: Vec<u32> = vec![
231
2
        2_498,
232
2
        24,
233
2
        897,
234
2
        4_097_789_579,
235
2
        8_498_119,
236
2
        684_279,
237
2
        961_189_198,
238
2
        7,
239
2
    ];
240
2
    let mut input: Vec<u8> =
241
2
        Vec::with_capacity(expected.len() * mem::size_of::<u32>() + mem::size_of::<u16>());
242
2
    input.push(expected.len() as u8);
243
2
    input.push((expected.len() >> 8) as u8);
244

            
245
    const MASK: u32 = 0xff;
246
18
    for val in &expected {
247
16
        input.push((val & MASK) as u8);
248
16
        input.push(((val >> 8) & MASK) as u8);
249
16
        input.push(((val >> 16) & MASK) as u8);
250
16
        input.push(((val >> 24) & MASK) as u8);
251
16
    }
252

            
253
2
    assert_eq!(
254
2
        expected,
255
2
        <Vec<u32> as WireFormat>::decode(&mut Cursor::new(&*input))
256
2
            .expect("failed to decode vector")
257
2
    );
258
2
}
259

            
260
#[test]
261
2
fn data_encode() {
262
2
    let values = Data(vec![169, 155, 79, 67, 182, 199, 25, 73, 129, 200]);
263
2
    let mut expected: Vec<u8> =
264
2
        Vec::with_capacity(values.len() * mem::size_of::<u8>() + mem::size_of::<u32>());
265
2
    expected.push(values.len() as u8);
266
2
    expected.push((values.len() >> 8) as u8);
267
2
    expected.push((values.len() >> 16) as u8);
268
2
    expected.push((values.len() >> 24) as u8);
269
2
    expected.extend_from_slice(&values);
270
2

            
271
2
    let mut actual: Vec<u8> = vec![0; expected.len()];
272
2

            
273
2
    WireFormat::encode(&values, &mut Cursor::new(&mut *actual)).expect("failed to encode datar");
274
2
    assert_eq!(expected, actual);
275
2
}
276

            
277
#[test]
278
2
fn data_decode() {
279
2
    let expected = Data(vec![219, 15, 8, 155, 194, 129, 79, 91, 46, 53, 173]);
280
2
    let mut input: Vec<u8> =
281
2
        Vec::with_capacity(expected.len() * mem::size_of::<u8>() + mem::size_of::<u32>());
282
2
    input.push(expected.len() as u8);
283
2
    input.push((expected.len() >> 8) as u8);
284
2
    input.push((expected.len() >> 16) as u8);
285
2
    input.push((expected.len() >> 24) as u8);
286
2
    input.extend_from_slice(&expected);
287
2

            
288
2
    assert_eq!(
289
2
        expected,
290
2
        <Data as WireFormat>::decode(&mut Cursor::new(&mut *input)).expect("failed to decode data")
291
2
    );
292
2
}
293

            
294
#[test]
295
2
fn error_cases() {
296
2
    // string is too long.
297
2
    let mut long_str = String::with_capacity(u16::MAX as usize);
298
32770
    while long_str.len() < u16::MAX as usize {
299
32768
        long_str.push_str("long");
300
32768
    }
301
2
    long_str.push('!');
302
2

            
303
2
    let count = long_str.len() + mem::size_of::<u16>();
304
2
    let mut buf = vec![0; count];
305
2

            
306
2
    long_str
307
2
        .encode(&mut Cursor::new(&mut *buf))
308
2
        .expect_err("long string");
309
2

            
310
2
    // vector is too long.
311
2
    let mut long_vec: Vec<u32> = Vec::with_capacity(u16::MAX as usize);
312
131072
    while long_vec.len() < u16::MAX as usize {
313
131070
        long_vec.push(0x8bad_f00d);
314
131070
    }
315
2
    long_vec.push(0x00ba_b10c);
316
2

            
317
2
    let count = long_vec.len() * mem::size_of::<u32>();
318
2
    let mut buf = vec![0; count];
319
2

            
320
2
    WireFormat::encode(&long_vec, &mut Cursor::new(&mut *buf)).expect_err("long vector");
321
2
}
322

            
323
#[derive(Debug, PartialEq, JetStreamWireFormat)]
324
struct Item {
325
    a: u64,
326
    b: String,
327
    c: Vec<u16>,
328
    buf: Data,
329
}
330

            
331
#[test]
332
2
fn struct_encode() {
333
2
    let item = Item {
334
2
        a: 0xdead_10cc_00ba_b10c,
335
2
        b: String::from("冻住,不许走!"),
336
2
        c: vec![359, 492, 8891],
337
2
        buf: Data(vec![254, 129, 0, 62, 49, 172]),
338
2
    };
339
2

            
340
2
    let mut expected: Vec<u8> = vec![0x0c, 0xb1, 0xba, 0x00, 0xcc, 0x10, 0xad, 0xde];
341
2
    let strlen = item.b.len() as u16;
342
2
    expected.push(strlen as u8);
343
2
    expected.push((strlen >> 8) as u8);
344
2
    expected.extend_from_slice(item.b.as_bytes());
345
2

            
346
2
    let veclen = item.c.len() as u16;
347
2
    expected.push(veclen as u8);
348
2
    expected.push((veclen >> 8) as u8);
349
8
    for val in &item.c {
350
6
        expected.push(*val as u8);
351
6
        expected.push((val >> 8) as u8);
352
6
    }
353

            
354
2
    let buflen = item.buf.len() as u32;
355
2
    expected.push(buflen as u8);
356
2
    expected.push((buflen >> 8) as u8);
357
2
    expected.push((buflen >> 16) as u8);
358
2
    expected.push((buflen >> 24) as u8);
359
2
    expected.extend_from_slice(&item.buf);
360
2

            
361
2
    let mut actual = vec![0; expected.len()];
362
2

            
363
2
    WireFormat::encode(&item, &mut Cursor::new(&mut *actual)).expect("failed to encode item");
364
2

            
365
2
    assert_eq!(expected, actual);
366
2
}
367

            
368
#[test]
369
2
fn struct_decode() {
370
2
    let expected = Item {
371
2
        a: 0xface_b00c_0404_4b1d,
372
2
        b: String::from("Огонь по готовности!"),
373
2
        c: vec![20067, 32449, 549, 4972, 77, 1987],
374
2
        buf: Data(vec![126, 236, 79, 59, 6, 159]),
375
2
    };
376
2

            
377
2
    let mut input: Vec<u8> = vec![0x1d, 0x4b, 0x04, 0x04, 0x0c, 0xb0, 0xce, 0xfa];
378
2
    let strlen = expected.b.len() as u16;
379
2
    input.push(strlen as u8);
380
2
    input.push((strlen >> 8) as u8);
381
2
    input.extend_from_slice(expected.b.as_bytes());
382
2

            
383
2
    let veclen = expected.c.len() as u16;
384
2
    input.push(veclen as u8);
385
2
    input.push((veclen >> 8) as u8);
386
14
    for val in &expected.c {
387
12
        input.push(*val as u8);
388
12
        input.push((val >> 8) as u8);
389
12
    }
390

            
391
2
    let buflen = expected.buf.len() as u32;
392
2
    input.push(buflen as u8);
393
2
    input.push((buflen >> 8) as u8);
394
2
    input.push((buflen >> 16) as u8);
395
2
    input.push((buflen >> 24) as u8);
396
2
    input.extend_from_slice(&expected.buf);
397
2

            
398
2
    let actual: Item = WireFormat::decode(&mut Cursor::new(input)).expect("failed to decode item");
399
2

            
400
2
    assert_eq!(expected, actual);
401
2
}
402

            
403
#[derive(Debug, PartialEq, JetStreamWireFormat)]
404
struct Nested {
405
    item: Item,
406
    val: Vec<u64>,
407
}
408

            
409
#[allow(clippy::vec_init_then_push)]
410
4
fn build_encoded_buffer(value: &Nested) -> Vec<u8> {
411
4
    let mut result: Vec<u8> = Vec::new();
412
4

            
413
4
    // encode a
414
4
    result.push(value.item.a as u8);
415
4
    result.push((value.item.a >> 8) as u8);
416
4
    result.push((value.item.a >> 16) as u8);
417
4
    result.push((value.item.a >> 24) as u8);
418
4
    result.push((value.item.a >> 32) as u8);
419
4
    result.push((value.item.a >> 40) as u8);
420
4
    result.push((value.item.a >> 48) as u8);
421
4
    result.push((value.item.a >> 56) as u8);
422
4

            
423
4
    // encode b
424
4
    result.push(value.item.b.len() as u8);
425
4
    result.push((value.item.b.len() >> 8) as u8);
426
4
    result.extend_from_slice(value.item.b.as_bytes());
427
4

            
428
4
    // encode c
429
4
    result.push(value.item.c.len() as u8);
430
4
    result.push((value.item.c.len() >> 8) as u8);
431
24
    for val in &value.item.c {
432
20
        result.push((val & 0xffu16) as u8);
433
20
        result.push(((val >> 8) & 0xffu16) as u8);
434
20
    }
435

            
436
    // encode buf
437
4
    result.push(value.item.buf.len() as u8);
438
4
    result.push((value.item.buf.len() >> 8) as u8);
439
4
    result.push((value.item.buf.len() >> 16) as u8);
440
4
    result.push((value.item.buf.len() >> 24) as u8);
441
4
    result.extend_from_slice(&value.item.buf);
442
4

            
443
4
    // encode val
444
4
    result.push(value.val.len() as u8);
445
4
    result.push((value.val.len() >> 8) as u8);
446
26
    for val in &value.val {
447
22
        result.push(*val as u8);
448
22
        result.push((val >> 8) as u8);
449
22
        result.push((val >> 16) as u8);
450
22
        result.push((val >> 24) as u8);
451
22
        result.push((val >> 32) as u8);
452
22
        result.push((val >> 40) as u8);
453
22
        result.push((val >> 48) as u8);
454
22
        result.push((val >> 56) as u8);
455
22
    }
456

            
457
4
    result
458
4
}
459

            
460
#[test]
461
2
fn nested_encode() {
462
2
    let value = Nested {
463
2
        item: Item {
464
2
            a: 0xcafe_d00d_8bad_f00d,
465
2
            b: String::from("龍が我が敵を喰らう!"),
466
2
            c: vec![2679, 55_919, 44, 38_819, 792],
467
2
            buf: Data(vec![129, 55, 200, 93, 7, 68]),
468
2
        },
469
2
        val: vec![1954978, 59, 4519, 15679],
470
2
    };
471
2

            
472
2
    let expected = build_encoded_buffer(&value);
473
2

            
474
2
    let mut actual = vec![0; expected.len()];
475
2

            
476
2
    WireFormat::encode(&value, &mut Cursor::new(&mut *actual)).expect("failed to encode value");
477
2
    assert_eq!(expected, actual);
478
2
}
479

            
480
#[test]
481
2
fn nested_decode() {
482
2
    let expected = Nested {
483
2
        item: Item {
484
2
            a: 0x0ff1ce,
485
2
            b: String::from("龍神の剣を喰らえ!"),
486
2
            c: vec![21687, 159, 55, 9217, 192],
487
2
            buf: Data(vec![189, 22, 7, 59, 235]),
488
2
        },
489
2
        val: vec![15679, 8619196, 319746, 123957, 77, 0, 492],
490
2
    };
491
2

            
492
2
    let input = build_encoded_buffer(&expected);
493
2

            
494
2
    assert_eq!(
495
2
        expected,
496
2
        <Nested as WireFormat>::decode(&mut Cursor::new(&*input)).expect("failed to decode value")
497
2
    );
498
2
}
499

            
500
#[test]
501
2
fn test_io_read_for_data() {
502
2
    let mut data = Data(vec![0x8b, 0xad, 0xf0, 0x0d, 0x0d, 0xf0, 0xad, 0x8b]);
503
2
    let mut buf = [0; 8];
504
2

            
505
2
    let _ = io::Read::read_exact(&mut data, &mut buf);
506
2

            
507
2
    assert_eq!(buf, [0x8b, 0xad, 0xf0, 0x0d, 0x0d, 0xf0, 0xad, 0x8b]);
508
2
}
509

            
510
struct BlockingIO<T: Sized + Unpin> {
511
    delay: Duration,
512
    inner: T,
513
}
514

            
515
impl BlockingIO<tokio::io::DuplexStream> {
516
    #[allow(dead_code)]
517
4
    fn new(delay: Duration, inner: tokio::io::DuplexStream) -> Self {
518
4
        Self { delay, inner }
519
4
    }
520
}
521

            
522
impl<T> AsyncRead for BlockingIO<T>
523
where
524
    T: AsyncRead + Unpin,
525
{
526
12
    fn poll_read(
527
12
        self: Pin<&mut Self>,
528
12
        cx: &mut std::task::Context<'_>,
529
12
        buf: &mut tokio::io::ReadBuf<'_>,
530
12
    ) -> std::task::Poll<io::Result<()>> {
531
12
        let delay = self.delay;
532
12

            
533
12
        // If there's a delay, we schedule a sleep before proceeding with the read.
534
12
        if delay > Duration::ZERO {
535
12
            // This future will complete after the specified delay.
536
12
            tokio::spawn(async move {
537
12
                sleep(delay).await;
538
12
            });
539
12
        }
540
12
        let this = self.get_mut();
541
12
        // Poll the inner AsyncRead.
542
12
        Pin::new(&mut this.inner).poll_read(cx, buf)
543
12
    }
544
}
545

            
546
impl<T> AsyncWrite for BlockingIO<T>
547
where
548
    T: AsyncWrite + Unpin,
549
{
550
12
    fn poll_write(
551
12
        self: Pin<&mut Self>,
552
12
        cx: &mut std::task::Context<'_>,
553
12
        buf: &[u8],
554
12
    ) -> std::task::Poll<io::Result<usize>> {
555
12
        let delay = self.delay;
556
12

            
557
12
        // If there's a delay, we schedule a sleep before proceeding with the write.
558
12
        if delay > Duration::ZERO {
559
12
            // This future will complete after the specified delay.
560
12
            tokio::spawn(async move {
561
12
                sleep(delay).await;
562
12
            });
563
12
        }
564
12
        let this = self.get_mut();
565
12
        // Poll the inner AsyncWrite.
566
12
        Pin::new(&mut this.inner).poll_write(cx, buf)
567
12
    }
568

            
569
    fn poll_flush(
570
        self: Pin<&mut Self>,
571
        cx: &mut std::task::Context<'_>,
572
    ) -> std::task::Poll<io::Result<()>> {
573
        let this = self.get_mut();
574
        Pin::new(&mut this.inner).poll_flush(cx)
575
    }
576

            
577
    fn poll_shutdown(
578
        self: Pin<&mut Self>,
579
        cx: &mut std::task::Context<'_>,
580
    ) -> std::task::Poll<io::Result<()>> {
581
        let this = self.get_mut();
582
        Pin::new(&mut this.inner).poll_shutdown(cx)
583
    }
584
}
585

            
586
#[tokio::test(flavor = "multi_thread")]
587
3
async fn test_async_wire_format() {
588
3
    let test = Tframe {
589
3
        tag: 0,
590
3
        msg: Ok(Tmessage::Version(Tversion {
591
3
            msize: 8192,
592
3
            version: "9P2000.L".to_string(),
593
3
        })),
594
3
    };
595
3

            
596
3
    let mut buf = Vec::new();
597
3
    test.encode_async(&mut buf).await.unwrap();
598
3
    let mut cursor = Cursor::new(buf);
599
3
    let decoded = Tframe::decode_async(&mut cursor).await.unwrap();
600
3
    assert_eq!(decoded.tag, 0);
601
2
}
602

            
603
#[tokio::test(flavor = "multi_thread")]
604
3
async fn test_async_wire_format_delayed() {
605
3
    let test = Tframe {
606
3
        tag: 0,
607
3
        msg: Ok(Tmessage::Version(Tversion {
608
3
            msize: 8192,
609
3
            version: "9P2000.L".to_string(),
610
3
        })),
611
3
    };
612
3

            
613
3
    let (upstream, downstream) = tokio::io::duplex(1024);
614
3
    let writer = BlockingIO::new(Duration::from_millis(1), upstream);
615
3
    let reader = BlockingIO::new(Duration::from_millis(1), downstream);
616
3

            
617
3
    test.encode_async(writer).await.unwrap();
618
3
    let decoded = Tframe::decode_async(reader).await.unwrap();
619
3
    assert_eq!(decoded.tag, 0);
620
2
}
621

            
622
#[test]
623
2
fn test_convert_wire_format() {
624
2
    let test = Tframe {
625
2
        tag: 0,
626
2
        msg: Ok(Tmessage::Version(Tversion {
627
2
            msize: 8192,
628
2
            version: "9P2000.L".to_string(),
629
2
        })),
630
2
    };
631
2

            
632
2
    let buf = test.to_bytes();
633
2
    let decoded = Tframe::from_bytes(&buf).unwrap();
634
2
    assert_eq!(decoded.tag, 0);
635
2
}
636
#[test]
637
2
fn test_option_none() {
638
2
    let value: Option<u32> = None;
639
2

            
640
2
    // Test byte size
641
2
    assert_eq!(value.byte_size(), 1);
642

            
643
    // Test encode
644
2
    let mut buf = Vec::new();
645
2
    value.encode(&mut buf).unwrap();
646
2
    assert_eq!(buf.len(), 1);
647
2
    assert_eq!(buf[0], 0);
648

            
649
    // Test decode
650
2
    let mut cursor = Cursor::new(buf);
651
2
    let decoded: Option<u32> = WireFormat::decode(&mut cursor).unwrap();
652
2
    assert_eq!(value, decoded);
653
2
}
654

            
655
#[test]
656
2
fn test_option_some() {
657
2
    let value = Some(42u32);
658
2

            
659
2
    // Test byte size
660
2
    assert_eq!(value.byte_size(), 5); // 1 byte tag + 4 bytes for u32
661

            
662
    // Test encode
663
2
    let mut buf = Vec::new();
664
2
    value.encode(&mut buf).unwrap();
665
2
    assert_eq!(buf.len(), 5);
666
2
    assert_eq!(buf[0], 1);
667

            
668
    // Test decode
669
2
    let mut cursor = Cursor::new(buf);
670
2
    let decoded: Option<u32> = WireFormat::decode(&mut cursor).unwrap();
671
2
    assert_eq!(value, decoded);
672
2
}
673

            
674
#[test]
675
2
fn test_option_invalid_tag() {
676
2
    let buf = vec![2u8]; // Invalid tag
677
2
    let mut cursor = Cursor::new(buf);
678
2
    let result: Result<Option<u32>, _> = WireFormat::decode(&mut cursor);
679
2
    assert!(result.is_err());
680
2
    if let Err(e) = result {
681
2
        assert_eq!(e.kind(), io::ErrorKind::InvalidData);
682
    }
683
2
}
684

            
685
#[test]
686
2
fn test_nested_option() {
687
2
    let value = Some(Some(42u32));
688
2

            
689
2
    // Test byte size
690
2
    assert_eq!(value.byte_size(), 6); // outer tag + inner tag + u32
691

            
692
    // Test encode/decode
693
2
    let mut buf = Vec::new();
694
2
    value.encode(&mut buf).unwrap();
695
2
    let mut cursor = Cursor::new(buf);
696
2
    let decoded: Option<Option<u32>> = WireFormat::decode(&mut cursor).unwrap();
697
2
    assert_eq!(value, decoded);
698
2
}
699

            
700
#[test]
701
2
fn test_bool_encode() {
702
2
    let mut buf = Vec::new();
703
2
    true.encode(&mut buf).unwrap();
704
2
    assert_eq!(buf, vec![1]);
705

            
706
2
    buf.clear();
707
2
    false.encode(&mut buf).unwrap();
708
2
    assert_eq!(buf, vec![0]);
709
2
}
710

            
711
#[test]
712
2
fn test_bool_decode() {
713
2
    let mut cursor = Cursor::new(vec![1]);
714
2
    let decoded: bool = WireFormat::decode(&mut cursor).unwrap();
715
2
    assert!(decoded);
716

            
717
2
    cursor = Cursor::new(vec![0]);
718
2
    let decoded: bool = WireFormat::decode(&mut cursor).unwrap();
719
2
    assert!(!decoded);
720
2
}
721

            
722
#[test]
723
2
fn test_bool_invalid_decode() {
724
2
    let mut cursor = Cursor::new(vec![2]);
725
2
    let result: Result<bool, _> = WireFormat::decode(&mut cursor);
726
2
    assert!(result.is_err());
727
2
    if let Err(e) = result {
728
2
        assert_eq!(e.kind(), io::ErrorKind::InvalidData);
729
    }
730
2
}