46 lines
907 B
Go
46 lines
907 B
Go
|
|
package formatter
|
||
|
|
|
||
|
|
import (
|
||
|
|
"fmt"
|
||
|
|
"math"
|
||
|
|
)
|
||
|
|
|
||
|
|
// FormatSize converts bytes to human-readable format
|
||
|
|
func FormatSize(bytes int64) string {
|
||
|
|
if bytes == 0 {
|
||
|
|
return "0 B"
|
||
|
|
}
|
||
|
|
|
||
|
|
const unit = 1024
|
||
|
|
units := []string{"B", "KB", "MB", "GB", "TB", "PB"}
|
||
|
|
|
||
|
|
exp := int(math.Log(float64(bytes)) / math.Log(float64(unit)))
|
||
|
|
if exp > len(units)-1 {
|
||
|
|
exp = len(units) - 1
|
||
|
|
}
|
||
|
|
|
||
|
|
value := float64(bytes) / math.Pow(float64(unit), float64(exp))
|
||
|
|
return fmt.Sprintf("%.2f %s", value, units[exp])
|
||
|
|
}
|
||
|
|
|
||
|
|
// CenterText centers text within a given width
|
||
|
|
func CenterText(text string, width int) string {
|
||
|
|
if len(text) >= width {
|
||
|
|
return text[:width]
|
||
|
|
}
|
||
|
|
|
||
|
|
padding := width - len(text)
|
||
|
|
left := padding / 2
|
||
|
|
right := padding - left
|
||
|
|
|
||
|
|
return fmt.Sprintf("%s%s%s", repeat(" ", left), text, repeat(" ", right))
|
||
|
|
}
|
||
|
|
|
||
|
|
func repeat(s string, count int) string {
|
||
|
|
result := ""
|
||
|
|
for i := 0; i < count; i++ {
|
||
|
|
result += s
|
||
|
|
}
|
||
|
|
return result
|
||
|
|
}
|