2 Commits

Author SHA1 Message Date
amery 306fe1e35f reflection: add initial New() validating type and triggering a scan
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-09-02 02:17:14 +00:00
amery 1e95acf21d reflection: introduce InvalidUnmarshalError{}
Signed-off-by: Alejandro Mery <amery@jpi.io>
2023-09-01 23:54:14 +00:00
3 changed files with 86 additions and 0 deletions
+44
View File
@@ -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()
}
+37
View File
@@ -0,0 +1,37 @@
// Package reflection helps Marshalling/Unmarshalling data to structs
package reflection
import (
"reflect"
)
// Reflection provides Marshalling/Unmarshalling oriented view
// of a value
type Reflection struct {
v reflect.Value
}
// Value returns the object it reflects
func (r *Reflection) Value() any {
return r.v.Interface()
}
// New creates a Reflection of the given pointer
func New(v any) (*Reflection, error) {
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Pointer || rv.IsNil() {
err := &InvalidUnmarshalError{Type: rv.Type()}
return nil, err
}
r := &Reflection{
v: rv,
}
if err := r.scan(); err != nil {
return nil, err
}
return r, nil
}
+5
View File
@@ -0,0 +1,5 @@
package reflection
func (*Reflection) scan() error {
return nil
}