Skip to content

Commit e81ebab

Browse files
committed
fix: add validation to set_pdf_color in pdf_core to prevent crashes
- Added IEEE_ARITHMETIC validation to set_pdf_color subroutine - Handles NaN, infinity, and out-of-range RGB values gracefully - Clamps values to valid [0,1] range to prevent PDF format errors - Fixes colored_contours example crash during GitHub Pages deployment - Ensures all PDF color operations are safe regardless of input data This completes the validation coverage across all PDF color writing functions.
1 parent ca9c358 commit e81ebab

File tree

1 file changed

+18
-1
lines changed

1 file changed

+18
-1
lines changed

src/fortplot_pdf_core.f90

Lines changed: 18 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -68,11 +68,28 @@ subroutine initialize_pdf_stream(ctx)
6868
end subroutine initialize_pdf_stream
6969

7070
subroutine set_pdf_color(this, r, g, b)
71+
use, intrinsic :: ieee_arithmetic, only: ieee_is_finite
7172
class(pdf_context_core), intent(inout) :: this
7273
real(wp), intent(in) :: r, g, b
7374
character(len=64) :: color_cmd
75+
real(wp) :: safe_r, safe_g, safe_b
7476

75-
write(color_cmd, '(F0.3, 1X, F0.3, 1X, F0.3, " RG")') r, g, b
77+
! Validate and clamp RGB values to prevent PDF format errors
78+
safe_r = r
79+
safe_g = g
80+
safe_b = b
81+
82+
! Handle NaN and infinity
83+
if (.not. ieee_is_finite(safe_r)) safe_r = 0.0_wp
84+
if (.not. ieee_is_finite(safe_g)) safe_g = 0.0_wp
85+
if (.not. ieee_is_finite(safe_b)) safe_b = 0.0_wp
86+
87+
! Clamp to [0,1] range
88+
safe_r = max(0.0_wp, min(1.0_wp, safe_r))
89+
safe_g = max(0.0_wp, min(1.0_wp, safe_g))
90+
safe_b = max(0.0_wp, min(1.0_wp, safe_b))
91+
92+
write(color_cmd, '(F0.3, 1X, F0.3, 1X, F0.3, " RG")') safe_r, safe_g, safe_b
7693
this%stream_data = this%stream_data // trim(adjustl(color_cmd)) // new_line('a')
7794
end subroutine set_pdf_color
7895

0 commit comments

Comments
 (0)