Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 1 | // Copyright 2009 The Go Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style |
| 3 | // license that can be found in the LICENSE file. |
| 4 | |
| 5 | package main |
| 6 | |
| 7 | import "fmt" |
| 8 | |
| 9 | type ByteSize float64 |
| 10 | |
| 11 | const ( |
| 12 | _ = iota // ignore first value by assigning to blank identifier |
| 13 | KB ByteSize = 1 << (10 * iota) |
| 14 | MB |
| 15 | GB |
| 16 | TB |
| 17 | PB |
| 18 | EB |
| 19 | ZB |
| 20 | YB |
| 21 | ) |
| 22 | |
| 23 | func (b ByteSize) String() string { |
| 24 | switch { |
| 25 | case b >= YB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 26 | return fmt.Sprintf("%.2fYB", b/YB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 27 | case b >= ZB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 28 | return fmt.Sprintf("%.2fZB", b/ZB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 29 | case b >= EB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 30 | return fmt.Sprintf("%.2fEB", b/EB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 31 | case b >= PB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 32 | return fmt.Sprintf("%.2fPB", b/PB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 33 | case b >= TB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 34 | return fmt.Sprintf("%.2fTB", b/TB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 35 | case b >= GB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 36 | return fmt.Sprintf("%.2fGB", b/GB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 37 | case b >= MB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 38 | return fmt.Sprintf("%.2fMB", b/MB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 39 | case b >= KB: |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 40 | return fmt.Sprintf("%.2fKB", b/KB) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 41 | } |
Rob Pike | 4074795 | 2012-03-25 11:34:51 +1100 | [diff] [blame] | 42 | return fmt.Sprintf("%.2fB", b) |
Rob Pike | 18b21c7 | 2011-08-22 22:46:59 +1000 | [diff] [blame] | 43 | } |
| 44 | |
| 45 | func main() { |
| 46 | fmt.Println(YB, ByteSize(1e13)) |
| 47 | } |