How do I efficiently build a vector and an index of that vector while processing a data stream?

后端 未结 3 1898
迷失自我
迷失自我 2020-12-30 08:13

I have a struct Foo:

struct Foo {
    v: String,
    // Other data not important for the question
}

I want to handle a data st

3条回答
  •  感动是毒
    2020-12-30 08:52

    not increase the run time by using Rc or RefCell.

    @Shepmaster already demonstrated accomplishing this using unsafe, once you have I would encourage you to check how much Rc actually would cost you. Here is a full version with Rc:

    use std::{
        collections::{hash_map::Entry, HashMap},
        rc::Rc,
    };
    
    #[derive(Debug)]
    struct Foo {
        v: Rc,
    }
    
    #[derive(Debug)]
    struct Collection {
        vec: Vec,
        index: HashMap, usize>,
    }
    
    impl Foo {
        fn new(s: &str) -> Foo {
            Foo {
                v: s.into(),
            }
        }
    }
    
    impl Collection {
        fn new() -> Collection {
            Collection {
                vec: Vec::new(),
                index: HashMap::new(),
            }
        }
    
        fn insert(&mut self, foo: Foo) {
            match self.index.entry(foo.v.clone()) {
                Entry::Occupied(o) => panic!(
                    "Duplicate entry for: {}, {:?} inserted before {:?}",
                    foo.v,
                    o.get(),
                    foo
                ),
                Entry::Vacant(v) => v.insert(self.vec.len()),
            };
            self.vec.push(foo)
        }
    }
    
    fn main() {
        let mut collection = Collection::new();
    
        for foo in vec![Foo::new("Hello"), Foo::new("World"), Foo::new("Go!")] {
            collection.insert(foo)
        }
    
        println!("{:?}", collection);
    }
    

提交回复
热议问题