gpt4 book ai didi

stream - 使用 PhantomData 和 unsafe 将流式迭代器作为普通迭代器处理

转载 作者:行者123 更新时间:2023-11-29 08:34:52 24 4
gpt4 key购买 nike

我知道下面的代码是 hacky,但它可以被称为安全和惯用的 Rust 吗?有更好的方法吗?

// needs to do 'rustup default nightly' to run under valgrind
// #![feature(alloc_system, global_allocator, allocator_api)]
// extern crate alloc_system;
// use alloc_system::System;
// #[global_allocator]
// static A: System = System;

struct Foo<'a> {
v: Vec<u8>,
pos: usize,
phantom: std::marker::PhantomData<&'a u8>,
}

impl<'a> Iterator for Foo<'a> {
type Item = &'a mut u8;

fn next(&mut self) -> Option<&'a mut u8> {
let r = self.v.get_mut(self.pos);
if r.is_some() {
self.pos += 1;
unsafe { Some(&mut *(r.unwrap() as *mut u8)) }
} else {
None
}
}
}

impl<'a> Foo<'a> {
fn reset(&mut self) {
self.pos = 0;
}
}

fn main() {
let mut x = Foo {
v: (1..10).collect(),
pos: 0,
phantom: std::marker::PhantomData,
};
let vp = x.v.as_ptr();

{
for i in &mut x {
println!("{}", i);
}
}
{
x.reset();
}
{
for i in &mut x {
*i *= *i;
}
}
{
x.reset();
}
{
for i in &mut x {
println!("{}", i);
}
}

assert!(vp == x.v.as_ptr());
}

在评论中写一点,Valgrind 告诉我没有泄漏,结果在 Rust 1.26.0-nightly 和 1.25.0 下符合预期。

相关:

最佳答案

此代码不安全。该类型的用户可以选择任何生命周期,包括'static:

fn constructor() -> Foo<'static> {
Foo {
v: vec![42; 10],
pos: 0,
phantom: std::marker::PhantomData,
}
}

fn example() -> &'static u8 {
let mut f = constructor();
f.next().unwrap()
}

fn main() {
println!("example: {}", example());
}

在这里,example 返回对不再在范围内的变量的引用,访问无效内存并破坏您必须坚持的限制。


an example of how you could write this code在另一个问答中没有任何unsafe

关于stream - 使用 PhantomData 和 unsafe 将流式迭代器作为普通迭代器处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49683888/

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