improved metrics implementation

This commit is contained in:
yusing
2025-02-13 05:58:30 +08:00
parent fd50f8fcab
commit 3c7fafa91f
11 changed files with 262 additions and 83 deletions

View File

@@ -74,7 +74,7 @@ func formatFloat(f float64) string {
return strconv.FormatFloat(f, 'f', -1, 64)
}
func FormatByteSize[T ~uint64](size T) string {
func FormatByteSize[T ~uint64 | ~float64](size T) (value, unit string) {
const (
_ = (1 << (10 * iota))
kb
@@ -85,20 +85,25 @@ func FormatByteSize[T ~uint64](size T) string {
)
switch {
case size < kb:
return fmt.Sprintf("%d B", size)
return fmt.Sprintf("%v", size), "B"
case size < mb:
return formatFloat(float64(size)/kb) + "KiB"
return formatFloat(float64(size) / kb), "KiB"
case size < gb:
return formatFloat(float64(size)/mb) + "MiB"
return formatFloat(float64(size) / mb), "MiB"
case size < tb:
return formatFloat(float64(size)/gb) + "GiB"
return formatFloat(float64(size) / gb), "GiB"
case size < pb:
return formatFloat(float64(size/gb)/kb) + "TiB" // prevent overflow
return formatFloat(float64(size/gb) / kb), "TiB" // prevent overflow
default:
return formatFloat(float64(size/tb)/kb) + "PiB" // prevent overflow
return formatFloat(float64(size/tb) / kb), "PiB" // prevent overflow
}
}
func FormatByteSizeWithUnit[T ~uint64 | ~float64](size T) string {
value, unit := FormatByteSize(size)
return value + " " + unit
}
func PortString(port uint16) string {
return strconv.FormatUint(uint64(port), 10)
}