refactor: clean up code and enhance utilities with new functions

This commit is contained in:
yusing
2025-03-28 08:08:33 +08:00
parent 7707fc6f36
commit cdb3ffe439
9 changed files with 103 additions and 17 deletions

View File

@@ -0,0 +1,11 @@
package strutils
import "strings"
// IsValidFilename checks if a filename is safe and doesn't contain path traversal attempts
// Returns true if the filename is valid, false otherwise
func IsValidFilename(filename string) bool {
return !strings.Contains(filename, "/") &&
!strings.Contains(filename, "\\") &&
!strings.Contains(filename, "..")
}

View File

@@ -2,6 +2,7 @@ package strutils
import (
"fmt"
"math"
"strconv"
"strings"
"time"
@@ -65,6 +66,44 @@ func ParseBool(s string) bool {
}
}
func formatFloat(f float64) string {
f = math.Round(f*100) / 100
if f == 0 {
return "0"
}
return strconv.FormatFloat(f, 'f', -1, 64)
}
func FormatByteSize[T ~int64 | ~uint64 | ~float64](size T) (value, unit string) {
const (
_ = (1 << (10 * iota))
kb
mb
gb
tb
pb
)
switch {
case size < kb:
return fmt.Sprintf("%v", size), "B"
case size < mb:
return formatFloat(float64(size) / kb), "KiB"
case size < gb:
return formatFloat(float64(size) / mb), "MiB"
case size < tb:
return formatFloat(float64(size) / gb), "GiB"
case size < pb:
return formatFloat(float64(size/gb) / kb), "TiB" // prevent overflow
default:
return formatFloat(float64(size/tb) / kb), "PiB" // prevent overflow
}
}
func FormatByteSizeWithUnit[T ~int64 | ~uint64 | ~float64](size T) string {
value, unit := FormatByteSize(size)
return value + " " + unit
}
func PortString(port uint16) string {
return strconv.FormatUint(uint64(port), 10)
}