Skip to content

Commit a72af10

Browse files
authored
gg: add explicit bounds checking for image caching methods in gg (fix #25590) (#25591)
1 parent f786469 commit a72af10

File tree

2 files changed

+29
-1
lines changed

2 files changed

+29
-1
lines changed

vlib/gg/image.v

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -46,11 +46,17 @@ pub fn (mut ctx Context) cache_image(img Image) int {
4646
return image_idx
4747
}
4848

49+
const missing_image = Image{}
50+
4951
// get_cached_image_by_idx returns a cached `Image` identified by `image_idx`.
52+
// If image not found, returns `Image{ok: false}`
5053
//
5154
// See also: cache_image
5255
// See also: remove_cached_image_by_idx
5356
pub fn (mut ctx Context) get_cached_image_by_idx(image_idx int) &Image {
57+
if image_idx < 0 || image_idx > ctx.image_cache.len - 1 {
58+
return &missing_image
59+
}
5460
return &ctx.image_cache[image_idx]
5561
}
5662

@@ -60,7 +66,10 @@ pub fn (mut ctx Context) get_cached_image_by_idx(image_idx int) &Image {
6066
// See also: cache_image
6167
// See also: get_cached_image_by_idx
6268
pub fn (mut ctx Context) remove_cached_image_by_idx(image_idx int) {
63-
ctx.image_cache.delete(image_idx)
69+
if image_idx < 0 || image_idx > ctx.image_cache.len - 1 {
70+
return
71+
}
72+
ctx.image_cache[image_idx] = &missing_image
6473
}
6574

6675
// Draw part of an image using uv coordinates

vlib/gg/image_test.v

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// vtest build: !docker-ubuntu-musl // needs GL/gl.h
2+
import gg
3+
4+
fn test_get_cached_image_idx_bounds_checking() {
5+
mut ctx := gg.new_context(width: 100)
6+
assert ctx.get_cached_image_by_idx(-1).ok == false
7+
assert ctx.get_cached_image_by_idx(1).ok == false
8+
}
9+
10+
fn test_remove_cached_image_remove_and_get() {
11+
mut ctx := gg.new_context(width: 100)
12+
image := gg.Image{
13+
ok: true
14+
}
15+
idx := ctx.cache_image(image)
16+
assert ctx.get_cached_image_by_idx(idx).ok == true
17+
ctx.remove_cached_image_by_idx(idx)
18+
assert ctx.get_cached_image_by_idx(idx).ok == false
19+
}

0 commit comments

Comments
 (0)