From 29745c1a000b8d1874f03b57f5a4fdf94991fbdb Mon Sep 17 00:00:00 2001 From: Rohan Singh Date: Thu, 19 Sep 2024 04:21:52 -0400 Subject: [PATCH] Don't panic on empty plot data (#1090) --- render/plot.go | 44 +++++++++++++++++++++++++------------------- render/plot_test.go | 31 +++++++++++++++++++++++++++++++ 2 files changed, 56 insertions(+), 19 deletions(-) diff --git a/render/plot.go b/render/plot.go index 3fc6c701f2..351129682c 100644 --- a/render/plot.go +++ b/render/plot.go @@ -29,25 +29,27 @@ var FillDampFactor uint8 = 0x55 // // EXAMPLE BEGIN // render.Plot( -// data = [ -// (0, 3.35), -// (1, 2.15), -// (2, 2.37), -// (3, -0.31), -// (4, -3.53), -// (5, 1.31), -// (6, -1.3), -// (7, 4.60), -// (8, 3.33), -// (9, 5.92), -// ], -// width = 64, -// height = 32, -// color = "#0f0", -// color_inverted = "#f00", -// x_lim = (0, 9), -// y_lim = (-5, 7), -// fill = True, +// +// data = [ +// (0, 3.35), +// (1, 2.15), +// (2, 2.37), +// (3, -0.31), +// (4, -3.53), +// (5, 1.31), +// (6, -1.3), +// (7, 4.60), +// (8, 3.33), +// (9, 5.92), +// ], +// width = 64, +// height = 32, +// color = "#0f0", +// color_inverted = "#f00", +// x_lim = (0, 9), +// y_lim = (-5, 7), +// fill = True, +// // ), // EXAMPLE END type Plot struct { @@ -95,6 +97,10 @@ func (p *Plot) computeLimits() (float64, float64, float64, float64) { } // Otherwise we'll need min/max of X and Y + if len(p.Data) == 0 { + return 0, 1, 0, 1 + } + pt := p.Data[0] minX, maxX, minY, maxY := pt[0], pt[0], pt[1], pt[1] for i := 1; i < len(p.Data); i++ { diff --git a/render/plot_test.go b/render/plot_test.go index 58aa8484a7..67e003fca3 100644 --- a/render/plot_test.go +++ b/render/plot_test.go @@ -301,6 +301,37 @@ func TestPlotJaggedLine(t *testing.T) { } +func TestPlotEmpty(t *testing.T) { + ic := ImageChecker{ + Palette: map[string]color.RGBA{ + "1": {0xff, 0xff, 0xff, 0xff}, + ".": {0, 0, 0, 0}, + }, + } + + p := Plot{ + Width: 10, + Height: 10, + Data: [][2]float64{}, + XLim: Empty, + YLim: Empty, + } + + assert.Equal(t, nil, ic.Check([]string{ + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + "..........", + }, PaintWidget(p, image.Rect(0, 0, 100, 100), 0))) + +} + func TestPlotFewPoints(t *testing.T) { ic := ImageChecker{ Palette: map[string]color.RGBA{