Highlighting / creating a vector of strings / vectors in a Rust hash map?

I'm trying to inject a toy hash into Rust from scratch and get hooked on the actual initialization of the buckets I need. I got this working with an array of buckets with other primitives such as u8 (shown below in the comments below).

I can't figure out how to tell the compiler to select me a mutable vector that contains other vectors - in this case ~str. This code compiles, but does not work at runtime with an error index out of bounds.

static DEFAULT_NUMBER_OF_BUCKETS: uint = 64;
static DEFAULT_VALUE_LENGTH: uint = 32; //unused

struct NaiveHashMap {
    hashmap_size: uint, //unused.
    string_capacity: uint, //unused.
    //contents: ~[ u8 ]
    contents: ~[ ~str ]
}

impl NaiveHashMap {

    fn new(hash_size: uint, string_size: uint) -> NaiveHashMap {
        NaiveHashMap {
            hashmap_size: hash_size, //unused
            string_capacity: string_size, //unused
            //contents: ~[ 0, ..DEFAULT_NUMBER_OF_BUCKETS ]
            contents: std::vec::with_capacity::<~str>(DEFAULT_NUMBER_OF_BUCKETS)
        }
    }

    fn get_hash(&self, key: &str) -> u32 {
        let hash: u32 = jenkins_hash(key);
        hash % self.hashmap_size.to_u32().unwrap()
    }

    //fn add(&mut self, key: &str, value: u8) {
    fn add(&mut self, key: &str, value: ~str) {
        let bucket = self.get_hash(key);
        self.contents[bucket] = value;
    }

    //fn get(self, key: &str) -> u8 {
    fn get(&self, key: &str) -> ~str {
        let bucket = self.get_hash(key);
        self.contents[bucket].clone()
    }

}

With the exception of calling insecure allocation from_buf or just copypasting std Hashmap lib, I'm not sure how to do this.

I understand that it would be better to go <T>around the class so that it is flexible, but prefer to output this bit first.

EDIT: get(), .

+3
1

, , - .

Rust , . ~[u8], () , u8 :

[0, ..DEFAULT_NUMBER_OF_BUCKETS]

~str? , Rust, . ~str, , ~"", . N :

vec::from_elem(N, ~"")

. N , , , .

T, T . , T Clone , from_elem(). T, . Option :

contents: ~[Option<T>]

, from_fn() :

contents: vec::from_fn(N, |_| None)

BTW, , "index out of bounds", , with_capacity(). , . push() , , , "" .

+6

All Articles