github.com/vmware/govmomi@v0.51.0/units/size.go (about) 1 // © Broadcom. All Rights Reserved. 2 // The term “Broadcom” refers to Broadcom Inc. and/or its subsidiaries. 3 // SPDX-License-Identifier: Apache-2.0 4 5 package units 6 7 import ( 8 "errors" 9 "fmt" 10 "regexp" 11 "strconv" 12 ) 13 14 type ByteSize int64 15 16 const ( 17 _ = iota 18 KB = 1 << (10 * iota) 19 MB 20 GB 21 TB 22 PB 23 EB 24 ) 25 26 func (b ByteSize) String() string { 27 switch { 28 case b >= EB: 29 return fmt.Sprintf("%.1fEB", float32(b)/EB) 30 case b >= PB: 31 return fmt.Sprintf("%.1fPB", float32(b)/PB) 32 case b >= TB: 33 return fmt.Sprintf("%.1fTB", float32(b)/TB) 34 case b >= GB: 35 return fmt.Sprintf("%.1fGB", float32(b)/GB) 36 case b >= MB: 37 return fmt.Sprintf("%.1fMB", float32(b)/MB) 38 case b >= KB: 39 return fmt.Sprintf("%.1fKB", float32(b)/KB) 40 } 41 return fmt.Sprintf("%dB", b) 42 } 43 44 type FileSize int64 45 46 func (b FileSize) String() string { 47 switch { 48 case b >= EB: 49 return fmt.Sprintf("%.1fE", float32(b)/EB) 50 case b >= PB: 51 return fmt.Sprintf("%.1fP", float32(b)/PB) 52 case b >= TB: 53 return fmt.Sprintf("%.1fT", float32(b)/TB) 54 case b >= GB: 55 return fmt.Sprintf("%.1fG", float32(b)/GB) 56 case b >= MB: 57 return fmt.Sprintf("%.1fM", float32(b)/MB) 58 case b >= KB: 59 return fmt.Sprintf("%.1fK", float32(b)/KB) 60 } 61 return fmt.Sprintf("%d", b) 62 } 63 64 var bytesRegexp = regexp.MustCompile(`^(?i)(\d+)([BKMGTPE]?)(ib|b)?$`) 65 66 func (b *ByteSize) Set(s string) error { 67 m := bytesRegexp.FindStringSubmatch(s) 68 if len(m) == 0 { 69 return errors.New("invalid byte value") 70 } 71 72 i, err := strconv.ParseInt(m[1], 10, 64) 73 if err != nil { 74 return err 75 } 76 *b = ByteSize(i) 77 78 switch m[2] { 79 case "B", "b", "": 80 case "K", "k": 81 *b *= ByteSize(KB) 82 case "M", "m": 83 *b *= ByteSize(MB) 84 case "G", "g": 85 *b *= ByteSize(GB) 86 case "T", "t": 87 *b *= ByteSize(TB) 88 case "P", "p": 89 *b *= ByteSize(PB) 90 case "E", "e": 91 *b *= ByteSize(EB) 92 default: 93 return errors.New("invalid byte suffix") 94 } 95 96 return nil 97 }