-
Notifications
You must be signed in to change notification settings - Fork 16
/
data_units.go
64 lines (54 loc) · 1.34 KB
/
data_units.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package helpers
import (
"fmt"
"strconv"
"strings"
"github.com/Trendyol/go-dcp/logger"
)
func ResolveUnionIntOrStringValue(input any) int {
switch value := input.(type) {
case int:
return value
case uint:
return int(value)
case string:
intValue, err := strconv.ParseInt(value, 10, 64)
if err == nil {
return int(intValue)
}
result, err := convertSizeUnitToByte(value)
if err != nil {
logger.Log.Error("error while convert size unit to byte, err: %v", err)
panic(err)
}
return result
}
return 0
}
func convertSizeUnitToByte(str string) (int, error) {
if len(str) < 2 {
return 0, fmt.Errorf("invalid input: %s", str)
}
// Extract the numeric part of the input
sizeStr := str[:len(str)-2]
sizeStr = strings.TrimSpace(sizeStr)
sizeStr = strings.ReplaceAll(sizeStr, ",", ".")
size, err := strconv.ParseFloat(sizeStr, 64)
if err != nil {
return 0, fmt.Errorf("cannot extract numeric part for the input %s, err = %w", str, err)
}
// Determine the unit (B, KB, MB, GB)
unit := str[len(str)-2:]
switch strings.ToUpper(unit) {
case "B":
return int(size), nil
case "KB":
return int(size * 1024), nil
case "MB":
return int(size * 1024 * 1024), nil
case "GB":
return int(size * 1024 * 1024 * 1024), nil
default:
return 0, fmt.Errorf("unsupported unit: %s, you can specify one of B, KB, MB and GB", unit)
}
}