gotosocial/vendor/github.com/spf13/cast/cast.go
kim 8b0ea56027 [chore] update go dependencies (#4304)
- github.com/KimMachineGun/automemlimit v0.7.2 => v0.7.3
- github.com/gin-contrib/cors v1.7.5 => v1.7.6
- github.com/minio/minio-go/v7 v7.0.92 => v7.0.94
- github.com/spf13/cast v1.8.0 => v1.9.2
- github.com/uptrace/bun{,/*} v1.2.11 => v1.2.14
- golang.org/x/image v0.27.0 => v0.28.0
- golang.org/x/net v0.40.0 => v0.41.0
- code.superseriousbusiness.org/go-swagger v0.31.0-gts-go1.23-fix => v0.32.3-gts-go1.23-fix

Reviewed-on: https://codeberg.org/superseriousbusiness/gotosocial/pulls/4304
Co-authored-by: kim <grufwub@gmail.com>
Co-committed-by: kim <grufwub@gmail.com>
2025-06-30 15:19:09 +02:00

84 lines
2 KiB
Go

// Copyright © 2014 Steve Francia <spf@spf13.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
// Package cast provides easy and safe casting in Go.
package cast
import "time"
const errorMsg = "unable to cast %#v of type %T to %T"
const errorMsgWith = "unable to cast %#v of type %T to %T: %w"
// Basic is a type parameter constraint for functions accepting basic types.
//
// It represents the supported basic types this package can cast to.
type Basic interface {
string | bool | Number | time.Time | time.Duration
}
// ToE casts any value to a [Basic] type.
func ToE[T Basic](i any) (T, error) {
var t T
var v any
var err error
switch any(t).(type) {
case string:
v, err = ToStringE(i)
case bool:
v, err = ToBoolE(i)
case int:
v, err = toNumberE[int](i, parseInt[int])
case int8:
v, err = toNumberE[int8](i, parseInt[int8])
case int16:
v, err = toNumberE[int16](i, parseInt[int16])
case int32:
v, err = toNumberE[int32](i, parseInt[int32])
case int64:
v, err = toNumberE[int64](i, parseInt[int64])
case uint:
v, err = toUnsignedNumberE[uint](i, parseUint[uint])
case uint8:
v, err = toUnsignedNumberE[uint8](i, parseUint[uint8])
case uint16:
v, err = toUnsignedNumberE[uint16](i, parseUint[uint16])
case uint32:
v, err = toUnsignedNumberE[uint32](i, parseUint[uint32])
case uint64:
v, err = toUnsignedNumberE[uint64](i, parseUint[uint64])
case float32:
v, err = toNumberE[float32](i, parseFloat[float32])
case float64:
v, err = toNumberE[float64](i, parseFloat[float64])
case time.Time:
v, err = ToTimeE(i)
case time.Duration:
v, err = ToDurationE(i)
}
if err != nil {
return t, err
}
return v.(T), nil
}
// Must is a helper that wraps a call to a cast function and panics if the error is non-nil.
func Must[T any](i any, err error) T {
if err != nil {
panic(err)
}
return i.(T)
}
// To casts any value to a [Basic] type.
func To[T Basic](i any) T {
v, _ := ToE[T](i)
return v
}