English 中文(简体)
如何使用Vc<Bytes”作为任何理由:decode()?
原标题:How to use Vec<Bytes> as an argument for Any::decode()?
  • 时间:2024-02-08 02:19:52
  •  标签:
  • rust

我有<代码>Vec<Bytes>,希望将其用作<代码>Any:decode(。

由于<代码>Any:decode() s case is a Buf trait that does not need a contiguous memory, theoryly, Vec<Bytes> can be used withoutplicaing memory.

然而,由于<代码>Vec<Bytes>没有实施Buf trait,需要将其转化为不同的东西。

While this scenario seems somewhat common, I failed to find an existing solution.

我如何能够做到这一点?

问题回答

如果两种类型(Vec<Bytes>)和海峡(Buf)均为外国,即目前图书馆没有申报,那么你就无法对此类类型实施海峡。 https://github.com/Ixrec/rust-orphan-rules” rel=“nofollow noreferer”

To workaround this limitation, you use something called a newtype pattern.

NewType Pattern

你可以简单地宣布你自己的习俗类型,以总结外国的类型。 现在,你可以简单地为你的新习俗而执行外国海峡。

pub struct MyCustomBuf(Vec<Bytes>);

impl Buf for MyCustomBuf {
// ... impl the functions
}

// now any function that takes `impl Buf` or `T: Buf` will accept your MyCustomBuf

Maybe chunked-bytes 有用:

use bytes::{Buf, Bytes};
use chunked_bytes::ChunkedBytes;

pub fn chain_noncopying(f: Vec<Bytes>) -> ChunkedBytes {
    f.into_iter().fold(ChunkedBytes::new(), |mut acc, b| {
        acc.put_bytes(b);
        
        acc
    })
}

旧答案:

How about re-collecting into Bytes?:

pub fn flatten_bytes_seq(bytes_collection: Vec<Bytes>) -> Bytes {
    bytes_collection.into_iter().flatten().collect()
}




相关问题
Creating an alias for a variable

I have the following code in Rust (which will not compile but illustrates what I am after). For readability purposes, I would like to refer the same string with two different names so that the name of ...

Rust Visual Studio Code code completion not working

I m trying to learn Rust and installed the Rust extension for VSCode. But I m not seeing auto-completions for any syntax. I d like to call .trim() on String but I get no completion for it. I read that ...

热门标签