gpt4 book ai didi

arrays - 如何让 serde 序列化结构数组?

转载 作者:行者123 更新时间:2023-12-03 11:39:31 24 4
gpt4 key购买 nike

我正在尝试使用 neon 生成到 rust library 的绑定(bind).我正在使用 serde 处理数据,但它只有一个数组宏defined up to length 32 .

该宏代码是:

macro_rules! array_impls {
($($len:tt)+) => {
$(
impl<T> Serialize for [T; $len]
where
T: Serialize,
{
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = try!(serializer.serialize_tuple($len));
for e in self {
try!(seq.serialize_element(e));
}
seq.end()
}
}
)+
}
}

array_impls! {
01 02 03 04 05 06 07 08 09 10
11 12 13 14 15 16 17 18 19 20
21 22 23 24 25 26 27 28 29 30
31 32
}

我一开始尝试粘贴宏并调用 array_impls! { 1024 } , 但是 rust 不允许从这个 crate 外部修改类型,宏中的泛型可能会这样做。

我对实现的最佳猜测是:
impl Serialize for [PolyCoeff; N] {
#[inline]
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
let mut seq = serializer.serialize_tuple(N)?;
for e in self.iter_mut().enumerate() {
seq.serialize_element(e)?;
}
seq.end()
}
}

a couple of different errors .主要的是“ this is not defined in the current crate because arrays are always foreign”。

我找到了 github issue for the array size limit .他们建议以下作为解决方法:
struct S {
#[serde(serialize_with = "<[_]>::serialize")]
arr: [u8; 256],
}

我还不能让它编译。

最佳答案

这是 serde 中遇到的问题之前,和 there's a crate dealing with it .我的最终代码看起来像:

use serde::{Serialize, Deserialize};
use serde_big_array::big_array;

big_array! { BigArray; N }

#[derive(Copy, Clone, Serialize, Deserialize)]
pub struct Poly {
#[serde(with = "BigArray")]
coeffs: [PolyCoeff; N],
}

关于arrays - 如何让 serde 序列化结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61997226/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com