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

Stream 使用PhantomData和unsafe将流迭代器作为普通迭代器处理,stream,iterator,rust,unsafe,Stream,Iterator,Rust,Unsafe,我知道下面的代码很粗糙,但它能被称为安全的、惯用的代码吗?有更好的办法吗 // 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] // stat

我知道下面的代码很粗糙,但它能被称为安全的、惯用的代码吗?有更好的办法吗

// 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());
}
//需要执行“rustup default nightly”才能在valgrind下运行
// #![功能(alloc_系统、全局_分配器、分配器_api)]
//外部板条箱分配系统;
//使用alloc_system::system;
//#[全局分配程序]
//静态A:系统=系统;
结构富,
}
恳求{
类型项=&'a mut u8;

fn next(&mut self)->选项Foo此代码不安全。该类型的用户可以选择任何生存期,包括静态

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());
}

fn构造函数()->foo每当编写
不安全的
块时,我强烈建议人们在块上添加注释,解释为什么您认为代码实际上是安全的。这类信息对将来阅读代码的人很有用,并且对任何潜在的回答者都很有用。请您的问题解释您为什么这样认为代码实际上是安全的谢谢你总是及时的回复。谈到
不安全的
,我没有想到,对不起。我意识到我只是试图欺骗生命周期检查器。valgrind实际上报告了你的
示例()
代码读取无效。没有办法做你想做的事情(相信我,我试过了)。您必须等待泛型关联类型和Rust迭代器的更新。