Compare commits
2 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| a2da12be7a | |||
| 1e95acf21d |
@@ -0,0 +1,44 @@
|
|||||||
|
package reflection
|
||||||
|
|
||||||
|
import (
|
||||||
|
"bytes"
|
||||||
|
"fmt"
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// An InvalidUnmarshalError describes an invalid argument passed to New.
|
||||||
|
// (It must be a non-nil pointer.)
|
||||||
|
type InvalidUnmarshalError struct {
|
||||||
|
Method string
|
||||||
|
Prefix string
|
||||||
|
|
||||||
|
reflect.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
func (e *InvalidUnmarshalError) Error() string {
|
||||||
|
var buf bytes.Buffer
|
||||||
|
|
||||||
|
if e.Prefix != "" {
|
||||||
|
_, _ = fmt.Fprintf(&buf, "%s: ", e.Prefix)
|
||||||
|
}
|
||||||
|
|
||||||
|
method := e.Method
|
||||||
|
if method == "" {
|
||||||
|
method = "New"
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = fmt.Fprintf(&buf, "%s(", method)
|
||||||
|
|
||||||
|
switch {
|
||||||
|
case e.Type == nil:
|
||||||
|
_, _ = buf.WriteString("nil")
|
||||||
|
case e.Type.Kind() != reflect.Pointer:
|
||||||
|
_, _ = fmt.Fprintf(&buf, "%s %s", "non-pointer", e.Type.String())
|
||||||
|
default:
|
||||||
|
_, _ = fmt.Fprintf(&buf, "%s %s", "nil", e.Type.String())
|
||||||
|
}
|
||||||
|
|
||||||
|
_, _ = buf.WriteString(")")
|
||||||
|
|
||||||
|
return buf.String()
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Package reflection helps Marshalling/Unmarshalling data to structs
|
||||||
|
package reflection
|
||||||
|
|
||||||
|
import (
|
||||||
|
"reflect"
|
||||||
|
)
|
||||||
|
|
||||||
|
// Reflection provides Marshalling/Unmarshalling oriented view
|
||||||
|
// of a value
|
||||||
|
type Reflection[T any] struct {
|
||||||
|
rv reflect.Value
|
||||||
|
rt reflect.Type
|
||||||
|
}
|
||||||
|
|
||||||
|
// Value returns the object it reflects
|
||||||
|
func (r *Reflection[T]) Value() *T {
|
||||||
|
return r.rv.Interface().(*T)
|
||||||
|
}
|
||||||
|
|
||||||
|
// New creates a Reflection of the given pointer
|
||||||
|
func New[T any](v *T) (*Reflection[T], error) {
|
||||||
|
if v == nil {
|
||||||
|
err := &InvalidUnmarshalError{Type: reflect.TypeOf(v)}
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
r := &Reflection[T]{
|
||||||
|
rv: reflect.ValueOf(v),
|
||||||
|
rt: reflect.TypeOf(v),
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := r.scan(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
return r, nil
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
package reflection
|
||||||
|
|
||||||
|
func (*Reflection[T]) scan() error {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user