mirror of
https://github.com/aptly-dev/aptly.git
synced 2026-01-12 03:21:33 +00:00
Function HumanBytes for human-readable representation of numbers. #18
This commit is contained in:
22
utils/human.go
Normal file
22
utils/human.go
Normal file
@@ -0,0 +1,22 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
)
|
||||
|
||||
// Convert bytes to human readable string
|
||||
func HumanBytes(i int64) (result string) {
|
||||
switch {
|
||||
case i > (512 * 1024 * 1024 * 1024):
|
||||
result = fmt.Sprintf("%#.02f TiB", float64(i)/1024/1024/1024/1024)
|
||||
case i > (512 * 1024 * 1024):
|
||||
result = fmt.Sprintf("%#.02f GiB", float64(i)/1024/1024/1024)
|
||||
case i > (512 * 1024):
|
||||
result = fmt.Sprintf("%#.02f MiB", float64(i)/1024/1024)
|
||||
case i > 512:
|
||||
result = fmt.Sprintf("%#.02f KiB", float64(i)/1024)
|
||||
default:
|
||||
result = fmt.Sprintf("%d B", i)
|
||||
}
|
||||
return
|
||||
}
|
||||
21
utils/human_test.go
Normal file
21
utils/human_test.go
Normal file
@@ -0,0 +1,21 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
. "launchpad.net/gocheck"
|
||||
)
|
||||
|
||||
type HumanSuite struct{}
|
||||
|
||||
var _ = Suite(&HumanSuite{})
|
||||
|
||||
func (s *HumanSuite) TestHumanBytes(c *C) {
|
||||
c.Check(HumanBytes(50), Equals, "50 B")
|
||||
c.Check(HumanBytes(968), Equals, "0.95 KiB")
|
||||
c.Check(HumanBytes(20480), Equals, "20.00 KiB")
|
||||
c.Check(HumanBytes(700480), Equals, "0.67 MiB")
|
||||
c.Check(HumanBytes(7000480), Equals, "6.68 MiB")
|
||||
c.Check(HumanBytes(824000480), Equals, "0.77 GiB")
|
||||
c.Check(HumanBytes(82400000480), Equals, "76.74 GiB")
|
||||
c.Check(HumanBytes(824000000480), Equals, "0.75 TiB")
|
||||
c.Check(HumanBytes(824000000000480), Equals, "749.42 TiB")
|
||||
}
|
||||
Reference in New Issue
Block a user