Optimize StorageSize performance with named constants

This commit is contained in:
Sanket Saagar Karan 2025-07-07 14:14:33 +05:30
parent bdf47f4557
commit 215aaab509
No known key found for this signature in database
GPG key ID: 63473FF9FE996CB1

View file

@ -20,21 +20,32 @@ import (
"fmt"
)
// Storage size constants for binary byte calculations
const (
// Binary byte size constants (powers of 2)
ByteSize = 1.0
KiB = 1024 * ByteSize
MiB = 1024 * KiB
GiB = 1024 * MiB
TiB = 1024 * GiB
)
// StorageSize is a wrapper around a float value that supports user friendly
// formatting.
type StorageSize float64
// String implements the stringer interface.
func (s StorageSize) String() string {
if s > 1099511627776 {
return fmt.Sprintf("%.2f TiB", s/1099511627776)
} else if s > 1073741824 {
return fmt.Sprintf("%.2f GiB", s/1073741824)
} else if s > 1048576 {
return fmt.Sprintf("%.2f MiB", s/1048576)
} else if s > 1024 {
return fmt.Sprintf("%.2f KiB", s/1024)
} else {
switch {
case s > TiB:
return fmt.Sprintf("%.2f TiB", s/TiB)
case s > GiB:
return fmt.Sprintf("%.2f GiB", s/GiB)
case s > MiB:
return fmt.Sprintf("%.2f MiB", s/MiB)
case s > KiB:
return fmt.Sprintf("%.2f KiB", s/KiB)
default:
return fmt.Sprintf("%.2f B", s)
}
}
@ -42,15 +53,16 @@ func (s StorageSize) String() string {
// TerminalString implements log.TerminalStringer, formatting a string for console
// output during logging.
func (s StorageSize) TerminalString() string {
if s > 1099511627776 {
return fmt.Sprintf("%.2fTiB", s/1099511627776)
} else if s > 1073741824 {
return fmt.Sprintf("%.2fGiB", s/1073741824)
} else if s > 1048576 {
return fmt.Sprintf("%.2fMiB", s/1048576)
} else if s > 1024 {
return fmt.Sprintf("%.2fKiB", s/1024)
} else {
switch {
case s > TiB:
return fmt.Sprintf("%.2fTiB", s/TiB)
case s > GiB:
return fmt.Sprintf("%.2fGiB", s/GiB)
case s > MiB:
return fmt.Sprintf("%.2fMiB", s/MiB)
case s > KiB:
return fmt.Sprintf("%.2fKiB", s/KiB)
default:
return fmt.Sprintf("%.2fB", s)
}
}