wa_proto/
protocol.rs

1//! Зачем разделили на Incoming и Outcoming?
2//! Конечно чаще всего структуры будут имплементировать оба трейта.
3//! Но иногда возможно какую то структуру будут передавать в wasm,
4//! но из wasm она не будет передаваться никогда. Тогда для этой
5//! структуры излишне имплементировать Outcoming.
6
7#[cfg(all(any(feature = "hashmap", feature = "std"), feature = "map"))]
8use crate::{FxBuildHasher, FxHashMap};
9#[cfg(not(feature = "std"))]
10use alloc::{boxed::Box, collections::BTreeMap, string::String, vec::Vec};
11#[cfg(feature = "chrono")]
12use chrono::{Date, DateTime, Datelike, Duration, NaiveDate, NaiveDateTime, Utc};
13#[cfg(feature = "std")]
14use core::fmt;
15#[cfg(not(feature = "std"))]
16use core::{convert::TryInto, slice::IterMut};
17#[cfg(all(not(feature = "std"), feature = "hashmap"))]
18use hashbrown::HashMap;
19#[cfg(feature = "std")]
20use std::{
21    cell::RefMut,
22    collections::{BTreeMap, HashMap},
23    convert::TryInto,
24    error::Error,
25    hash::Hash,
26    slice::Iter,
27    string::String,
28    vec::Vec,
29};
30
31// TODO: alignment memory of 32 bits?
32
33#[derive(Default)]
34#[cfg_attr(feature = "std", derive(Debug))]
35#[cfg(feature = "std")]
36pub struct ProtocolError(pub String);
37
38#[derive(Default)]
39#[cfg(not(feature = "std"))]
40pub struct ProtocolError(pub u32);
41
42#[cfg(feature = "std")]
43pub const ARGS_NEXT_ERROR: &str = "args next error";
44
45#[cfg(not(feature = "std"))]
46pub const ARGS_NEXT_ERROR: u32 = 2;
47
48pub const BYTES_INTO_ARR4_ERROR: u32 = 3;
49pub const BYTES_INTO_ARR8_ERROR: u32 = 4;
50pub const MAP_INSERT_ERROR: u32 = 5;
51pub const STRING_FROM_BYTES_ERROR: u32 = 6;
52
53#[cfg(feature = "std")]
54pub const ENUM_FROM_U32_ERROR: &str = "enum from u32 error";
55
56#[cfg(not(feature = "std"))]
57pub const ENUM_FROM_U32_ERROR: u32 = 7;
58
59pub const TIME_PARSE_ERROR: u32 = 8;
60
61#[cfg(feature = "std")]
62impl From<&str> for ProtocolError {
63    fn from(s: &str) -> Self {
64        ProtocolError(s.to_string())
65    }
66}
67
68#[cfg(feature = "std")]
69impl From<std::array::TryFromSliceError> for ProtocolError {
70    fn from(_: std::array::TryFromSliceError) -> Self {
71        ProtocolError("slice len error".to_string())
72    }
73}
74
75#[cfg(feature = "std")]
76impl From<std::string::FromUtf8Error> for ProtocolError {
77    fn from(_: std::string::FromUtf8Error) -> Self {
78        ProtocolError("utf-8 string bytes error".to_string())
79    }
80}
81
82#[cfg(feature = "std")]
83impl From<time::error::ComponentRange> for ProtocolError {
84    fn from(_: time::error::ComponentRange) -> Self {
85        ProtocolError("time from u32 error".to_string())
86    }
87}
88
89#[cfg(not(feature = "std"))]
90impl From<u32> for ProtocolError {
91    fn from(s: u32) -> Self {
92        ProtocolError(s)
93    }
94}
95
96#[cfg(feature = "std")]
97impl fmt::Display for ProtocolError {
98    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
99        if self.0.is_empty() {
100            write!(f, "Protocol error, can't transform")
101        } else {
102            write!(f, "Protocol error: {}", &self.0)
103        }
104    }
105}
106
107#[cfg(feature = "std")]
108impl Error for ProtocolError {}
109
110/**
111Incoming trait (Deserializable) - (Входящее сообщение) если структура реализует этот трейт,
112то значит что эту структуру можно передать в wasm.
113Внутри структуры находится информация:
114- о длине строки или массива
115- о типе варианта перечисления
116- и другие данные, которые помогут определить полностью сообщение.
117Важно одно ограничение - Структура должна быть построена на основе перечислений,
118а не на основе дженериков (или хранить внутри себя информацию о соответствущем дженерике)?
119Зачем это ограничение, если мы уже реализовали трейт для HashMap и Vec с дженериками?
120
121Будет в основном использоваться для передачи сообщений между wasm модулем и Rust рантаймом.
122Для сериализации и десериализации в БД рекомендуется использовать serde.
123T - тип, который сериализуем
124*/
125// #[cfg(all(target = "wasm32-unknown-unknown"))]
126pub trait Incoming<T = Self> {
127    /**
128    Указывает на то что необходимо инициализировать данные, а затем заполнить
129    если true - получается 2 шага
130    если false - 1 шаг
131     */
132    const IS_NEED_INIT_FILL: bool = false;
133
134    /**
135    Инициализируем кусок памяти в wasm для последующего заполнения.
136    Вызывается в wasm.
137    */
138    #[cfg(not(feature = "std"))]
139    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError>
140    where
141        Self: Sized;
142
143    /**
144    Добавление в аргументы вспомогательных данных,
145    таких как длина строки/массива и др.
146    Вызывается на хосте.
147    */
148    #[cfg(feature = "std")]
149    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError>;
150
151    /**
152    Заполнение данными инициализированный участок памяти.
153    вызывается на хосте.
154    Иногда инициализация не нужна, если значение можно полностью передать в аргументах,
155    уместить в значении u32.
156    */
157    #[cfg(feature = "std")]
158    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError>;
159}
160
161/**
162Outcoming trait (Serializable) - (Исходящее сообщение) если структура реализует этот трейт,
163то эту структуру можно передать из wasm на хост.
164
165Будет в основном использоваться для передачи сообщений между wasm модулем и Rust рантаймом.
166Для сериализации и десериализации в БД рекомендуется использовать serde.
167*/
168pub trait Outcoming<T = Self> {
169    /**
170    Указывает на то что необходимо прочитать данные из памяти песочницы
171     */
172    const IS_NEED_READ: bool = false;
173
174    /**
175    Заполнение массива чисел вспомогательными данными,
176    такими как длина строки или массива и др.
177    Вызывается в wasm.
178    */
179    #[cfg(not(feature = "std"))]
180    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError>;
181
182    /**
183    Чтение данных из памяти wasm.
184    Вызывается на хосте.
185    */
186    #[cfg(feature = "std")]
187    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError>
188    where
189        Self: Sized;
190}
191
192impl Incoming for bool {
193    #[cfg(not(feature = "std"))]
194    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
195        let el: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
196        Ok((el, el != 0))
197    }
198
199    #[cfg(feature = "std")]
200    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
201        args.push(if *self { 1 } else { 0 });
202        Ok(())
203    }
204
205    #[cfg(feature = "std")]
206    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
207        args.next()
208            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
209        Ok(())
210    }
211}
212
213impl Outcoming for bool {
214    #[cfg(not(feature = "std"))]
215    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
216        args.push(if *self { 1 } else { 0 });
217        Ok(())
218    }
219
220    #[cfg(feature = "std")]
221    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
222        let el: u32 = *args
223            .next()
224            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
225        Ok(el != 0)
226    }
227}
228
229impl Incoming for u8 {
230    #[cfg(not(feature = "std"))]
231    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
232        let el: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
233        Ok((el, el as u8))
234    }
235
236    #[cfg(feature = "std")]
237    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
238        args.push(*self as u32);
239        Ok(())
240    }
241
242    #[cfg(feature = "std")]
243    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
244        args.next()
245            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
246        Ok(())
247    }
248}
249
250impl Outcoming for u8 {
251    #[cfg(not(feature = "std"))]
252    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
253        args.push(*self as u32);
254        Ok(())
255    }
256
257    #[cfg(feature = "std")]
258    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
259        let el: u32 = *args
260            .next()
261            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
262        Ok(el as u8)
263    }
264}
265
266impl Incoming for i32 {
267    #[cfg(not(feature = "std"))]
268    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
269        let el: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
270        Ok((el, el as i32))
271    }
272
273    #[cfg(feature = "std")]
274    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
275        args.push(*self as u32);
276        Ok(())
277    }
278
279    #[cfg(feature = "std")]
280    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
281        args.next()
282            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
283        Ok(())
284    }
285}
286
287impl Outcoming for i32 {
288    #[cfg(not(feature = "std"))]
289    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
290        args.push(*self as u32);
291        Ok(())
292    }
293
294    #[cfg(feature = "std")]
295    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
296        Ok(*args
297            .next()
298            .ok_or_else(|| ProtocolError("args is end".to_string()))? as i32)
299    }
300}
301
302impl Incoming for i64 {
303    #[cfg(not(feature = "std"))]
304    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
305        let el1: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
306        let el2: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
307        let b1: [u8; 4] = el1.to_le_bytes();
308        let b2: [u8; 4] = el2.to_be_bytes();
309        let c: Vec<u8> = [&b1[..], &b2[..]].concat();
310        let d: &[u8; 8] = &c[..]
311            .try_into()
312            .map_err(|_| ProtocolError(BYTES_INTO_ARR8_ERROR))?;
313        let e = i64::from_le_bytes(*d);
314        Ok((0, e))
315    }
316
317    #[cfg(feature = "std")]
318    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
319        let bytes: [u8; 8] = self.to_le_bytes();
320        let arr1: &[u8; 4] = bytes[0..4].try_into()?;
321        let arr2: &[u8; 4] = bytes[4..8].try_into()?;
322        let arg1: u32 = u32::from_le_bytes(*arr1);
323        let arg2: u32 = u32::from_le_bytes(*arr2);
324        args.push(arg1);
325        args.push(arg2);
326        Ok(())
327    }
328
329    #[cfg(feature = "std")]
330    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
331        args.next()
332            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
333        args.next()
334            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
335        Ok(())
336    }
337}
338
339impl Outcoming for i64 {
340    #[cfg(not(feature = "std"))]
341    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
342        let bytes: [u8; 8] = self.to_le_bytes();
343        let arr1: &[u8; 4] = bytes[0..4]
344            .try_into()
345            .map_err(|_| ProtocolError(BYTES_INTO_ARR4_ERROR))?;
346        let arr2: &[u8; 4] = bytes[4..8]
347            .try_into()
348            .map_err(|_| ProtocolError(BYTES_INTO_ARR4_ERROR))?;
349        let arg1: u32 = u32::from_le_bytes(*arr1);
350        let arg2: u32 = u32::from_le_bytes(*arr2);
351        args.push(arg1);
352        args.push(arg2);
353        Ok(())
354    }
355
356    #[cfg(feature = "std")]
357    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
358        let el1: u32 = *args
359            .next()
360            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
361        let el2: u32 = *args
362            .next()
363            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
364        let b1: [u8; 4] = el1.to_le_bytes();
365        let b2: [u8; 4] = el2.to_be_bytes();
366        let c: Vec<u8> = [&b1[..], &b2[..]].concat();
367        let d: &[u8; 8] = &c[..].try_into()?;
368        let e = i64::from_le_bytes(*d);
369        Ok(e)
370    }
371}
372
373impl Incoming for u32 {
374    #[cfg(not(feature = "std"))]
375    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
376        let el: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
377        Ok((el, el))
378    }
379
380    #[cfg(feature = "std")]
381    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
382        args.push(*self);
383        Ok(())
384    }
385
386    #[cfg(feature = "std")]
387    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
388        args.next()
389            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
390        Ok(())
391    }
392}
393
394impl Outcoming for u32 {
395    #[cfg(not(feature = "std"))]
396    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
397        args.push(*self);
398        Ok(())
399    }
400
401    #[cfg(feature = "std")]
402    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
403        Ok(*args
404            .next()
405            .ok_or_else(|| ProtocolError("args is end".to_string()))?)
406    }
407}
408
409impl Incoming for u64 {
410    #[cfg(not(feature = "std"))]
411    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
412        let el1: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
413        let el2: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
414        let b1: [u8; 4] = el1.to_le_bytes();
415        let b2: [u8; 4] = el2.to_be_bytes();
416        let c: Vec<u8> = [&b1[..], &b2[..]].concat();
417        let d: &[u8; 8] = &c[..]
418            .try_into()
419            .map_err(|_| ProtocolError(BYTES_INTO_ARR8_ERROR))?;
420        let e = u64::from_le_bytes(*d);
421        Ok((0, e))
422    }
423
424    #[cfg(feature = "std")]
425    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
426        let bytes: [u8; 8] = self.to_le_bytes();
427        let arr1: &[u8; 4] = bytes[0..4].try_into()?;
428        let arr2: &[u8; 4] = bytes[4..8].try_into()?;
429        let arg1: u32 = u32::from_le_bytes(*arr1);
430        let arg2: u32 = u32::from_le_bytes(*arr2);
431        args.push(arg1);
432        args.push(arg2);
433        Ok(())
434    }
435
436    #[cfg(feature = "std")]
437    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
438        args.next()
439            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
440        args.next()
441            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
442        Ok(())
443    }
444}
445
446impl Outcoming for u64 {
447    #[cfg(not(feature = "std"))]
448    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
449        let bytes: [u8; 8] = self.to_le_bytes();
450        let arr1: &[u8; 4] = bytes[0..4]
451            .try_into()
452            .map_err(|_| ProtocolError(BYTES_INTO_ARR4_ERROR))?;
453        let arr2: &[u8; 4] = bytes[4..8]
454            .try_into()
455            .map_err(|_| ProtocolError(BYTES_INTO_ARR4_ERROR))?;
456        let arg1: u32 = u32::from_le_bytes(*arr1);
457        let arg2: u32 = u32::from_le_bytes(*arr2);
458        args.push(arg1);
459        args.push(arg2);
460        Ok(())
461    }
462
463    #[cfg(feature = "std")]
464    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
465        let el1: u32 = *args
466            .next()
467            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
468        let el2: u32 = *args
469            .next()
470            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
471        let b1: [u8; 4] = el1.to_le_bytes();
472        let b2: [u8; 4] = el2.to_be_bytes();
473        let c: Vec<u8> = [&b1[..], &b2[..]].concat();
474        let d: &[u8; 8] = &c[..].try_into()?;
475        let e = u64::from_le_bytes(*d);
476        Ok(e)
477    }
478}
479
480// only for wasm32 and runner target_pointer_width = "32"
481// #[cfg(all(not(feature = "std"), target_pointer_width = "32"))]
482impl Incoming for usize {
483    // NOTE: for wasm64 required implement other fn
484    #[cfg(not(feature = "std"))]
485    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
486        let el: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
487        Ok((0, el as usize))
488    }
489
490    #[cfg(feature = "std")]
491    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
492        args.push(*self as u32);
493        Ok(())
494    }
495
496    #[cfg(feature = "std")]
497    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
498        args.next()
499            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
500        Ok(())
501    }
502}
503
504// only for wasm32 and runner target_pointer_width = "32"
505// #[cfg(all(not(feature = "std"), target_pointer_width = "32"))]
506impl Outcoming for usize {
507    #[cfg(not(feature = "std"))]
508    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
509        args.push(*self as u32);
510        Ok(())
511    }
512
513    #[cfg(feature = "std")]
514    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
515        let el: u32 = *args
516            .next()
517            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
518        Ok(el as usize)
519    }
520}
521
522// only for wasm32 and runner target_pointer_width = "32"
523impl Incoming for isize {
524    #[cfg(not(feature = "std"))]
525    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
526        let el: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
527        Ok((0, el as isize))
528    }
529
530    #[cfg(feature = "std")]
531    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
532        args.push(*self as u32);
533        Ok(())
534    }
535
536    #[cfg(feature = "std")]
537    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
538        args.next()
539            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
540        Ok(())
541    }
542}
543
544// only for wasm32 and runner target_pointer_width = "32"
545impl Outcoming for isize {
546    #[cfg(not(feature = "std"))]
547    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
548        args.push(*self as u32);
549        Ok(())
550    }
551
552    #[cfg(feature = "std")]
553    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
554        let el: u32 = *args
555            .next()
556            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
557        Ok(el as isize)
558    }
559}
560
561impl Incoming for f32 {
562    #[cfg(not(feature = "std"))]
563    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
564        let el: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
565        let bytes: [u8; 4] = el.to_le_bytes();
566        let f = f32::from_le_bytes(bytes);
567        Ok((0, f))
568    }
569
570    #[cfg(feature = "std")]
571    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
572        let bytes = self.to_le_bytes();
573        let u = u32::from_le_bytes(bytes);
574        args.push(u);
575        Ok(())
576    }
577
578    #[cfg(feature = "std")]
579    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
580        args.next()
581            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
582        Ok(())
583    }
584}
585
586impl Outcoming for f32 {
587    #[cfg(not(feature = "std"))]
588    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
589        let bytes: [u8; 4] = self.to_le_bytes();
590        let u = u32::from_le_bytes(bytes);
591        args.push(u);
592        Ok(())
593    }
594
595    #[cfg(feature = "std")]
596    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
597        let el: u32 = *args
598            .next()
599            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
600        let bytes: [u8; 4] = el.to_le_bytes();
601        let f = f32::from_le_bytes(bytes);
602        Ok(f)
603    }
604}
605
606impl Incoming for f64 {
607    #[cfg(not(feature = "std"))]
608    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
609        let el1: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
610        let el2: u32 = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
611        let b1: [u8; 4] = el1.to_le_bytes();
612        let b2: [u8; 4] = el2.to_be_bytes();
613        let c: Vec<u8> = [&b1[..], &b2[..]].concat();
614        let d: &[u8; 8] = &c[..]
615            .try_into()
616            .map_err(|_| ProtocolError(BYTES_INTO_ARR8_ERROR))?;
617        let e = f64::from_le_bytes(*d);
618        Ok((0, e))
619    }
620
621    #[cfg(feature = "std")]
622    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
623        let bytes: [u8; 8] = self.to_le_bytes();
624        let arr1: &[u8; 4] = bytes[0..4].try_into()?;
625        let arr2: &[u8; 4] = bytes[4..8].try_into()?;
626        let arg1: u32 = u32::from_le_bytes(*arr1);
627        let arg2: u32 = u32::from_le_bytes(*arr2);
628        args.push(arg1);
629        args.push(arg2);
630        Ok(())
631    }
632
633    #[cfg(feature = "std")]
634    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
635        args.next()
636            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
637        args.next()
638            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
639        Ok(())
640    }
641}
642
643impl Outcoming for f64 {
644    #[cfg(not(feature = "std"))]
645    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
646        let bytes: [u8; 8] = self.to_le_bytes();
647        let arr1: &[u8; 4] = bytes[0..4]
648            .try_into()
649            .map_err(|_| ProtocolError(BYTES_INTO_ARR4_ERROR))?;
650        let arr2: &[u8; 4] = bytes[4..8]
651            .try_into()
652            .map_err(|_| ProtocolError(BYTES_INTO_ARR4_ERROR))?;
653        let arg1: u32 = u32::from_le_bytes(*arr1);
654        let arg2: u32 = u32::from_le_bytes(*arr2);
655        args.push(arg1);
656        args.push(arg2);
657        Ok(())
658    }
659
660    #[cfg(feature = "std")]
661    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
662        let el1: u32 = *args
663            .next()
664            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
665        let el2: u32 = *args
666            .next()
667            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
668        let b1: [u8; 4] = el1.to_le_bytes();
669        let b2: [u8; 4] = el2.to_be_bytes();
670        let c: Vec<u8> = [&b1[..], &b2[..]].concat();
671        let d: &[u8; 8] = &c[..].try_into()?;
672        let e = f64::from_le_bytes(*d);
673        Ok(e)
674    }
675}
676
677#[cfg(feature = "chrono")]
678impl Incoming for Duration {
679    #[cfg(not(feature = "std"))]
680    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
681        let (_, e) = i64::init(args)?;
682        let duration = Duration::milliseconds(e);
683        Ok((0, duration))
684    }
685
686    #[cfg(feature = "std")]
687    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
688        let e = self.num_milliseconds();
689        e.args(args)?;
690        Ok(())
691    }
692
693    #[cfg(feature = "std")]
694    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
695        args.next()
696            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
697        args.next()
698            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
699        Ok(())
700    }
701}
702
703#[cfg(feature = "chrono")]
704impl Outcoming for Duration {
705    #[cfg(not(feature = "std"))]
706    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
707        let e = self.num_milliseconds();
708        e.args(args)?;
709        Ok(())
710    }
711
712    #[cfg(feature = "std")]
713    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
714        let e = i64::read(heap, args)?;
715        Ok(Duration::milliseconds(e))
716    }
717}
718
719#[cfg(feature = "chrono")]
720impl Incoming for DateTime<Utc> {
721    #[cfg(not(feature = "std"))]
722    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
723        let (_, secs) = i64::init(args)?;
724        let dt = Self::from_utc(NaiveDateTime::from_timestamp(secs, 0), Utc);
725        Ok((0, dt))
726    }
727
728    #[cfg(feature = "std")]
729    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
730        let secs = self.timestamp();
731        secs.args(args)?;
732        Ok(())
733    }
734
735    #[cfg(feature = "std")]
736    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
737        args.next()
738            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
739        args.next()
740            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
741        Ok(())
742    }
743}
744
745#[cfg(feature = "chrono")]
746impl Outcoming for DateTime<Utc> {
747    #[cfg(not(feature = "std"))]
748    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
749        let secs = self.timestamp();
750        secs.args(args)?;
751        Ok(())
752    }
753
754    #[cfg(feature = "std")]
755    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
756        let secs = i64::read(heap, args)?;
757        Ok(Self::from_utc(NaiveDateTime::from_timestamp(secs, 0), Utc))
758    }
759}
760
761#[cfg(feature = "chrono")]
762impl Incoming for Date<Utc> {
763    #[cfg(not(feature = "std"))]
764    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
765        let (_, days) = i32::init(args)?;
766        let d = Self::from_utc(NaiveDate::from_num_days_from_ce(days), Utc);
767        Ok((0, d))
768    }
769
770    #[cfg(feature = "std")]
771    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
772        let days = self.num_days_from_ce();
773        days.args(args)?;
774        Ok(())
775    }
776
777    #[cfg(feature = "std")]
778    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
779        args.next()
780            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
781        Ok(())
782    }
783}
784
785#[cfg(feature = "chrono")]
786impl Outcoming for Date<Utc> {
787    #[cfg(not(feature = "std"))]
788    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
789        let days = self.num_days_from_ce();
790        days.args(args)?;
791        Ok(())
792    }
793
794    #[cfg(feature = "std")]
795    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
796        let days = i32::read(heap, args)?;
797        Ok(Self::from_utc(NaiveDate::from_num_days_from_ce(days), Utc))
798    }
799}
800
801// #[cfg(feature = "time")]
802impl Incoming for time::Duration {
803    #[cfg(not(feature = "std"))]
804    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
805        let (_, e) = i64::init(args)?;
806        let duration = time::Duration::seconds(e);
807        Ok((0, duration))
808    }
809
810    #[cfg(feature = "std")]
811    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
812        let e = self.whole_seconds();
813        e.args(args)?;
814        Ok(())
815    }
816
817    #[cfg(feature = "std")]
818    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
819        args.next()
820            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
821        args.next()
822            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
823        Ok(())
824    }
825}
826
827// #[cfg(feature = "time")]
828impl Outcoming for time::Duration {
829    #[cfg(not(feature = "std"))]
830    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
831        let e = self.whole_seconds();
832        e.args(args)?;
833        Ok(())
834    }
835
836    #[cfg(feature = "std")]
837    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
838        let e = i64::read(heap, args)?;
839        Ok(time::Duration::seconds(e))
840    }
841}
842
843// #[cfg(feature = "time")]
844impl Incoming for time::OffsetDateTime {
845    #[cfg(not(feature = "std"))]
846    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
847        let (_, secs) = i64::init(args)?;
848        let dt = Self::from_unix_timestamp(secs);
849        match dt {
850            Ok(dt) => Ok((0, dt)),
851            Err(_) => Err(ProtocolError(TIME_PARSE_ERROR)),
852        }
853    }
854
855    #[cfg(feature = "std")]
856    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
857        let secs = self.unix_timestamp();
858        secs.args(args)?;
859        Ok(())
860    }
861
862    #[cfg(feature = "std")]
863    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
864        args.next()
865            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
866        args.next()
867            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
868        Ok(())
869    }
870}
871
872// #[cfg(feature = "time")]
873impl Outcoming for time::OffsetDateTime {
874    #[cfg(not(feature = "std"))]
875    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
876        let secs = self.unix_timestamp();
877        secs.args(args)?;
878        Ok(())
879    }
880
881    #[cfg(feature = "std")]
882    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
883        let secs = i64::read(heap, args)?;
884        Self::from_unix_timestamp(secs).map_err(|_| ProtocolError::from("cannot read datetime"))
885    }
886}
887
888// #[cfg(feature = "time")]
889impl Incoming for time::Date {
890    #[cfg(not(feature = "std"))]
891    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
892        let (_, days) = i32::init(args)?;
893        let d = Self::from_julian_day(days);
894        match d {
895            Ok(d) => Ok((0, d)),
896            Err(_) => Err(ProtocolError(TIME_PARSE_ERROR)),
897        }
898    }
899
900    #[cfg(feature = "std")]
901    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
902        let days = self.to_julian_day();
903        days.args(args)?;
904        Ok(())
905    }
906
907    #[cfg(feature = "std")]
908    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
909        args.next()
910            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
911        args.next()
912            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
913        Ok(())
914    }
915}
916
917// #[cfg(feature = "time")]
918impl Outcoming for time::Date {
919    #[cfg(not(feature = "std"))]
920    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
921        let days = self.to_julian_day();
922        days.args(args)?;
923        Ok(())
924    }
925
926    #[cfg(feature = "std")]
927    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
928        let days = i32::read(heap, args)?;
929        Self::from_julian_day(days).map_err(|_| ProtocolError::from("cannot read datetime"))
930    }
931}
932
933/**
934convert u32 to time::Time
935*/
936// #[cfg(feature = "time")]
937pub const fn time_from_u32(u: u32) -> Result<time::Time, time::error::ComponentRange> {
938    let bytes: [u8; 4] = u.to_le_bytes();
939    let hour = bytes[0];
940    let minute = bytes[1];
941    let second = bytes[2];
942    time::Time::from_hms(hour, minute, second)
943}
944
945/**
946convert time::Time to u32
947*/
948// #[cfg(feature = "time")]
949pub const fn time_into_u32(time: &time::Time) -> u32 {
950    let (h, m, s) = time.as_hms();
951    u32::from_le_bytes([h, m, s, 0])
952}
953
954// #[cfg(feature = "time")]
955impl Incoming for time::Time {
956    #[cfg(not(feature = "std"))]
957    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
958        let (_, u) = u32::init(args)?;
959        let time = time_from_u32(u).map_err(|_| ProtocolError(TIME_PARSE_ERROR))?;
960        Ok((0, time))
961    }
962
963    #[cfg(feature = "std")]
964    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
965        let u = time_into_u32(self);
966        u.args(args)?;
967        Ok(())
968    }
969
970    #[cfg(feature = "std")]
971    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
972        args.next()
973            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
974        Ok(())
975    }
976}
977
978// #[cfg(feature = "time")]
979impl Outcoming for time::Time {
980    #[cfg(not(feature = "std"))]
981    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
982        let u = time_into_u32(self);
983        u.args(args)?;
984        Ok(())
985    }
986
987    #[cfg(feature = "std")]
988    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
989        let u = u32::read(heap, args)?;
990        let time = time_from_u32(u)?;
991        Ok(time)
992    }
993}
994
995// TODO: used?
996#[derive(PartialEq, Clone, Default)]
997pub struct Bytes(Vec<u8>);
998
999// TODO: for wasm64 other logic
1000impl Incoming for Bytes {
1001    #[cfg(not(feature = "std"))]
1002    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1003        let len = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))? as usize;
1004        let quot = len / 4;
1005        let rem = len % 4;
1006        let is_divided = rem == 0;
1007        let mut vec: Vec<u8> = Vec::with_capacity(len);
1008
1009        for _ in 0..quot {
1010            let u = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1011            let bytes: [u8; 4] = u.to_le_bytes();
1012            for byte in &bytes {
1013                vec.push(*byte);
1014            }
1015        }
1016
1017        if !is_divided {
1018            let u = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1019            let bytes: [u8; 4] = u.to_le_bytes();
1020            let mut iter = bytes.iter();
1021            for _ in 0..rem {
1022                let byte = *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1023                vec.push(byte);
1024            }
1025        }
1026
1027        Ok((0, Bytes(vec)))
1028    }
1029
1030    #[cfg(feature = "std")]
1031    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1032        let len = self.0.len();
1033        args.push(len as u32);
1034
1035        let quot = len / 4;
1036        let rem = len % 4;
1037        let is_divided = rem == 0;
1038        let count = if is_divided { quot } else { quot + 1 };
1039        let mut vec: Vec<u32> = Vec::with_capacity(count);
1040        let mut iter = self.0.iter();
1041
1042        for _ in 0..quot {
1043            let bytes: [u8; 4] = [
1044                *iter
1045                    .next()
1046                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1047                *iter
1048                    .next()
1049                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1050                *iter
1051                    .next()
1052                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1053                *iter
1054                    .next()
1055                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1056            ];
1057
1058            let u = u32::from_le_bytes(bytes);
1059            vec.push(u);
1060        }
1061
1062        if !is_divided {
1063            let b1 = *iter
1064                .next()
1065                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1066            let b2 = *iter.next().unwrap_or(&0);
1067            let b3 = *iter.next().unwrap_or(&0);
1068            let b4 = *iter.next().unwrap_or(&0);
1069            let u = u32::from_le_bytes([b1, b2, b3, b4]);
1070            vec.push(u);
1071        }
1072
1073        args.append(&mut vec);
1074
1075        Ok(())
1076    }
1077
1078    #[cfg(feature = "std")]
1079    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1080        args.next()
1081            .ok_or_else(|| ProtocolError("args is end".to_string()))?; // len
1082        let len = self.0.len();
1083        let quot = len / 4;
1084        let rem = len % 4;
1085        let is_divided = rem == 0;
1086        let count = if is_divided { quot } else { quot + 1 };
1087
1088        for _ in 0..count {
1089            args.next()
1090                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1091        }
1092        Ok(())
1093    }
1094}
1095
1096// TODO: for wasm64 other logic
1097impl Outcoming for Bytes {
1098    #[cfg(not(feature = "std"))]
1099    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1100        let len = self.0.len();
1101        args.push(len as u32);
1102
1103        // TODO: for wasm64 other logic
1104        let quot = len / 4;
1105        let rem = len % 4;
1106        let is_divided = rem == 0;
1107        let count = if is_divided { quot } else { quot + 1 };
1108        let mut vec: Vec<u32> = Vec::with_capacity(count);
1109        let mut iter = self.0.iter();
1110
1111        for _ in 0..quot {
1112            let bytes: [u8; 4] = [
1113                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1114                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1115                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1116                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1117            ];
1118
1119            let u = u32::from_le_bytes(bytes);
1120            vec.push(u);
1121        }
1122
1123        if !is_divided {
1124            let b1 = *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1125            let b2 = *iter.next().unwrap_or(&0);
1126            let b3 = *iter.next().unwrap_or(&0);
1127            let b4 = *iter.next().unwrap_or(&0);
1128            let u = u32::from_le_bytes([b1, b2, b3, b4]);
1129            vec.push(u);
1130        }
1131
1132        args.append(&mut vec);
1133
1134        Ok(())
1135    }
1136
1137    // TODO: https://stackoverflow.com/questions/49690459/converting-a-vecu32-to-vecu8-in-place-and-with-minimal-overhead
1138    #[cfg(feature = "std")]
1139    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1140        let len = *args
1141            .next()
1142            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1143        let quot = len / 4;
1144        let rem = len % 4;
1145        let is_divided = rem == 0;
1146        let mut vec: Vec<u8> = Vec::with_capacity(len);
1147
1148        for _ in 0..quot {
1149            let u = *args
1150                .next()
1151                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1152            let bytes: [u8; 4] = u.to_le_bytes();
1153            for byte in &bytes {
1154                vec.push(*byte);
1155            }
1156        }
1157
1158        if !is_divided {
1159            let u = *args
1160                .next()
1161                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1162            let bytes: [u8; 4] = u.to_le_bytes();
1163            let mut iter = bytes.iter();
1164            for _ in 0..rem {
1165                let byte = *iter
1166                    .next()
1167                    .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1168                vec.push(byte);
1169            }
1170        }
1171
1172        Ok(Bytes(vec))
1173    }
1174}
1175
1176/*impl Incoming for String {
1177    const IS_NEED_INIT_FILL: bool = true;
1178
1179    #[cfg(not(feature = "std"))]
1180    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1181        // узнаем длину строки
1182        let arg = args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1183        let len = *arg as usize;
1184        // создаем массив байт указанной длины состоящий из нулевых байт
1185        let vec = vec![0u8; len];
1186        // let s = String::with_capacity(len);
1187        let string = unsafe { String::from_utf8_unchecked(vec) };
1188        let ptr = string.as_ptr() as u32;
1189        *arg = ptr;
1190        Ok((ptr, string)) // why ptr?
1191    }
1192
1193    #[cfg(feature = "std")]
1194    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1195        args.push(self.len() as u32);
1196        Ok(())
1197    }
1198
1199    #[cfg(feature = "std")]
1200    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1201        let ptr: usize = *args
1202            .next()
1203            .ok_or_else(|| ProtocolError("args is end".to_string()))?
1204            as usize; // its pointer to string
1205        let mut pointer = ptr;
1206        for byte in self.as_bytes() {
1207            heap[pointer] = *byte;
1208            pointer += 1;
1209        }
1210        Ok(())
1211    }
1212}*/
1213
1214/*impl Outcoming for String {
1215    const IS_NEED_READ: bool = true;
1216
1217    #[cfg(not(feature = "std"))]
1218    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1219        args.push(self.len() as u32);
1220        args.push(self.as_ptr() as u32);
1221        Ok(())
1222    }
1223
1224    #[cfg(feature = "std")]
1225    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1226        let len = *args
1227            .next()
1228            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1229        let ptr = *args
1230            .next()
1231            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1232        let bytes = &heap[ptr..ptr + len];
1233        Ok(String::from_utf8(bytes.to_vec())?)
1234    }
1235}*/
1236
1237impl Incoming for String {
1238    #[cfg(not(feature = "std"))]
1239    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1240        let len = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))? as usize;
1241        let quot = len / 4;
1242        let rem = len % 4;
1243        let is_divided = rem == 0;
1244        let mut vec: Vec<u8> = Vec::with_capacity(len);
1245
1246        for _ in 0..quot {
1247            let u = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1248            let bytes: [u8; 4] = u.to_le_bytes();
1249            for byte in &bytes {
1250                vec.push(*byte);
1251            }
1252        }
1253
1254        if !is_divided {
1255            let u = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1256            let bytes: [u8; 4] = u.to_le_bytes();
1257            let mut iter = bytes.iter();
1258            for _ in 0..rem {
1259                let byte = *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1260                vec.push(byte);
1261            }
1262        }
1263
1264        let s = unsafe { String::from_utf8_unchecked(vec) };
1265
1266        Ok((0, s))
1267    }
1268
1269    #[cfg(feature = "std")]
1270    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1271        let len = self.len();
1272        args.push(len as u32);
1273
1274        let quot = len / 4;
1275        let rem = len % 4;
1276        let is_divided = rem == 0;
1277        let count = if is_divided { quot } else { quot + 1 };
1278        let mut vec: Vec<u32> = Vec::with_capacity(count);
1279        let mut iter = self.as_bytes().iter();
1280
1281        for _ in 0..quot {
1282            let bytes: [u8; 4] = [
1283                *iter
1284                    .next()
1285                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1286                *iter
1287                    .next()
1288                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1289                *iter
1290                    .next()
1291                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1292                *iter
1293                    .next()
1294                    .ok_or_else(|| ProtocolError("args is end".to_string()))?,
1295            ];
1296
1297            let u = u32::from_le_bytes(bytes);
1298            vec.push(u);
1299        }
1300
1301        if !is_divided {
1302            let b1 = *iter
1303                .next()
1304                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1305            let b2 = *iter.next().unwrap_or(&0);
1306            let b3 = *iter.next().unwrap_or(&0);
1307            let b4 = *iter.next().unwrap_or(&0);
1308            let u = u32::from_le_bytes([b1, b2, b3, b4]);
1309            vec.push(u);
1310        }
1311
1312        args.append(&mut vec);
1313
1314        Ok(())
1315    }
1316
1317    #[cfg(feature = "std")]
1318    fn fill(&self, _: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1319        args.next()
1320            .ok_or_else(|| ProtocolError("args is end".to_string()))?; // len
1321        let len = self.len();
1322        let quot = len / 4;
1323        let rem = len % 4;
1324        let is_divided = rem == 0;
1325        let count = if is_divided { quot } else { quot + 1 };
1326
1327        for _ in 0..count {
1328            args.next()
1329                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1330        }
1331        Ok(())
1332    }
1333}
1334
1335impl Outcoming for String {
1336    #[cfg(not(feature = "std"))]
1337    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1338        let len = self.len();
1339        args.push(len as u32);
1340
1341        // TODO: for wasm64 other logic
1342        let quot = len / 4;
1343        let rem = len % 4;
1344        let is_divided = rem == 0;
1345        let count = if is_divided { quot } else { quot + 1 };
1346        let mut vec: Vec<u32> = Vec::with_capacity(count);
1347        let mut iter = self.as_bytes().iter();
1348
1349        for _ in 0..quot {
1350            let bytes: [u8; 4] = [
1351                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1352                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1353                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1354                *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?,
1355            ];
1356
1357            let u = u32::from_le_bytes(bytes);
1358            vec.push(u);
1359        }
1360
1361        if !is_divided {
1362            let b1 = *iter.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1363            let b2 = *iter.next().unwrap_or(&0);
1364            let b3 = *iter.next().unwrap_or(&0);
1365            let b4 = *iter.next().unwrap_or(&0);
1366            let u = u32::from_le_bytes([b1, b2, b3, b4]);
1367            vec.push(u);
1368        }
1369
1370        args.append(&mut vec);
1371
1372        Ok(())
1373    }
1374
1375    #[cfg(feature = "std")]
1376    fn read(_: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1377        let len = *args
1378            .next()
1379            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1380        let quot = len / 4;
1381        let rem = len % 4;
1382        let is_divided = rem == 0;
1383        let mut vec: Vec<u8> = Vec::with_capacity(len);
1384
1385        for _ in 0..quot {
1386            let u = *args
1387                .next()
1388                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1389            let bytes: [u8; 4] = u.to_le_bytes();
1390            for byte in &bytes {
1391                vec.push(*byte);
1392            }
1393        }
1394
1395        if !is_divided {
1396            let u = *args
1397                .next()
1398                .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1399            let bytes: [u8; 4] = u.to_le_bytes();
1400            let mut iter = bytes.iter();
1401            for _ in 0..rem {
1402                let byte = *iter
1403                    .next()
1404                    .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1405                vec.push(byte);
1406            }
1407        }
1408
1409        let s = String::from_utf8(vec)?;
1410
1411        Ok(s)
1412    }
1413}
1414
1415// TODO: other realization for bytes vec
1416impl<T: Incoming> Incoming for Vec<T> {
1417    const IS_NEED_INIT_FILL: bool = T::IS_NEED_INIT_FILL;
1418
1419    #[cfg(not(feature = "std"))]
1420    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1421        let arg = args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))?;
1422        let len = *arg as usize;
1423        let mut vec = Vec::with_capacity(len);
1424        for _ in 0..len {
1425            let item: T = T::init(args)?.1;
1426            vec.push(item);
1427        }
1428        // TODO: ptr for not destructing?
1429        let ptr = vec.as_mut_ptr() as u32;
1430        *arg = ptr; // TODO: not need?
1431        Ok((ptr, vec))
1432    }
1433
1434    #[cfg(feature = "std")]
1435    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1436        let len = self.len();
1437        args.push(len as u32);
1438        for item in self {
1439            item.args(args)?;
1440        }
1441        Ok(())
1442    }
1443
1444    #[cfg(feature = "std")]
1445    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1446        args.next()
1447            .ok_or_else(|| ProtocolError("args is end".to_string()))?; // len
1448        for item in self {
1449            item.fill(heap, args)?;
1450        }
1451        Ok(())
1452    }
1453}
1454
1455impl<T: Outcoming> Outcoming for Vec<T> {
1456    const IS_NEED_READ: bool = T::IS_NEED_READ;
1457
1458    #[cfg(not(feature = "std"))]
1459    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1460        let len = self.len() as u32;
1461        args.push(len);
1462        for item in self {
1463            item.args(args)?;
1464        }
1465        Ok(())
1466    }
1467
1468    #[cfg(feature = "std")]
1469    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1470        let len = *args
1471            .next()
1472            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1473        let mut vec: Vec<T> = Vec::with_capacity(len);
1474
1475        for _ in 0..len {
1476            let item: T = T::read(heap, args)?;
1477            vec.push(item);
1478        }
1479        Ok(vec)
1480    }
1481}
1482
1483impl<T: Incoming> Incoming for Option<T> {
1484    const IS_NEED_INIT_FILL: bool = T::IS_NEED_INIT_FILL;
1485
1486    #[cfg(not(feature = "std"))]
1487    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1488        let is_some: bool = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))? != 0;
1489
1490        if !is_some {
1491            Ok((0, None))
1492        } else {
1493            // TODO: ???
1494            let (ptr, item) = T::init(args)?;
1495            Ok((ptr, Some(item)))
1496        }
1497    }
1498
1499    #[cfg(feature = "std")]
1500    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1501        match self {
1502            None => {
1503                args.push(0);
1504            }
1505            Some(item) => {
1506                args.push(1);
1507                item.args(args)?;
1508            }
1509        }
1510        Ok(())
1511    }
1512
1513    #[cfg(feature = "std")]
1514    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1515        args.next()
1516            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1517        if let Some(item) = self {
1518            item.fill(heap, args)?;
1519        }
1520        Ok(())
1521    }
1522}
1523
1524impl<T: Outcoming> Outcoming for Option<T> {
1525    const IS_NEED_READ: bool = T::IS_NEED_READ;
1526
1527    #[cfg(not(feature = "std"))]
1528    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1529        match self {
1530            None => {
1531                args.push(0);
1532            }
1533            Some(item) => {
1534                args.push(1);
1535                item.args(args)?;
1536            }
1537        }
1538        Ok(())
1539    }
1540
1541    #[cfg(feature = "std")]
1542    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1543        let is_some = *args
1544            .next()
1545            .ok_or_else(|| ProtocolError("args is end".to_string()))?
1546            != 0;
1547
1548        if !is_some {
1549            Ok(None)
1550        } else {
1551            Ok(Some(T::read(heap, args)?))
1552        }
1553    }
1554}
1555
1556#[cfg(any(feature = "std", feature = "hashmap"))]
1557impl<K: Incoming, V: Incoming> Incoming for HashMap<K, V>
1558where
1559    K: Eq + Hash,
1560{
1561    const IS_NEED_INIT_FILL: bool = K::IS_NEED_INIT_FILL || V::IS_NEED_INIT_FILL;
1562
1563    #[cfg(not(feature = "std"))]
1564    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1565        let len = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))? as usize;
1566        let mut map: HashMap<K, V> = HashMap::with_capacity(len);
1567        for _ in 0..len {
1568            let (key_ptr, key) = K::init(args)?;
1569            let (value_ptr, value) = V::init(args)?;
1570            map.insert(key, value)
1571                .ok_or(ProtocolError(MAP_INSERT_ERROR))?;
1572        }
1573        Ok((0, map))
1574    }
1575
1576    #[cfg(feature = "std")]
1577    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1578        let len = self.len();
1579        args.push(len as u32);
1580        for (key, value) in self {
1581            key.args(args)?;
1582            value.args(args)?;
1583        }
1584        Ok(())
1585    }
1586
1587    #[cfg(feature = "std")]
1588    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1589        args.next()
1590            .ok_or_else(|| ProtocolError("args is end".to_string()))?; // len
1591        for (key, value) in self {
1592            key.fill(heap, args)?;
1593            value.fill(heap, args)?;
1594        }
1595        Ok(())
1596    }
1597}
1598
1599#[cfg(any(feature = "std", feature = "hashmap"))]
1600impl<K: Outcoming, V: Outcoming> Outcoming for HashMap<K, V>
1601where
1602    K: Eq + Hash,
1603{
1604    const IS_NEED_READ: bool = K::IS_NEED_READ || V::IS_NEED_READ;
1605
1606    #[cfg(not(feature = "std"))]
1607    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1608        let len = self.len() as u32;
1609        args.push(len);
1610        for (key, value) in self {
1611            key.args(args)?;
1612            value.args(args)?;
1613        }
1614        Ok(())
1615    }
1616
1617    #[cfg(feature = "std")]
1618    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1619        let len = *args
1620            .next()
1621            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1622        let mut map: HashMap<K, V> = HashMap::with_capacity(len);
1623        for _ in 0..len {
1624            let key: K = K::read(heap, args)?;
1625            let value: V = V::read(heap, args)?;
1626            map.insert(key, value)
1627                .ok_or_else(|| ProtocolError("map already have item".to_string()))?;
1628        }
1629        Ok(map)
1630    }
1631}
1632
1633impl<K: Incoming, V: Incoming> Incoming for BTreeMap<K, V>
1634where
1635    K: Ord,
1636{
1637    const IS_NEED_INIT_FILL: bool = K::IS_NEED_INIT_FILL || V::IS_NEED_INIT_FILL;
1638
1639    #[cfg(not(feature = "std"))]
1640    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1641        let len = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))? as usize;
1642        let mut map: BTreeMap<K, V> = BTreeMap::new();
1643        for _ in 0..len {
1644            let (_, key) = K::init(args)?;
1645            let (_, value) = V::init(args)?;
1646            map.insert(key, value)
1647                .ok_or(ProtocolError(MAP_INSERT_ERROR))?;
1648        }
1649        Ok((0, map))
1650    }
1651
1652    #[cfg(feature = "std")]
1653    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1654        let len = self.len();
1655        args.push(len as u32);
1656        for (key, value) in self {
1657            key.args(args)?;
1658            value.args(args)?;
1659        }
1660        Ok(())
1661    }
1662
1663    #[cfg(feature = "std")]
1664    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1665        args.next()
1666            .ok_or_else(|| ProtocolError("args is end".to_string()))?; // len
1667        for (key, value) in self {
1668            key.fill(heap, args)?;
1669            value.fill(heap, args)?;
1670        }
1671        Ok(())
1672    }
1673}
1674
1675impl<K: Outcoming, V: Outcoming> Outcoming for BTreeMap<K, V>
1676where
1677    K: Ord,
1678{
1679    const IS_NEED_READ: bool = K::IS_NEED_READ || V::IS_NEED_READ;
1680
1681    #[cfg(not(feature = "std"))]
1682    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1683        let len = self.len() as u32;
1684        args.push(len);
1685        for (key, value) in self {
1686            key.args(args)?;
1687            value.args(args)?;
1688        }
1689        Ok(())
1690    }
1691
1692    #[cfg(feature = "std")]
1693    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1694        let len = *args
1695            .next()
1696            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1697        let mut map: BTreeMap<K, V> = BTreeMap::new();
1698        for _ in 0..len {
1699            let key: K = K::read(heap, args)?;
1700            let value: V = V::read(heap, args)?;
1701            map.insert(key, value)
1702                .ok_or_else(|| ProtocolError("map already have item".to_string()))?;
1703        }
1704        Ok(map)
1705    }
1706}
1707
1708#[cfg(all(any(feature = "hashmap", feature = "std"), feature = "map"))]
1709impl<K: Incoming, V: Incoming> Incoming for FxHashMap<K, V>
1710where
1711    K: Eq + Hash,
1712{
1713    const IS_NEED_INIT_FILL: bool = K::IS_NEED_INIT_FILL || V::IS_NEED_INIT_FILL;
1714
1715    #[cfg(not(feature = "std"))]
1716    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1717        let len = *args.next().ok_or(ProtocolError(ARGS_NEXT_ERROR))? as usize;
1718        let mut map: FxHashMap<K, V> =
1719            FxHashMap::with_capacity_and_hasher(len, FxBuildHasher::default());
1720        for _ in 0..len {
1721            let (key_ptr, key) = K::init(args)?;
1722            let (value_ptr, value) = V::init(args)?;
1723            map.insert(key, value)
1724                .ok_or(ProtocolError(MAP_INSERT_ERROR))?;
1725        }
1726        Ok((0, map))
1727    }
1728
1729    #[cfg(feature = "std")]
1730    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1731        let len = self.len();
1732        args.push(len as u32);
1733        for (key, value) in self {
1734            key.args(args)?;
1735            value.args(args)?;
1736        }
1737        Ok(())
1738    }
1739
1740    #[cfg(feature = "std")]
1741    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1742        args.next()
1743            .ok_or_else(|| ProtocolError("args is end".to_string()))?;
1744        for (key, value) in self {
1745            key.fill(heap, args)?;
1746            value.fill(heap, args)?;
1747        }
1748        Ok(())
1749    }
1750}
1751
1752#[cfg(all(any(feature = "hashmap", feature = "std"), feature = "map"))]
1753impl<K: Outcoming, V: Outcoming> Outcoming for FxHashMap<K, V>
1754where
1755    K: Eq + Hash,
1756{
1757    const IS_NEED_READ: bool = K::IS_NEED_READ || V::IS_NEED_READ;
1758
1759    #[cfg(not(feature = "std"))]
1760    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1761        let len = self.len() as u32;
1762        args.push(len);
1763        for (key, value) in self {
1764            key.args(args)?;
1765            value.args(args)?;
1766        }
1767        Ok(())
1768    }
1769
1770    #[cfg(feature = "std")]
1771    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1772        let len = *args
1773            .next()
1774            .ok_or_else(|| ProtocolError("args is end".to_string()))? as usize;
1775        let mut map: FxHashMap<K, V> =
1776            FxHashMap::with_capacity_and_hasher(len, FxBuildHasher::default());
1777        for _ in 0..len {
1778            let key: K = K::read(heap, args)?;
1779            let value: V = V::read(heap, args)?;
1780            map.insert(key, value)
1781                .ok_or_else(|| ProtocolError("map already have item".to_string()))?;
1782        }
1783        Ok(map)
1784    }
1785}
1786
1787impl<T1: Incoming, T2: Incoming> Incoming for (T1, T2) {
1788    const IS_NEED_INIT_FILL: bool = T1::IS_NEED_INIT_FILL || T2::IS_NEED_INIT_FILL;
1789
1790    #[cfg(not(feature = "std"))]
1791    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1792        let (_, t1) = T1::init(args)?;
1793        let (_, t2) = T2::init(args)?;
1794        Ok((0, (t1, t2)))
1795    }
1796
1797    #[cfg(feature = "std")]
1798    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1799        self.0.args(args)?;
1800        self.1.args(args)?;
1801        Ok(())
1802    }
1803
1804    #[cfg(feature = "std")]
1805    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1806        self.0.fill(heap, args)?;
1807        self.1.fill(heap, args)?;
1808        Ok(())
1809    }
1810}
1811
1812impl<T1: Outcoming, T2: Outcoming> Outcoming for (T1, T2) {
1813    const IS_NEED_READ: bool = T1::IS_NEED_READ || T2::IS_NEED_READ;
1814
1815    #[cfg(not(feature = "std"))]
1816    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1817        self.0.args(args)?;
1818        self.1.args(args)?;
1819        Ok(())
1820    }
1821
1822    #[cfg(feature = "std")]
1823    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1824        let t1 = T1::read(heap, args)?;
1825        let t2 = T2::read(heap, args)?;
1826        Ok((t1, t2))
1827    }
1828}
1829
1830impl<T1: Incoming, T2: Incoming, T3: Incoming> Incoming for (T1, T2, T3) {
1831    const IS_NEED_INIT_FILL: bool =
1832        T1::IS_NEED_INIT_FILL || T2::IS_NEED_INIT_FILL || T3::IS_NEED_INIT_FILL;
1833
1834    #[cfg(not(feature = "std"))]
1835    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1836        let (_, t1) = T1::init(args)?;
1837        let (_, t2) = T2::init(args)?;
1838        let (_, t3) = T3::init(args)?;
1839        Ok((0, (t1, t2, t3)))
1840    }
1841
1842    #[cfg(feature = "std")]
1843    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1844        self.0.args(args)?;
1845        self.1.args(args)?;
1846        self.2.args(args)?;
1847        Ok(())
1848    }
1849
1850    #[cfg(feature = "std")]
1851    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1852        self.0.fill(heap, args)?;
1853        self.1.fill(heap, args)?;
1854        self.2.fill(heap, args)?;
1855        Ok(())
1856    }
1857}
1858
1859impl<T1: Outcoming, T2: Outcoming, T3: Outcoming> Outcoming for (T1, T2, T3) {
1860    const IS_NEED_READ: bool = T1::IS_NEED_READ || T2::IS_NEED_READ || T3::IS_NEED_READ;
1861
1862    #[cfg(not(feature = "std"))]
1863    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1864        self.0.args(args)?;
1865        self.1.args(args)?;
1866        self.2.args(args)?;
1867        Ok(())
1868    }
1869
1870    #[cfg(feature = "std")]
1871    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1872        let t1 = T1::read(heap, args)?;
1873        let t2 = T2::read(heap, args)?;
1874        let t3 = T3::read(heap, args)?;
1875        Ok((t1, t2, t3))
1876    }
1877}
1878
1879impl<T1: Incoming, T2: Incoming, T3: Incoming, T4: Incoming> Incoming for (T1, T2, T3, T4) {
1880    const IS_NEED_INIT_FILL: bool = T1::IS_NEED_INIT_FILL
1881        || T2::IS_NEED_INIT_FILL
1882        || T3::IS_NEED_INIT_FILL
1883        || T4::IS_NEED_INIT_FILL;
1884
1885    #[cfg(not(feature = "std"))]
1886    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1887        let (_, t1) = T1::init(args)?;
1888        let (_, t2) = T2::init(args)?;
1889        let (_, t3) = T3::init(args)?;
1890        let (_, t4) = T4::init(args)?;
1891        Ok((0, (t1, t2, t3, t4)))
1892    }
1893
1894    #[cfg(feature = "std")]
1895    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1896        self.0.args(args)?;
1897        self.1.args(args)?;
1898        self.2.args(args)?;
1899        self.3.args(args)?;
1900        Ok(())
1901    }
1902
1903    #[cfg(feature = "std")]
1904    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1905        self.0.fill(heap, args)?;
1906        self.1.fill(heap, args)?;
1907        self.2.fill(heap, args)?;
1908        self.3.fill(heap, args)?;
1909        Ok(())
1910    }
1911}
1912
1913impl<T1: Outcoming, T2: Outcoming, T3: Outcoming, T4: Outcoming> Outcoming for (T1, T2, T3, T4) {
1914    const IS_NEED_READ: bool =
1915        T1::IS_NEED_READ || T2::IS_NEED_READ || T3::IS_NEED_READ || T4::IS_NEED_READ;
1916
1917    #[cfg(not(feature = "std"))]
1918    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1919        self.0.args(args)?;
1920        self.1.args(args)?;
1921        self.2.args(args)?;
1922        self.3.args(args)?;
1923        Ok(())
1924    }
1925
1926    #[cfg(feature = "std")]
1927    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1928        let t1 = T1::read(heap, args)?;
1929        let t2 = T2::read(heap, args)?;
1930        let t3 = T3::read(heap, args)?;
1931        let t4 = T4::read(heap, args)?;
1932        Ok((t1, t2, t3, t4))
1933    }
1934}
1935
1936impl<T: Incoming> Incoming for Box<T> {
1937    const IS_NEED_INIT_FILL: bool = T::IS_NEED_INIT_FILL;
1938
1939    #[cfg(not(feature = "std"))]
1940    fn init(args: &mut IterMut<u32>) -> Result<(u32, Self), ProtocolError> {
1941        let (_, t) = T::init(args)?;
1942        Ok((0, Box::new(t)))
1943    }
1944
1945    #[cfg(feature = "std")]
1946    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1947        self.as_ref().args(args)?;
1948        Ok(())
1949    }
1950
1951    #[cfg(feature = "std")]
1952    fn fill(&self, heap: &mut RefMut<[u8]>, args: &mut Iter<u32>) -> Result<(), ProtocolError> {
1953        self.as_ref().fill(heap, args)?;
1954        Ok(())
1955    }
1956}
1957
1958impl<T: Outcoming> Outcoming for Box<T> {
1959    const IS_NEED_READ: bool = T::IS_NEED_READ;
1960
1961    #[cfg(not(feature = "std"))]
1962    fn args(&self, args: &mut Vec<u32>) -> Result<(), ProtocolError> {
1963        self.as_ref().args(args)?;
1964        Ok(())
1965    }
1966
1967    #[cfg(feature = "std")]
1968    fn read(heap: &[u8], args: &mut Iter<u32>) -> Result<Self, ProtocolError> {
1969        let t = T::read(heap, args)?;
1970        Ok(Box::new(t))
1971    }
1972}
1973
1974// TODO: impl Incoming and Outcoming for HashSet