code refactoring

This commit is contained in:
2025-07-12 22:25:50 +02:00
parent a3a0b1256b
commit 3665f0c873
12 changed files with 870 additions and 742 deletions

View File

@@ -4,6 +4,7 @@ import (
"encoding/base64"
"encoding/hex"
"fmt"
"strings"
)
// toBinary tries to convert v into a []byte.
@@ -31,3 +32,31 @@ func toBinary(v interface{}) ([]byte, error) {
return nil, fmt.Errorf("cannot convert type %T to binary", v)
}
}
// decodeBinary decodes Base64 or Hex-encoded binary strings to byte slices
func decodeBinary(t StateVarType, val string) ([]byte, error) {
switch t {
case StateType_BinBase64:
data, err := base64.StdEncoding.DecodeString(val)
if err != nil {
return nil, fmt.Errorf("invalid base64: %v", err)
}
return data, nil
case StateType_BinHex:
// Accept even-length hex string
val = strings.TrimSpace(val)
if len(val)%2 != 0 {
return nil, fmt.Errorf("invalid hex: odd-length string")
}
data := make([]byte, len(val)/2)
_, err := hex.Decode(data, []byte(val))
if err != nil {
return nil, fmt.Errorf("invalid hex: %v", err)
}
return data, nil
default:
return nil, fmt.Errorf("decodeBinary: unsupported binary type %v", t)
}
}