camper/pkg/template/humanize.go

31 lines
595 B
Go
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

/*
* SPDX-FileCopyrightText: 20122015 Dustin Sallings <dustin@spy.net>
* SPDX-License-Identifier: MIT
*/
package template
import (
"fmt"
"math"
)
func humanizeBytes(s int64) string {
if s < 10 {
return fmt.Sprintf("%d B", s)
}
base := 1024.0
e := math.Floor(logn(float64(s), base))
val := math.Floor(float64(s)/math.Pow(base, e)*10+0.5) / 10
f := "%.0f %s"
if val < 10 {
f = "%.1f %s"
}
sizes := []string{"B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB"}
return fmt.Sprintf(f, val, sizes[int(e)])
}
func logn(n, b float64) float64 {
return math.Log(n) / math.Log(b)
}