Skip to content

Commit

Permalink
Added docs and made func signature explicit (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
tkivisik authored and egonelbre committed Oct 6, 2019
1 parent 6cddfc8 commit 866ad2c
Showing 1 changed file with 17 additions and 15 deletions.
32 changes: 17 additions & 15 deletions memory/size.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,23 +11,25 @@ func (bytes Bytes) String() string {
return ToString(int64(bytes))
}

func ToString(s int64) string {
size := float64(s)
// ToString returns a given size in bytes as a human size string.
// Examples: ToString(1) ==> "1B"; ToString(1000) ==> "1KB"
func ToString(size int64) string {
s := float64(size)

switch {
case size >= (1<<60)*2/3:
return fmt.Sprintf("%.1fEB", size/(1<<60))
case size >= (1<<50)*2/3:
return fmt.Sprintf("%.1fPB", size/(1<<50))
case size >= (1<<40)*2/3:
return fmt.Sprintf("%.1fTB", size/(1<<40))
case size >= (1<<30)*2/3:
return fmt.Sprintf("%.1fGB", size/(1<<30))
case size >= (1<<20)*2/3:
return fmt.Sprintf("%.1fMB", size/(1<<20))
case size >= (1<<10)*2/3:
return fmt.Sprintf("%.1fKB", size/(1<<10))
case s >= (1<<60)*2/3:
return fmt.Sprintf("%.1fEB", s/(1<<60))
case s >= (1<<50)*2/3:
return fmt.Sprintf("%.1fPB", s/(1<<50))
case s >= (1<<40)*2/3:
return fmt.Sprintf("%.1fTB", s/(1<<40))
case s >= (1<<30)*2/3:
return fmt.Sprintf("%.1fGB", s/(1<<30))
case s >= (1<<20)*2/3:
return fmt.Sprintf("%.1fMB", s/(1<<20))
case s >= (1<<10)*2/3:
return fmt.Sprintf("%.1fKB", s/(1<<10))
}

return strconv.Itoa(int(s)) + "B"
return strconv.Itoa(int(size)) + "B"
}

0 comments on commit 866ad2c

Please sign in to comment.