From 13895d0bd314b0a735d6c00efc53a2f5eeb8b855 Mon Sep 17 00:00:00 2001 From: Rohan Singh Date: Thu, 19 Sep 2024 04:17:47 -0400 Subject: [PATCH] Don't panic on empty plot data --- render/plot.go | 44 +++++++++++++++++++++++++------------------- render/plot_test.go | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 57 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..ca63d57292 100644 --- a/render/plot_test.go +++ b/render/plot_test.go @@ -105,6 +105,7 @@ func TestPlotComputeLimits(t *testing.T) { } check(2, 2.5, 3.14-0.5, 3.14+0.5) + reset() } // Tests of the internal translatePoints() method @@ -301,6 +302,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{