File: cast.go

package info (click to toggle)
golang-github-spf13-cast 1.10.0-1
  • links: PTS, VCS
  • area: main
  • in suites: experimental, sid
  • size: 284 kB
  • sloc: makefile: 34
file content (84 lines) | stat: -rw-r--r-- 2,026 bytes parent folder | download
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
// 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
}