gpt4 book ai didi

arrays - 如何为大于 32 的数组实现 serde::Deserialize?

转载 作者:行者123 更新时间:2023-12-03 11:25:59 26 4
gpt4 key购买 nike

这个问题在这里已经有了答案:





How do I use Serde to (de)serialize arrays greater than 32 elements, such as [u8; 128]?

(2 个回答)



How do I implement a trait I don't own for a type I don't own?

(2 个回答)


去年关闭。




我需要使用 33 字节的数组。看起来最多包含 32 个元素的数组序列化没有问题,但 33 字节数组导致:

error[E0277]: the trait bound `[u8; 33]: _::_serde::Deserialize<'_>` is not satisfied
--> src/main.rs:54:2
|
54 | foo: [u8; 33]
| ^^^ the trait `_::_serde::Deserialize<'_>` is not implemented for `[u8; 33]`
|
= help: the following implementations were found:
<&'a [u8] as _::_serde::Deserialize<'de>>
<[T; 0] as _::_serde::Deserialize<'de>>
<[T; 10] as _::_serde::Deserialize<'de>>
<[T; 11] as _::_serde::Deserialize<'de>>
and 30 others
= note: required by `_::_serde::de::MapAccess::next_value`
他们显然认为 32 是一个停下来的好地方。如何添加对 33 个元素数组的支持?

最佳答案

你不能implement a trait you don't own for a type you don't own ,但不幸的是,在这种特殊情况下,您不必这样做。

对于序列化,支持大数组非常容易

struct S {
#[serde(serialize_with = "<[_]>::serialize")]
arr: [u8; 256],
}

Source
这会将数组强制转换为切片并对其进行序列化。

对于反序列化,它有点复杂。
serde 自己的作者推荐以下内容
#[macro_use] extern crate serde_derive;

extern crate serde; extern crate serde_json;

use std::fmt; use std::marker::PhantomData;
use serde::ser::{Serialize, Serializer, SerializeTuple};
use serde::de::{Deserialize, Deserializer, Visitor, SeqAccess, Error};

trait BigArray<'de>: Sized {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer;
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
where D: Deserializer<'de>;
}

macro_rules! big_array {
($($len:expr,)+) => {
$(
impl<'de, T> BigArray<'de> for [T; $len]
where T: Default + Copy + Serialize + Deserialize<'de>
{
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where S: Serializer
{
let mut seq = serializer.serialize_tuple(self.len())?;
for elem in &self[..] {
seq.serialize_element(elem)?;
}
seq.end()
}

fn deserialize<D>(deserializer: D) -> Result<[T; $len], D::Error>
where D: Deserializer<'de>
{
struct ArrayVisitor<T> {
element: PhantomData<T>,
}

impl<'de, T> Visitor<'de> for ArrayVisitor<T>
where T: Default + Copy + Deserialize<'de>
{
type Value = [T; $len];

fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
formatter.write_str(concat!("an array of length ", $len))
}

fn visit_seq<A>(self, mut seq: A) -> Result<[T; $len], A::Error>
where A: SeqAccess<'de>
{
let mut arr = [T::default(); $len];
for i in 0..$len {
arr[i] = seq.next_element()?
.ok_or_else(|| Error::invalid_length(i, &self))?;
}
Ok(arr)
}
}

let visitor = ArrayVisitor { element: PhantomData };
deserializer.deserialize_tuple($len, visitor)
}
}
)+
}
}

big_array! {
40, 48, 50, 56, 64, 72, 96, 100, 128, 160, 192, 200, 224, 256, 384, 512,
768, 1024, 2048, 4096, 8192, 16384, 32768, 65536, }

#[derive(Serialize, Deserialize)]
struct S {
#[serde(with = "BigArray")]
arr: [u8; 64], }

fn main() {
let s = S { arr: [1; 64] };
let j = serde_json::to_string(&s).unwrap();
println!("{}", j);
serde_json::from_str::<S>(&j).unwrap(); }

Source
这已发表在 serde-big-array 箱。

关于arrays - 如何为大于 32 的数组实现 serde::Deserialize?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62665558/

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