Skip to content

Commit 67b68ed

Browse files
committed
fix: 修复频繁调用LRU缓存导致的内存泄漏
1 parent 1b74d32 commit 67b68ed

2 files changed

Lines changed: 14 additions & 36 deletions

File tree

crates/project_graph/src/stage/structs.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,8 +19,18 @@ pub struct Text {
1919
pub pos: KdlPos2,
2020
#[knus(child, unwrap(argument), default = String::new())]
2121
pub val: String,
22-
pub position: Pos2,
23-
pub content: String,
22+
23+
text_width: std::sync::OnceLock<f32>,
24+
}
25+
impl Text {
26+
pub fn new(id: String, pos: Pos2, val: String) -> Self {
27+
Text {
28+
id,
29+
pos: pos.into(),
30+
val,
31+
text_width: std::sync::OnceLock::new(),
32+
}
33+
}
2434
}
2535
impl EntityTrait for Text {
2636
fn id(&self) -> &str {
Lines changed: 2 additions & 34 deletions
Original file line numberDiff line numberDiff line change
@@ -1,40 +1,8 @@
1-
use egui::{Context, FontId, Painter};
2-
use lru::LruCache;
3-
use std::num::NonZeroUsize;
4-
use std::sync::{LazyLock, Mutex};
5-
6-
#[derive(Hash, PartialEq, Eq, Clone)]
7-
struct TextWidthCacheKey {
8-
text: String,
9-
/// 浮点数不能作为哈希键,所以需要转换为整数后存储
10-
size: i32,
11-
}
12-
13-
static TEXT_WIDTH_CACHE: LazyLock<Mutex<LruCache<TextWidthCacheKey, f32>>> = LazyLock::new(|| {
14-
let cache = LruCache::new(NonZeroUsize::new(1024).unwrap());
15-
Mutex::new(cache)
16-
});
1+
use egui::{FontId, Painter};
172

183
/// 计算文字宽度
194
pub fn get_text_width(text: &str, font_size: f32, painter: &Painter) -> f32 {
20-
let key = TextWidthCacheKey {
21-
text: text.to_string(),
22-
size: (font_size * 10.0) as i32,
23-
};
24-
25-
if let Ok(mut cache) = TEXT_WIDTH_CACHE.lock() {
26-
if let Some(&width) = cache.get(&key) {
27-
return width;
28-
}
29-
}
30-
315
let font_id = FontId::proportional(font_size);
326
let galley = painter.layout_no_wrap(text.to_string(), font_id, egui::Color32::TRANSPARENT);
33-
let width = galley.size().x;
34-
35-
if let Ok(mut cache) = TEXT_WIDTH_CACHE.lock() {
36-
cache.put(key, width);
37-
}
38-
39-
width
7+
galley.size().x
408
}

0 commit comments

Comments
 (0)