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
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
use ::core::future::Future;
use ::core::mem;
use ::core::str;

use std::sync::Arc;

use leb128_tokio::{AsyncReadLeb128, Leb128DecoderU32, Leb128Encoder};
use tokio::io::{AsyncRead, AsyncReadExt as _, AsyncWrite, AsyncWriteExt as _};
use tokio_util::bytes::{BufMut as _, Bytes, BytesMut};
use tokio_util::codec::{Decoder, Encoder};

pub trait AsyncReadCore: AsyncRead {
    /// Read [`core:name`](https://webassembly.github.io/spec/core/binary/values.html#names)
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(level = "trace", ret, skip_all, fields(ty = "name"))
    )]
    fn read_core_name(&mut self, s: &mut String) -> impl Future<Output = std::io::Result<()>>
    where
        Self: Unpin + Sized,
    {
        async move {
            let n = self.read_u32_leb128().await?;
            s.reserve(n.try_into().unwrap_or(usize::MAX));
            self.take(n.into()).read_to_string(s).await?;
            Ok(())
        }
    }
}

impl<T: AsyncRead> AsyncReadCore for T {}

pub trait AsyncWriteCore: AsyncWrite {
    /// Write [`core:name`](https://webassembly.github.io/spec/core/binary/values.html#names)
    #[cfg_attr(
        feature = "tracing",
        tracing::instrument(level = "trace", ret, skip_all, fields(ty = "name"))
    )]
    fn write_core_name(&mut self, s: &str) -> impl Future<Output = std::io::Result<()>>
    where
        Self: Unpin,
    {
        async move {
            let mut buf = BytesMut::with_capacity(5usize.saturating_add(s.len()));
            CoreNameEncoder.encode(s, &mut buf)?;
            self.write_all(&buf).await
        }
    }
}

impl<T: AsyncWrite> AsyncWriteCore for T {}

/// [`core:name`](https://webassembly.github.io/spec/core/binary/values.html#names) encoder
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct CoreNameEncoder;

impl<T: AsRef<str>> Encoder<T> for CoreNameEncoder {
    type Error = std::io::Error;

    fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> {
        let item = item.as_ref();
        let len = item.len();
        let n: u32 = len
            .try_into()
            .map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidInput, e))?;
        dst.reserve(len + 5 - n.leading_zeros() as usize / 7);
        Leb128Encoder.encode(n, dst)?;
        dst.put(item.as_bytes());
        Ok(())
    }
}

/// [`core:name`](https://webassembly.github.io/spec/core/binary/values.html#names) decoder
#[derive(Debug, Default)]
pub struct CoreNameDecoder(CoreVecDecoderBytes);

impl Decoder for CoreNameDecoder {
    type Item = String;
    type Error = std::io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        let Some(buf) = self.0.decode(src)? else {
            return Ok(None);
        };
        let s = str::from_utf8(&buf)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidData, err))?;
        Ok(Some(s.to_string()))
    }
}

/// [`core:vec`](https://webassembly.github.io/spec/core/binary/conventions.html#binary-vec) encoder
pub struct CoreVecEncoder<E>(pub E);

impl<E, T, const N: usize> Encoder<[T; N]> for CoreVecEncoder<E>
where
    E: Encoder<T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: [T; N], dst: &mut BytesMut) -> Result<(), Self::Error> {
        dst.reserve(5 + N);
        let len = u32::try_from(N)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
        Leb128Encoder.encode(len, dst)?;
        for item in item {
            self.0.encode(item, dst)?;
        }
        Ok(())
    }
}

impl<E, T> Encoder<Vec<T>> for CoreVecEncoder<E>
where
    E: Encoder<T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: Vec<T>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        let len = item.len();
        dst.reserve(5 + len);
        let len = u32::try_from(len)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
        Leb128Encoder.encode(len, dst)?;
        for item in item {
            self.0.encode(item, dst)?;
        }
        Ok(())
    }
}

impl<E, T> Encoder<Box<[T]>> for CoreVecEncoder<E>
where
    E: Encoder<T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: Box<[T]>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(Vec::from(item), dst)
    }
}

impl<'a, E, T, const N: usize> Encoder<&'a [T; N]> for CoreVecEncoder<E>
where
    E: Encoder<&'a T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: &'a [T; N], dst: &mut BytesMut) -> Result<(), Self::Error> {
        dst.reserve(5 + N);
        let len = u32::try_from(N)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
        Leb128Encoder.encode(len, dst)?;
        for item in item {
            self.0.encode(item, dst)?;
        }
        Ok(())
    }
}

impl<'a, E, T> Encoder<&'a [T]> for CoreVecEncoder<E>
where
    E: Encoder<&'a T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: &'a [T], dst: &mut BytesMut) -> Result<(), Self::Error> {
        let len = item.len();
        dst.reserve(5 + len);
        let len = u32::try_from(len)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
        Leb128Encoder.encode(len, dst)?;
        for item in item {
            self.0.encode(item, dst)?;
        }
        Ok(())
    }
}

impl<'a, 'b, E, T> Encoder<&'a &'b [T]> for CoreVecEncoder<E>
where
    E: Encoder<&'b T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: &'a &'b [T], dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(*item, dst)
    }
}

impl<'a, E, T> Encoder<&'a Vec<T>> for CoreVecEncoder<E>
where
    E: Encoder<&'a T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: &'a Vec<T>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(item.as_slice(), dst)
    }
}

impl<'a, 'b, E, T> Encoder<&'a &'b Vec<T>> for CoreVecEncoder<E>
where
    E: Encoder<&'b T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: &'a &'b Vec<T>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        self.encode(item.as_slice(), dst)
    }
}

impl<'a, E, T> Encoder<&'a Box<[T]>> for CoreVecEncoder<E>
where
    E: Encoder<&'a T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: &'a Box<[T]>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        let item: &[T] = item.as_ref();
        self.encode(item, dst)
    }
}

impl<E, T> Encoder<Arc<[T]>> for CoreVecEncoder<E>
where
    for<'a> E: Encoder<&'a T>,
    for<'a> std::io::Error: From<<E as Encoder<&'a T>>::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: Arc<[T]>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        let item = item.as_ref();
        let len = item.len();
        dst.reserve(5 + len);
        let len = u32::try_from(len)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
        Leb128Encoder.encode(len, dst)?;
        for item in item {
            self.0.encode(item, dst)?;
        }
        Ok(())
    }
}

impl<'a, E, T> Encoder<&'a Arc<[T]>> for CoreVecEncoder<E>
where
    E: Encoder<&'a T>,
    std::io::Error: From<E::Error>,
{
    type Error = std::io::Error;

    fn encode(&mut self, item: &'a Arc<[T]>, dst: &mut BytesMut) -> Result<(), Self::Error> {
        let item: &[T] = item.as_ref();
        self.encode(item, dst)
    }
}

/// [`core:vec`](https://webassembly.github.io/spec/core/binary/conventions.html#binary-vec) decoder
#[derive(Debug)]
pub struct CoreVecDecoder<T: Decoder> {
    dec: T,
    ret: Vec<T::Item>,
    cap: usize,
}

impl<T> CoreVecDecoder<T>
where
    T: Decoder,
{
    pub fn new(decoder: T) -> Self {
        Self {
            dec: decoder,
            ret: Vec::default(),
            cap: 0,
        }
    }

    pub fn into_inner(self) -> T {
        self.dec
    }
}

impl<T> Default for CoreVecDecoder<T>
where
    T: Decoder + Default,
{
    fn default() -> Self {
        Self::new(T::default())
    }
}

impl<T> Decoder for CoreVecDecoder<T>
where
    T: Decoder,
{
    type Item = Vec<T::Item>;
    type Error = T::Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        if self.cap == 0 {
            let Some(len) = Leb128DecoderU32.decode(src)? else {
                return Ok(None);
            };
            if len == 0 {
                return Ok(Some(Vec::default()));
            }
            let len = len
                .try_into()
                .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
            self.ret = Vec::with_capacity(len);
            self.cap = len;
        }
        while self.cap > 0 {
            let Some(v) = self.dec.decode(src)? else {
                return Ok(None);
            };
            self.ret.push(v);
            self.cap -= 1;
        }
        Ok(Some(mem::take(&mut self.ret)))
    }
}

/// [`core:vec`](https://webassembly.github.io/spec/core/binary/conventions.html#binary-vec)
/// encoder optimized for vectors of byte-sized values
#[derive(Copy, Clone, Debug, Default, Eq, PartialEq)]
pub struct CoreVecEncoderBytes;

impl<T: AsRef<[u8]>> Encoder<T> for CoreVecEncoderBytes {
    type Error = std::io::Error;

    fn encode(&mut self, item: T, dst: &mut BytesMut) -> Result<(), Self::Error> {
        let item = item.as_ref();
        let n = item.len();
        let n = u32::try_from(n)
            .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
        dst.reserve(item.len().saturating_add(5));
        Leb128Encoder.encode(n, dst)?;
        dst.extend_from_slice(item);
        Ok(())
    }
}

/// [`core:vec`](https://webassembly.github.io/spec/core/binary/conventions.html#binary-vec)
/// decoder optimized for vectors of byte-sized values
#[derive(Debug, Default)]
pub struct CoreVecDecoderBytes(usize);

impl Decoder for CoreVecDecoderBytes {
    type Item = Bytes;
    type Error = std::io::Error;

    fn decode(&mut self, src: &mut BytesMut) -> Result<Option<Self::Item>, Self::Error> {
        if self.0 == 0 {
            let Some(len) = Leb128DecoderU32.decode(src)? else {
                return Ok(None);
            };
            if len == 0 {
                return Ok(Some(Bytes::default()));
            }
            let len = len
                .try_into()
                .map_err(|err| std::io::Error::new(std::io::ErrorKind::InvalidInput, err))?;
            self.0 = len;
        }
        let n = self.0.saturating_sub(src.len());
        if n > 0 {
            src.reserve(n);
            return Ok(None);
        }
        let buf = src.split_to(self.0);
        self.0 = 0;
        Ok(Some(buf.freeze()))
    }
}

#[cfg(test)]
mod tests {
    use futures::{SinkExt as _, TryStreamExt as _};
    use tokio_util::codec::{FramedRead, FramedWrite};
    use tracing::trace;

    use super::*;

    #[test_log::test(tokio::test)]
    async fn string() {
        let mut s = String::new();
        "\x04test"
            .as_bytes()
            .read_core_name(&mut s)
            .await
            .expect("failed to read string");
        assert_eq!(s, "test");

        let mut buf = vec![];
        buf.write_core_name("test")
            .await
            .expect("failed to write string");
        assert_eq!(buf, b"\x04test");

        let mut tx = FramedWrite::new(Vec::new(), CoreNameEncoder);

        trace!("sending `foo`");
        tx.send("foo").await.expect("failed to send `foo`");

        trace!("sending ``");
        tx.send(String::default()).await.expect("failed to send ``");

        trace!("sending `test`");
        tx.send(&&&&&&"test").await.expect("failed to send `test`");

        trace!("sending `bar`");
        tx.send(Arc::from("bar"))
            .await
            .expect("failed to send `bar`");

        trace!("sending `ƒ𐍈Ő`");
        tx.send(&&String::from("ƒ𐍈Ő"))
            .await
            .expect("failed to send `ƒ𐍈Ő`");

        trace!("sending `baz`");
        tx.send(&&&Arc::from("baz"))
            .await
            .expect("failed to send `baz`");

        let tx = tx.into_inner();
        assert_eq!(
            tx,
            concat!("\x03foo", "\0", "\x04test", "\x03bar", "\x08ƒ𐍈Ő", "\x03baz").as_bytes()
        );
        let mut rx = FramedRead::new(tx.as_slice(), CoreNameDecoder::default());

        trace!("reading `foo`");
        let s = rx.try_next().await.expect("failed to get `foo`");
        assert_eq!(s.as_deref(), Some("foo"));

        trace!("reading ``");
        let s = rx.try_next().await.expect("failed to get ``");
        assert_eq!(s.as_deref(), Some(""));

        trace!("reading `test`");
        let s = rx.try_next().await.expect("failed to get `test`");
        assert_eq!(s.as_deref(), Some("test"));

        trace!("reading `bar`");
        let s = rx.try_next().await.expect("failed to get `bar`");
        assert_eq!(s.as_deref(), Some("bar"));

        trace!("reading `ƒ𐍈Ő`");
        let s = rx.try_next().await.expect("failed to get `ƒ𐍈Ő`");
        assert_eq!(s.as_deref(), Some("ƒ𐍈Ő"));

        trace!("reading `baz`");
        let s = rx.try_next().await.expect("failed to get `baz`");
        assert_eq!(s.as_deref(), Some("baz"));

        let s = rx.try_next().await.expect("failed to get EOF");
        assert_eq!(s, None);
    }

    #[test_log::test(tokio::test)]
    async fn vec() {
        let mut tx = FramedWrite::new(Vec::new(), CoreVecEncoder(CoreNameEncoder));

        trace!("sending [`foo`, ``, `test`, `bar`, `ƒ𐍈Ő`, `baz`]");
        tx.send(&["foo", "", "test", "bar", "ƒ𐍈Ő", "baz"])
            .await
            .expect("failed to send [`foo`, ``, `test`, `bar`, `ƒ𐍈Ő`, `baz`]");

        trace!("sending [``]");
        tx.send(&[""; 0]).await.expect("failed to send []");

        trace!("sending [`test`]");
        tx.send(&["test"]).await.expect("failed to send [`test`]");

        trace!("sending [``]");
        tx.send(&[""; 0]).await.expect("failed to send []");

        let tx = tx.into_inner();
        assert_eq!(
            tx,
            concat!(
                concat!(
                    "\x06",
                    concat!("\x03foo", "\0", "\x04test", "\x03bar", "\x08ƒ𐍈Ő", "\x03baz")
                ),
                "\0",
                concat!("\x01", "\x04test"),
                "\0"
            )
            .as_bytes()
        );
        let mut rx = FramedRead::new(tx.as_slice(), CoreVecDecoder::<CoreNameDecoder>::default());

        trace!("reading [`foo`, ``, `test`, `bar`, `baz`]");
        let s = rx
            .try_next()
            .await
            .expect("failed to get [`foo`, ``, `test`, `bar`, `baz`]");
        assert_eq!(
            s.as_deref(),
            Some(
                [
                    "foo".to_string(),
                    String::new(),
                    "test".to_string(),
                    "bar".to_string(),
                    "ƒ𐍈Ő".to_string(),
                    "baz".to_string()
                ]
                .as_slice()
            )
        );

        trace!("reading []");
        let s = rx.try_next().await.expect("failed to get []");
        assert_eq!(s.as_deref(), Some([].as_slice()));

        trace!("reading [`test`]");
        let s = rx.try_next().await.expect("failed to get [`test`]");
        assert_eq!(s.as_deref(), Some(["test".to_string()].as_slice()));

        trace!("reading []");
        let s = rx.try_next().await.expect("failed to get []");
        assert_eq!(s.as_deref(), Some([].as_slice()));

        let s = rx.try_next().await.expect("failed to get EOF");
        assert_eq!(s, None);
    }
}