Skip to content

Commit

Permalink
Fix use of reflect.StringHeader in prometheus/metric.go
Browse files Browse the repository at this point in the history
The `go vet` command in Go 1.16 reports a warning for inappropriate
use of reflect.StringHeader.

golang/go#40701

Its use in prometheus/metric.go to convert a byte array to a string in
place began to trigger the warning. That code has been replaced with a
safer variant that avoids the `vet` warning and still converts the array
without allocating new memory.

https://stackoverflow.com/a/66865482
  • Loading branch information
bhavanki committed Aug 12, 2021
1 parent 1cae955 commit 19eb7ef
Showing 1 changed file with 9 additions and 4 deletions.
13 changes: 9 additions & 4 deletions prometheus/metric.go
Original file line number Diff line number Diff line change
Expand Up @@ -402,10 +402,15 @@ func le(buckets []stats.Value) string {
b = appendFloat(b, valueOf(v))
}

return *(*string)(unsafe.Pointer(&reflect.StringHeader{
Data: uintptr(unsafe.Pointer(&b[0])),
Len: len(b),
}))
// This code block converts the byte array to a string without additional
// memory allocation.
// Source: https://stackoverflow.com/a/66865482 (license: CC BY-SA 4.0)
sliceHeader := (*reflect.SliceHeader)(unsafe.Pointer(&b))
var s string
sh := (*reflect.StringHeader)(unsafe.Pointer(&s))
sh.Data = sliceHeader.Data
sh.Len = sliceHeader.Len
return s
}

func nextLe(s string) (head string, tail string) {
Expand Down

0 comments on commit 19eb7ef

Please sign in to comment.