- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
tl;博士 创建一些字节存储的最佳“Rust 方式”是什么,在这种情况下是 Vec<u8>
,存储该 Vec<u8>
在 struct
可以使用键值访问的字段(例如 BTreeMap<usize, &Vec<u8>>
),然后读取这些 Vec<u8>
来自其他一些 struct
?
这可以外推到类似的一般良好的防 rust 设计struct
s 充当字节块( Vec<u8>
、 [u8; 16384]
等)的存储和缓存,可通过键(usize
偏移量、u32
索引、String
文件路径等)访问?
目标
我正在尝试创建一个字节存储 struct
和 impl
功能:
Vec<u8>
的“块”中容量 16384 struct
会分析各种Vec<u8>
并且可能需要存储自己对这些“块”的引用 struct BlockReader
那
Vec<u8>
( Vec<u8>::with_capacity(16384)
) 输入为 Block
File::seek
和 File::take::read_to_end
)并存储 u8
的 16384成Vec<u8>
Vec<u8>
的引用内BTreeMap
输入为 Blocks
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Read;
use std::fs::File;
use std::collections::BTreeMap;
type Block = Vec<u8>;
type Blocks<'a> = BTreeMap<usize, &'a Block>;
pub struct BlockReader<'a> {
blocks: Blocks<'a>,
file: File,
}
impl<'a> BlockReader<'a> {
/// read a "block" of 16384 `u8` at file offset
/// `offset` which is multiple of 16384
/// if the "block" at the `offset` is cached in
/// `self.blocks` then return a reference to that
/// XXX: assume `self.file` is already `open`ed file
/// handle
fn readblock(& mut self, offset: usize) -> Result<&Block, std::io::Error> {
// the data at this offset is the "cache"
// return reference to that
if self.blocks.contains_key(&offset) {
return Ok(&self.blocks[&offset]);
}
// have not read data at this offset so read
// the "block" of data from the file, store it,
// return a reference
let mut buffer = Block::with_capacity(16384);
self.file.seek(SeekFrom::Start(offset as u64))?;
self.file.read_to_end(&mut buffer);
self.blocks.insert(offset, & buffer);
Ok(&self.blocks[&offset])
}
}
用例问题示例
BlockReader.readblock
来自
struct BlockAnalyzer1
造成了无穷无尽的困难:
pub struct BlockAnalyzer1<'b> {
pub blockreader: BlockReader<'b>,
}
impl<'b> BlockAnalyzer1<'b> {
/// contrived example function
pub fn doStuff(&mut self) -> Result<bool, std::io::Error> {
let mut b: &Block;
match self.blockreader.readblock(3 * 16384) {
Ok(val) => {
b = val;
},
Err(err) => {
return Err(err);
}
}
match self.blockreader.readblock(5 * 16384) {
Ok(val) => {
b = val;
},
Err(err) => {
return Err(err);
}
}
Ok(true)
}
}
结果是
error[E0597]: `buffer` does not live long enough
--> src/lib.rs:34:36
|
15 | impl<'a> BlockReader<'a> {
| -- lifetime `'a` defined here
...
34 | self.blocks.insert(offset, & buffer);
| ---------------------------^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `buffer` is borrowed for `'a`
35 | Ok(&self.blocks[&offset])
36 | }
| - `buffer` dropped here while still borrowed
但是,对于这种设计的不同排列,我遇到了许多其他错误,例如我遇到的另一个错误
error[E0499]: cannot borrow `self.blockreader` as mutable more than once at a time
--> src/main.rs:543:23
|
463 | impl<'a> BlockUser1<'a> {
| ----------- lifetime `'a` defined here
...
505 | match self.blockreader.readblock(3 * 16384) {
| ---------------------------------------
| |
| first mutable borrow occurs here
| argument requires that `self.blockreader` is borrowed for `'a`
...
543 | match self.blockreader.readblock(5 * 16384) {
| ^^^^^^^^^^^^^^^^ second mutable borrow occurs here
在
BlockReader
,我已经尝试使用
Block
对“
Vec<u8>
”存储进行排列,
&Vec<u8>
,
Box<Vec<u8>>
,
Box<&Vec<u8>>
,
&Box<&Vec<u8>>
,
&Pin<&Box<&Vec<u8>>
等等。然而,每个实现排列都会遇到各种与借用、生命周期和可变性相关的混淆问题。
struct
管理的字节块, 还有其他
struct
获取对字节块的引用(或指针等),在循环中读取该字节块(同时可能存储新的字节块)。
Vec<u8>
( Block
) 在 BlockReader.blocks
,还允许其他 Struct
将他们自己的引用(或指针,或对指针的引用,或固定框指针等)存储到 Block
?
struct
s 复制或克隆
Box<Block>
或
Pin<Box<Block>>
或者是其他东西?
type Block = [u8; 16384];
更容易传递引用?
Struct
喜欢
BlockUser1
给予
&Block
, 或
Box<Block>
, 或
&Pin<&Box<&Block>
, 或者是其他东西?
Vec<u8>
(
Block
) 被写入一次(在
BlockReader.readblock
期间)并且可以被其他
Struct
多次读取s 调用
BlockReader.readblock
后来通过保存他们自己的引用/指针/等。到那个
Block
(理想情况下,也许这不理想?)。
最佳答案
你可以把Vec<u8>
在 Rc<RefCell<...>>
后面或者只是一个 Rc<..>
如果它们是不可变的。
如果您需要线程安全访问,则需要使用 Arc<Mutex<...>>
或 Arc<RwLock<...>>
反而。
这是您的代码的转换版本。 (有一些拼写错误和位需要更改才能编译 - 你应该在你的例子中真正修复这些,并给我们一些几乎可以编译的东西......)
您也可以在 playground 中看到这一点。
use std::io::Seek;
use std::io::SeekFrom;
use std::io::Read;
use std::fs::File;
use std::cell::RefCell;
use std::rc::Rc;
use std::collections::BTreeMap;
type Block = Vec<u8>;
type Blocks = BTreeMap<usize, Rc<RefCell<Block>>>;
pub struct BlockReader {
blocks: Blocks,
file: File,
}
impl BlockReader {
/// read a "block" of 16384 `u8` at file offset
/// `offset` which is multiple of 16384
/// if the "block" at the `offset` is cached in
/// `self.blocks` then return a reference to that
/// XXX: assume `self.file` is already `open`ed file
/// handle
fn readblock(& mut self, offset: usize) -> Result<Rc<RefCell<Block>>,std::io::Error> {
// the data at this offset is the "cache"
// return reference to that
if self.blocks.contains_key(&offset) {
return Ok(self.blocks[&offset].clone());
}
// have not read data at this offset so read
// the "block" of data from the file, store it,
// return a reference
let mut buffer = Block::with_capacity(16384);
self.file.seek(SeekFrom::Start(offset as u64))?;
self.file.read_to_end(&mut buffer);
self.blocks.insert(offset, Rc::new(RefCell::new(buffer)));
Ok(self.blocks[&offset].clone())
}
}
pub struct BlockAnalyzer1 {
pub blockreader: BlockReader,
}
impl BlockAnalyzer1 {
/// contrived example function
pub fn doStuff(&mut self) -> Result<bool,std::io::Error> {
let mut b: Rc<RefCell<Block>>;
match self.blockreader.readblock(3 * 16384) {
Ok(val) => {
b = val;
},
Err(err) => {
return Err(err);
}
}
match self.blockreader.readblock(5 * 16384) {
Ok(val) => {
b = val;
},
Err(err) => {
return Err(err);
}
}
Ok(true)
}
}
关于Rust 设计存储结构和只读结构用户的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68991015/
编辑备注 由于 Rust(版本:1.42)仍然没有稳定的 ABI ,推荐使用extern (目前相当于extern "C"(将来可能会改变))否则,可能需要重新编译库。 This article解释如
词法分析器/解析器文件位于 here非常大,我不确定它是否适合只检索 Rust 函数列表。也许我自己编写/使用另一个库是更好的选择? 最终目标是创建一种执行管理器。为了上下文化,它将能够读取包装在函数
我试图在 Rust 中展平 Enum 的向量,但我遇到了一些问题: enum Foo { A(i32), B(i32, i32), } fn main() { let vf =
我正在 64 位模式下运行的 Raspberry Pi 3 上使用 Rust 进行裸机编程。我已经实现了一个自旋锁,如下所示: use core::{sync::atomic::{AtomicBool
我无法理解以下示例是如何从 this code 中提炼出来的, 编译: trait A: B {} trait B {} impl B for T where T: A {} struct Foo;
在我写了一些代码和阅读了一些文章之后,我对 Rust 中的移动语义有点困惑,我认为值移动后,它应该被释放,内存应该是无效的。所以我尝试写一些代码来作证。 第一个例子 #[derive(Debug)]
https://doc.rust-lang.org/reference/types/closure.html#capture-modes struct SetVec { set: HashSe
考虑 const-generic 数据结构的经典示例:方矩阵。 struct Matrix { inner: [[T; N]; N] } 我想返回一个结构体,其 const 参数是动态定义的:
以下代码无法编译,因为 x在移动之后使用(因为 x 具有类型 &mut u8 ,它没有实现 Copy 特性) fn main() { let mut a: u8 = 1; let x:
我在玩 Rust,发现了下面的例子: fn main() { let mut x = [3, 4, 5].to_vec(); x; println!("{:?}", x); }
假设一个 Rust 2018 宏定义了一个 async里面的功能。它将使用的语法与 Rust 2015 不兼容。因此,如果您使用 2015 版编译您的 crate,那么宏中的扩展代码不会与它冲突吗?
假设我有一些 Foo 的自定义集合s: struct Bar {} struct Foo { bar: Bar } struct SubList { contents: Vec, }
代码如下: fn inner(x:&'a i32, _y:&'b i32) -> &'b i32 { x } fn main() { let a = 1; { let b
在lifetime_things的定义中,'b的生命周期比'a长,但实际上当我调用这个函数时,x1比y1长,但是这样可以编译成功: //here you could see 'b:'a means
我正在尝试检索 FLTK-RS Widget 周围的 Arc Mutex 包装器的内部值: pub struct ArcWidget(Arc>); impl ArcWidget{ pub
如下代码所示,我想封装一个定时函数,返回一个闭包的结果和执行时间。 use tap::prelude::Pipe; use std::time::{Instant, Duration}; pub fn
我想实现自己的通用容器,这是我正在使用的特征的片段: pub trait MyVec where Self: Default + Clone + IntoIterator, Self:
所需代码: 注释掉的块可以编译并工作,但是我想从嵌套的匹配样式转变为更简洁的函数链 async fn ws_req_resp(msg: String, conn: PgConn) -> Result>
我正在尝试编写一些代码,该代码将生成具有随机值的随机结构。对于结构,我具有以下特征和帮助程序宏: use rand::{thread_rng, Rng}; use std::fmt; pub trai
我有一个带有函数成员的结构: struct Foo { fun: Box, } type FooI = Foo; 这不起作用: error[E0106]: missing lifetime s
我是一名优秀的程序员,十分优秀!