为什么Piston text()需要对字形缓存的可变引用?

时间:2016-12-31 02:15:00

标签: rust rust-piston

我很好奇为什么text()需要 mutable 借用字形缓存:

cache: &mut C

我的理解是,glyphe缓存表示从字体文件加载的静态字符(字形)。为什么那些需要能够被底层图形系统变异?

1 个答案:

答案 0 :(得分:4)

因为如果您始终关注Text中的代码,那么appears that it loads each character on demand on a per-font-size basis。如果你要求它有一个大小的字符,它没有缓存,它将加载它 - 这需要一个可变的引用,以便修改其内部状态。实际上,它是使用entry API的第一部分 - 需要一个可变引用:fn entry(&mut self, key: K) -> Entry<K, V>

有问题的代码:

impl<'a> graphics::character::CharacterCache for GlyphCache<'a> {
    type Texture = Texture;

    fn character(&mut self, size: FontSize, ch: char) -> &Character {
        match {
            match self.data.entry(size) { // <----- BAM!
                Vacant(entry) => entry.insert(HashMap::new()), 
                Occupied(entry) => entry.into_mut(),
            }
        }.contains_key(&ch) {
            true => &self.data[&size][&ch],
            false => { self.load_character(size, ch); &self.data[&size][&ch] }
            // ^^^^ BAM!
        }
    }
}