referrerpolicy=no-referrer-when-downgrade

sp_runtime_interface/
pass_by.rs

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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
// This file is part of Substrate.

// Copyright (C) Parity Technologies (UK) Ltd.
// SPDX-License-Identifier: Apache-2.0

// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// 	http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Provides host <-> runtime FFI marshalling strategy newtype wrappers
//! for defining runtime interfaces.

use crate::{
	util::{pack_ptr_and_len, unpack_ptr_and_len},
	RIType,
};

#[cfg(not(substrate_runtime))]
use crate::host::*;

#[cfg(substrate_runtime)]
use crate::wasm::*;

#[cfg(not(substrate_runtime))]
use sp_wasm_interface::{FunctionContext, Pointer, Result};

#[cfg(not(substrate_runtime))]
use alloc::{format, string::String};

use alloc::vec::Vec;
use core::{any::type_name, marker::PhantomData};

/// Pass a value into the host by a thin pointer.
///
/// This casts the value into a `&[u8]` using `AsRef<[u8]>` and passes a pointer to that byte blob
/// to the host. Then the host reads `N` bytes from that address into an `[u8; N]`, converts it
/// into target type using `From<[u8; N]>` and passes it into the host function by a copy.
///
/// Use [`PassPointerAndRead`] if you want to have the host function accept a reference type
/// on the host side or if you'd like to avoid the extra copy.
///
/// Raw FFI type: `u32` (a pointer)
pub struct PassPointerAndReadCopy<T, const N: usize>(PhantomData<(T, [u8; N])>);

impl<T, const N: usize> RIType for PassPointerAndReadCopy<T, N> {
	type FFIType = u32;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<'a, T, const N: usize> FromFFIValue<'a> for PassPointerAndReadCopy<T, N>
where
	T: From<[u8; N]> + Copy,
{
	type Owned = T;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		let mut out = [0; N];
		context.read_memory_into(Pointer::new(arg), &mut out)?;
		Ok(T::from(out))
	}

	#[inline]
	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		*owned
	}
}

#[cfg(substrate_runtime)]
impl<T, const N: usize> IntoFFIValue for PassPointerAndReadCopy<T, N>
where
	T: AsRef<[u8]>,
{
	type Destructor = ();

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		// Using an 'assert' instead of a 'T: AsRef<[u8; N]>` bound since a '[u8; N]' *doesn't*
		// implement it.
		assert_eq!(value.as_ref().len(), N);
		(value.as_ref().as_ptr() as u32, ())
	}
}

/// Pass a value into the host by a thin pointer.
///
/// This casts the value into a `&[u8]` using `AsRef<[u8]>` and passes a pointer to that byte blob
/// to the host. Then the host reads `N` bytes from that address into an `[u8; N]`, converts it
/// into target type using `From<[u8; N]>` and passes it into the host function by a reference.
///
/// This can only be used with reference types (e.g. `&[u8; 32]`). Use [`PassPointerAndReadCopy`]
/// if you want to have the host function accept a non-reference type on the host side.
///
/// Raw FFI type: `u32` (a pointer)
pub struct PassPointerAndRead<T, const N: usize>(PhantomData<(T, [u8; N])>);

impl<'a, T, const N: usize> RIType for PassPointerAndRead<&'a T, N> {
	type FFIType = u32;
	type Inner = &'a T;
}

#[cfg(not(substrate_runtime))]
impl<'a, T, const N: usize> FromFFIValue<'a> for PassPointerAndRead<&'a T, N>
where
	T: From<[u8; N]>,
{
	type Owned = T;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		let mut out = [0; N];
		context.read_memory_into(Pointer::new(arg), &mut out)?;
		Ok(T::from(out))
	}

	#[inline]
	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		&*owned
	}
}

#[cfg(substrate_runtime)]
impl<'a, T, const N: usize> IntoFFIValue for PassPointerAndRead<&'a T, N>
where
	T: AsRef<[u8]>,
{
	type Destructor = ();

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		assert_eq!(value.as_ref().len(), N);
		(value.as_ref().as_ptr() as u32, ())
	}
}

/// Pass a value into the host by a fat pointer.
///
/// This casts the value into a `&[u8]` and passes a pointer to that byte blob and its length
/// to the host. Then the host reads that blob and converts it into an owned type and passes it
/// (either as an owned type or as a reference) to the host function.
///
/// Raw FFI type: `u64` (a fat pointer; upper 32 bits is the size, lower 32 bits is the pointer)
pub struct PassFatPointerAndRead<T>(PhantomData<T>);

impl<T> RIType for PassFatPointerAndRead<T> {
	type FFIType = u64;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<'a> FromFFIValue<'a> for PassFatPointerAndRead<&'a [u8]> {
	type Owned = Vec<u8>;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		let (ptr, len) = unpack_ptr_and_len(arg);
		context.read_memory(Pointer::new(ptr), len)
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		&*owned
	}
}

#[cfg(not(substrate_runtime))]
impl<'a> FromFFIValue<'a> for PassFatPointerAndRead<&'a str> {
	type Owned = String;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		let (ptr, len) = unpack_ptr_and_len(arg);
		let vec = context.read_memory(Pointer::new(ptr), len)?;
		String::from_utf8(vec).map_err(|_| "could not parse '&str' when marshalling hostcall's arguments through the FFI boundary: the string is not valid UTF-8".into())
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		&*owned
	}
}

#[cfg(not(substrate_runtime))]
impl<'a> FromFFIValue<'a> for PassFatPointerAndRead<Vec<u8>> {
	type Owned = Vec<u8>;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		<PassFatPointerAndRead<&[u8]> as FromFFIValue>::from_ffi_value(context, arg)
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		core::mem::take(owned)
	}
}

#[cfg(substrate_runtime)]
impl<T> IntoFFIValue for PassFatPointerAndRead<T>
where
	T: AsRef<[u8]>,
{
	type Destructor = ();

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		let value = value.as_ref();
		(pack_ptr_and_len(value.as_ptr() as u32, value.len() as u32), ())
	}
}

/// Pass a value into the host by a fat pointer, writing it back after the host call ends.
///
/// This casts the value into a `&mut [u8]` and passes a pointer to that byte blob and its length
/// to the host. Then the host reads that blob and converts it into an owned type and passes it
/// as a mutable reference to the host function. After the host function finishes the byte blob
/// is written back into the guest memory.
///
/// Raw FFI type: `u64` (a fat pointer; upper 32 bits is the size, lower 32 bits is the pointer)
pub struct PassFatPointerAndReadWrite<T>(PhantomData<T>);

impl<T> RIType for PassFatPointerAndReadWrite<T> {
	type FFIType = u64;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<'a> FromFFIValue<'a> for PassFatPointerAndReadWrite<&'a mut [u8]> {
	type Owned = Vec<u8>;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		let (ptr, len) = unpack_ptr_and_len(arg);
		context.read_memory(Pointer::new(ptr), len)
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		&mut *owned
	}

	fn write_back_into_runtime(
		value: Self::Owned,
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<()> {
		let (ptr, len) = unpack_ptr_and_len(arg);
		assert_eq!(len as usize, value.len());
		context.write_memory(Pointer::new(ptr), &value)
	}
}

#[cfg(substrate_runtime)]
impl<'a> IntoFFIValue for PassFatPointerAndReadWrite<&'a mut [u8]> {
	type Destructor = ();

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		(pack_ptr_and_len(value.as_ptr() as u32, value.len() as u32), ())
	}
}

/// Pass a pointer into the host and write to it after the host call ends.
///
/// This casts a given type into `&mut [u8]` using `AsMut<[u8]>` and passes a pointer to
/// that byte slice into the host. The host *doesn't* read from this and instead creates
/// a default instance of type `T` and passes it as a `&mut T` into the host function
/// implementation. After the host function finishes this value is then cast into a `&[u8]` using
/// `AsRef<[u8]>` and written back into the guest memory.
///
/// Raw FFI type: `u32` (a pointer)
pub struct PassPointerAndWrite<T, const N: usize>(PhantomData<(T, [u8; N])>);

impl<T, const N: usize> RIType for PassPointerAndWrite<T, N> {
	type FFIType = u32;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<'a, T, const N: usize> FromFFIValue<'a> for PassPointerAndWrite<&'a mut T, N>
where
	T: Default + AsRef<[u8]>,
{
	type Owned = T;

	fn from_ffi_value(
		_context: &mut dyn FunctionContext,
		_arg: Self::FFIType,
	) -> Result<Self::Owned> {
		Ok(T::default())
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		&mut *owned
	}

	fn write_back_into_runtime(
		value: Self::Owned,
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<()> {
		let value = value.as_ref();
		assert_eq!(value.len(), N);
		context.write_memory(Pointer::new(arg), value)
	}
}

#[cfg(substrate_runtime)]
impl<'a, T, const N: usize> IntoFFIValue for PassPointerAndWrite<&'a mut T, N>
where
	T: AsMut<[u8]>,
{
	type Destructor = ();

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		let value = value.as_mut();
		assert_eq!(value.len(), N);
		(value.as_ptr() as u32, ())
	}
}

/// Pass a `T` into the host using the SCALE codec.
///
/// This encodes a `T` into a `Vec<u8>` using the SCALE codec and then
/// passes a pointer to that byte blob and its length to the host,
/// which then reads it and decodes back into `T`.
///
/// Raw FFI type: `u64` (a fat pointer; upper 32 bits is the size, lower 32 bits is the pointer)
pub struct PassFatPointerAndDecode<T>(PhantomData<T>);

impl<T> RIType for PassFatPointerAndDecode<T> {
	type FFIType = u64;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<'a, T: codec::Decode> FromFFIValue<'a> for PassFatPointerAndDecode<T> {
	type Owned = Option<T>;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		let (ptr, len) = unpack_ptr_and_len(arg);
		let vec = context.read_memory(Pointer::new(ptr), len)?;
		T::decode(&mut &vec[..]).map_err(|error| format!(
			"could not SCALE-decode '{}' when marshalling hostcall's arguments through the FFI boundary: {error}",
			type_name::<T>())
		).map(Some)
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		owned.take().expect("this is called only once and is never 'None'")
	}
}

#[cfg(substrate_runtime)]
impl<T: codec::Encode> IntoFFIValue for PassFatPointerAndDecode<T> {
	type Destructor = Vec<u8>;

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		let data = value.encode();
		(pack_ptr_and_len(data.as_ptr() as u32, data.len() as u32), data)
	}
}

/// Pass a `&[T]` into the host using the SCALE codec.
///
/// This encodes a `&[T]` into a `Vec<u8>` using the SCALE codec and then
/// passes a pointer to that byte blob and its length to the host,
/// which then reads it and decodes back into `Vec<T>` and passes
/// a reference to that (as `&[T]`) into the host function.
///
/// Raw FFI type: `u64` (a fat pointer; upper 32 bits is the size, lower 32 bits is the pointer)
pub struct PassFatPointerAndDecodeSlice<T>(PhantomData<T>);

impl<T> RIType for PassFatPointerAndDecodeSlice<T> {
	type FFIType = u64;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<'a, T: codec::Decode> FromFFIValue<'a> for PassFatPointerAndDecodeSlice<&'a [T]> {
	type Owned = Vec<T>;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		let (ptr, len) = unpack_ptr_and_len(arg);
		let vec = context.read_memory(Pointer::new(ptr), len)?;
		<Vec::<T> as codec::Decode>::decode(&mut &vec[..]).map_err(|error| format!(
			"could not SCALE-decode '{}' when marshalling hostcall's arguments through the FFI boundary: {error}",
			type_name::<Vec<T>>()
		))
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		&*owned
	}
}

#[cfg(substrate_runtime)]
impl<'a, T: codec::Encode> IntoFFIValue for PassFatPointerAndDecodeSlice<&'a [T]> {
	type Destructor = Vec<u8>;

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		let data = codec::Encode::encode(value);
		(pack_ptr_and_len(data.as_ptr() as u32, data.len() as u32), data)
	}
}

/// A trait signifying a primitive type.
trait Primitive: Copy {}

impl Primitive for u8 {}
impl Primitive for u16 {}
impl Primitive for u32 {}
impl Primitive for u64 {}

impl Primitive for i8 {}
impl Primitive for i16 {}
impl Primitive for i32 {}
impl Primitive for i64 {}

/// Pass `T` through the FFI boundary by first converting it to `U` in the runtime, and then
/// converting it back to `T` on the host's side.
///
/// Raw FFI type: same as `U`'s FFI type
pub struct PassAs<T, U>(PhantomData<(T, U)>);

impl<T, U> RIType for PassAs<T, U>
where
	U: RIType,
{
	type FFIType = <U as RIType>::FFIType;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<'a, T, U> FromFFIValue<'a> for PassAs<T, U>
where
	U: RIType + FromFFIValue<'a> + Primitive,
	T: TryFrom<<U as FromFFIValue<'a>>::Owned> + Copy,
{
	type Owned = T;

	fn from_ffi_value(
		context: &mut dyn FunctionContext,
		arg: Self::FFIType,
	) -> Result<Self::Owned> {
		<U as FromFFIValue>::from_ffi_value(context, arg).and_then(|value| value.try_into()
			.map_err(|_| format!(
				"failed to convert '{}' (passed as '{}') into '{}' when marshalling hostcall's arguments through the FFI boundary",
				type_name::<T>(),
				type_name::<Self::FFIType>(),
				type_name::<Self::Owned>()
			)))
	}

	fn take_from_owned(owned: &'a mut Self::Owned) -> Self::Inner {
		*owned
	}
}

#[cfg(substrate_runtime)]
impl<T, U> IntoFFIValue for PassAs<T, U>
where
	U: RIType + IntoFFIValue + Primitive,
	U::Inner: From<T>,
	T: Copy,
{
	type Destructor = <U as IntoFFIValue>::Destructor;

	fn into_ffi_value(value: &mut Self::Inner) -> (Self::FFIType, Self::Destructor) {
		let mut value = U::Inner::from(*value);
		<U as IntoFFIValue>::into_ffi_value(&mut value)
	}
}

/// Return `T` through the FFI boundary by first converting it to `U` on the host's side, and then
/// converting it back to `T` in the runtime.
///
/// Raw FFI type: same as `U`'s FFI type
pub struct ReturnAs<T, U>(PhantomData<(T, U)>);

impl<T, U> RIType for ReturnAs<T, U>
where
	U: RIType,
{
	type FFIType = <U as RIType>::FFIType;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<T, U> IntoFFIValue for ReturnAs<T, U>
where
	U: RIType + IntoFFIValue + Primitive,
	<U as RIType>::Inner: From<Self::Inner>,
{
	fn into_ffi_value(
		value: Self::Inner,
		context: &mut dyn FunctionContext,
	) -> Result<Self::FFIType> {
		let value: <U as RIType>::Inner = value.into();
		<U as IntoFFIValue>::into_ffi_value(value, context)
	}
}

#[cfg(substrate_runtime)]
impl<T, U> FromFFIValue for ReturnAs<T, U>
where
	U: RIType + FromFFIValue + Primitive,
	Self::Inner: TryFrom<U::Inner>,
{
	fn from_ffi_value(arg: Self::FFIType) -> Self::Inner {
		let value = <U as FromFFIValue>::from_ffi_value(arg);
		match Self::Inner::try_from(value) {
			Ok(value) => value,
			Err(_) => {
				panic!(
					"failed to convert '{}' (passed as '{}') into a '{}' when marshalling a hostcall's return value through the FFI boundary",
					type_name::<U::Inner>(),
					type_name::<Self::FFIType>(),
					type_name::<Self::Inner>()
				);
			},
		}
	}
}

/// (DEPRECATED) Return `T` as a blob of bytes into the runtime.
///
/// Uses `T::AsRef<[u8]>` to cast `T` into a `&[u8]`, allocates runtime memory
/// using the legacy allocator, copies the slice into the runtime memory, and
/// returns a pointer to it.
///
/// THIS STRATEGY IS DEPRECATED; DO NOT USE FOR NEW HOST FUNCTIONS!
///
/// Ideally use a mutable slice to return data to the guest, for example using
/// the [`PassPointerAndWrite`] strategy.
///
/// Raw FFI type: `u32` (a pointer to the byte blob)
pub struct AllocateAndReturnPointer<T, const N: usize>(PhantomData<(T, [u8; N])>);

impl<T, const N: usize> RIType for AllocateAndReturnPointer<T, N> {
	type FFIType = u32;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<T, const N: usize> IntoFFIValue for AllocateAndReturnPointer<T, N>
where
	T: AsRef<[u8]>,
{
	fn into_ffi_value(
		value: Self::Inner,
		context: &mut dyn FunctionContext,
	) -> Result<Self::FFIType> {
		let value = value.as_ref();
		assert_eq!(
			value.len(),
			N,
			"expected the byte blob to be {N} bytes long, is {} bytes when returning '{}' from a host function",
			value.len(),
			type_name::<T>()
		);

		let addr = context.allocate_memory(value.len() as u32)?;
		context.write_memory(addr, value)?;
		Ok(addr.into())
	}
}

#[cfg(substrate_runtime)]
impl<T: codec::Decode, const N: usize> FromFFIValue for AllocateAndReturnPointer<T, N>
where
	T: From<[u8; N]>,
{
	fn from_ffi_value(arg: Self::FFIType) -> Self::Inner {
		// SAFETY: This memory was allocated by the host allocator with the exact
		// capacity needed, so it's safe to make a `Vec` out of it.
		let value = unsafe { Vec::from_raw_parts(arg as *mut u8, N, N) };

		// SAFETY: Reading a `[u8; N]` from a `&[u8]` which is at least `N` elements long is safe.
		let array = unsafe { *(value.as_ptr() as *const [u8; N]) };
		T::from(array)
	}
}

/// (DEPRECATED) Return `T` as a blob of bytes into the runtime.
///
/// Uses `T::AsRef<[u8]>` to cast `T` into a `&[u8]`, allocates runtime memory
/// using the legacy allocator, copies the slice into the runtime memory, and
/// returns a pointer to it.
///
/// THIS STRATEGY IS DEPRECATED; DO NOT USE FOR NEW HOST FUNCTIONS!
///
/// Ideally use a mutable slice to return data to the guest, for example using
/// the [`PassPointerAndWrite`] strategy.
///
/// Raw FFI type: `u64` (a fat pointer; upper 32 bits is the size, lower 32 bits is the pointer)
pub struct AllocateAndReturnFatPointer<T>(PhantomData<T>);

impl<T> RIType for AllocateAndReturnFatPointer<T> {
	type FFIType = u64;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<T> IntoFFIValue for AllocateAndReturnFatPointer<T>
where
	T: AsRef<[u8]>,
{
	fn into_ffi_value(
		value: Self::Inner,
		context: &mut dyn FunctionContext,
	) -> Result<Self::FFIType> {
		let value = value.as_ref();
		let ptr = context.allocate_memory(value.len() as u32)?;
		context.write_memory(ptr, &value)?;
		Ok(pack_ptr_and_len(ptr.into(), value.len() as u32))
	}
}

#[cfg(substrate_runtime)]
impl<T> FromFFIValue for AllocateAndReturnFatPointer<T>
where
	T: From<Vec<u8>>,
{
	fn from_ffi_value(arg: Self::FFIType) -> Self::Inner {
		let (ptr, len) = unpack_ptr_and_len(arg);
		let len = len as usize;
		let vec = if len == 0 {
			Vec::new()
		} else {
			// SAFETY: This memory was allocated by the host allocator with the exact
			// capacity needed, so it's safe to make a `Vec` out of it.
			unsafe { Vec::from_raw_parts(ptr as *mut u8, len, len) }
		};

		T::from(vec)
	}
}

/// (DEPRECATED) Return `T` into the runtime using the SCALE codec.
///
/// Encodes `T` using the SCALE codec, allocates runtime memory using the legacy
/// allocator, copies the encoded payload into the runtime memory, and returns
/// a fat pointer to it.
///
/// THIS STRATEGY IS DEPRECATED; DO NOT USE FOR NEW HOST FUNCTIONS!
///
/// Ideally use a mutable slice to return data to the guest, for example using
/// the [`PassPointerAndWrite`] strategy.
///
/// Raw FFI type: `u64` (a fat pointer; upper 32 bits is the size, lower 32 bits is the pointer)
pub struct AllocateAndReturnByCodec<T>(PhantomData<T>);

impl<T> RIType for AllocateAndReturnByCodec<T> {
	type FFIType = u64;
	type Inner = T;
}

#[cfg(not(substrate_runtime))]
impl<T: codec::Encode> IntoFFIValue for AllocateAndReturnByCodec<T> {
	fn into_ffi_value(value: T, context: &mut dyn FunctionContext) -> Result<Self::FFIType> {
		let vec = value.encode();
		let ptr = context.allocate_memory(vec.len() as u32)?;
		context.write_memory(ptr, &vec)?;
		Ok(pack_ptr_and_len(ptr.into(), vec.len() as u32))
	}
}

#[cfg(substrate_runtime)]
impl<T: codec::Decode> FromFFIValue for AllocateAndReturnByCodec<T> {
	fn from_ffi_value(arg: Self::FFIType) -> Self::Inner {
		let (ptr, len) = unpack_ptr_and_len(arg);
		let len = len as usize;

		let encoded = if len == 0 {
			bytes::Bytes::new()
		} else {
			// SAFETY: This memory was allocated by the host allocator with the exact
			// capacity needed, so it's safe to make a `Vec` out of it.
			bytes::Bytes::from(unsafe { Vec::from_raw_parts(ptr as *mut u8, len, len) })
		};

		match codec::decode_from_bytes(encoded) {
			Ok(value) => value,
			Err(error) => {
				panic!(
					"failed to decode '{}' when marshalling a hostcall's return value through the FFI boundary: {error}",
					type_name::<T>(),
				);
			},
		}
	}
}