runtime/metrics: fix Read panic on empty slice

Add a length check in metrics.Read to handle empty slices gracefully.
Previously, passing an empty slice would panic due to accessing &m[0]
on a zero-length slice.

The fix ensures Read is a no-op for empty inputs, which is the
expected behavior.

Fixes #77231
This commit is contained in:
Amol Yadav
2026-01-23 16:21:34 +05:30
parent 7251c9e0f0
commit 6f24f67b18
2 changed files with 10 additions and 0 deletions

View File

@@ -156,3 +156,10 @@ func TestDocs(t *testing.T) {
fmt.Fprintf(os.Stderr, "go test -generate: doc.go already up-to-date\n")
}
}
func TestReadEmptySlice(t *testing.T) {
// Test that Read does not panic when given an empty slice.
// This should be a no-op.
metrics.Read(nil)
metrics.Read([]metrics.Sample{})
}

View File

@@ -43,5 +43,8 @@ func runtime_readMetrics(unsafe.Pointer, int, int)
// Sample values with names not appearing in [All] will have their Value populated
// as KindBad to indicate that the name is unknown.
func Read(m []Sample) {
if len(m) == 0 {
return
}
runtime_readMetrics(unsafe.Pointer(&m[0]), len(m), cap(m))
}