github.com/criyle/go-sandbox@v0.10.3/runner/size.go (about) 1 package runner 2 3 import ( 4 "fmt" 5 "strconv" 6 ) 7 8 // Size stores number of byte for the object. E.g. Memory. 9 // Maximum size is bounded by 64-bit limit 10 type Size uint64 11 12 // String stringer interface for print 13 func (s Size) String() string { 14 t := uint64(s) 15 switch { 16 case t < 1<<10: 17 return fmt.Sprintf("%d B", t) 18 case t < 1<<20: 19 return fmt.Sprintf("%.1f KiB", float64(t)/float64(1<<10)) 20 case t < 1<<30: 21 return fmt.Sprintf("%.1f MiB", float64(t)/float64(1<<20)) 22 default: 23 return fmt.Sprintf("%.1f GiB", float64(t)/float64(1<<30)) 24 } 25 } 26 27 // Set parse the size value from string 28 func (s *Size) Set(str string) error { 29 switch str[len(str)-1] { 30 case 'b', 'B': 31 str = str[:len(str)-1] 32 } 33 34 factor := 0 35 switch str[len(str)-1] { 36 case 'k', 'K': 37 factor = 10 38 str = str[:len(str)-1] 39 case 'm', 'M': 40 factor = 20 41 str = str[:len(str)-1] 42 case 'g', 'G': 43 factor = 30 44 str = str[:len(str)-1] 45 } 46 47 t, err := strconv.Atoi(str) 48 if err != nil { 49 return err 50 } 51 *s = Size(t << factor) 52 return nil 53 } 54 55 // Byte return size in bytes 56 func (s Size) Byte() uint64 { 57 return uint64(s) 58 } 59 60 // KiB return size in KiB 61 func (s Size) KiB() uint64 { 62 return uint64(s) >> 10 63 } 64 65 // MiB return size in MiB 66 func (s Size) MiB() uint64 { 67 return uint64(s) >> 20 68 } 69 70 // GiB return size in GiB 71 func (s Size) GiB() uint64 { 72 return uint64(s) >> 30 73 } 74 75 // TiB return size in TiB 76 func (s Size) TiB() uint64 { 77 return uint64(s) >> 40 78 } 79 80 // PiB return size in PiB 81 func (s Size) PiB() uint64 { 82 return uint64(s) >> 50 83 } 84 85 // EiB return size in EiB 86 func (s Size) EiB() uint64 { 87 return uint64(s) >> 60 88 }