cmd, ui: Move size parsing code and make it more robust

This commit is contained in:
greatroar
2023-07-02 21:44:50 +02:00
parent f96896a9c0
commit 41a5bf357f
6 changed files with 97 additions and 84 deletions
+41
View File
@@ -3,7 +3,10 @@ package ui
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"math/bits"
"strconv"
"time"
)
@@ -56,6 +59,44 @@ func FormatSeconds(sec uint64) string {
return fmt.Sprintf("%d:%02d", min, sec)
}
// ParseBytes parses a size in bytes from s. It understands the suffixes
// B, K, M, G and T for powers of 1024.
func ParseBytes(s string) (int64, error) {
if s == "" {
return 0, errors.New("expected size, got empty string")
}
numStr := s[:len(s)-1]
var unit uint64 = 1
switch s[len(s)-1] {
case 'b', 'B':
// use initialized values, do nothing here
case 'k', 'K':
unit = 1024
case 'm', 'M':
unit = 1024 * 1024
case 'g', 'G':
unit = 1024 * 1024 * 1024
case 't', 'T':
unit = 1024 * 1024 * 1024 * 1024
default:
numStr = s
}
value, err := strconv.ParseInt(numStr, 10, 64)
if err != nil {
return 0, err
}
hi, lo := bits.Mul64(uint64(value), unit)
value = int64(lo)
if hi != 0 || value < 0 {
return 0, fmt.Errorf("ParseSize: %q: %w", numStr, strconv.ErrRange)
}
return value, nil
}
func ToJSONString(status interface{}) string {
buf := new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(status)