52 lines
1.3 KiB
Go
52 lines
1.3 KiB
Go
|
package metrics
|
||
|
|
||
|
import (
|
||
|
"errors"
|
||
|
"fmt"
|
||
|
"regexp"
|
||
|
"strconv"
|
||
|
"strings"
|
||
|
)
|
||
|
|
||
|
// ConvertMemoryToBytes converts a memory limit string into bytes.
|
||
|
// Supported units are: K (Kilobytes), M (Megabytes), G (Gigabytes), case-insensitive.
|
||
|
// Anything else is interpreted as bytes.
|
||
|
func ConvertMemoryToBytes(memory string) (uint64, error) {
|
||
|
// Trim whitespace
|
||
|
memory = strings.TrimSpace(memory)
|
||
|
|
||
|
// Regular expression to match the pattern (number + optional unit)
|
||
|
re := regexp.MustCompile(`(?i)^([\d.]+)([KMG]?)$`)
|
||
|
matches := re.FindStringSubmatch(memory)
|
||
|
if matches == nil {
|
||
|
return 0, errors.New("invalid memory format")
|
||
|
}
|
||
|
|
||
|
// Extract the numeric part and unit
|
||
|
numberStr := matches[1]
|
||
|
unit := strings.ToUpper(matches[2])
|
||
|
|
||
|
// Parse the number, truncate fractional parts as PHP does
|
||
|
number, err := strconv.ParseFloat(numberStr, 64)
|
||
|
if err != nil {
|
||
|
return 0, fmt.Errorf("invalid numeric value: %v", err)
|
||
|
}
|
||
|
numberInt := uint64(number) // Truncate fractional part by casting to uint64
|
||
|
|
||
|
// Convert to bytes based on the unit
|
||
|
var multiplier uint64
|
||
|
switch unit {
|
||
|
case "K":
|
||
|
multiplier = 1024 // Kilobytes
|
||
|
case "M":
|
||
|
multiplier = 1024 * 1024 // Megabytes
|
||
|
case "G":
|
||
|
multiplier = 1024 * 1024 * 1024 // Gigabytes
|
||
|
default:
|
||
|
multiplier = 1 // Bytes
|
||
|
}
|
||
|
|
||
|
// Calculate the result
|
||
|
return numberInt * multiplier, nil
|
||
|
}
|