Skip to content

Commit cc36bed

Browse files
committed
feat: pseudo.PointerTo()
1 parent 00506bc commit cc36bed

File tree

2 files changed

+44
-0
lines changed

2 files changed

+44
-0
lines changed

libevm/pseudo/type.go

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,27 @@ func Zero[T any]() *Pseudo[T] {
6060
return From[T](x)
6161
}
6262

63+
// PointerTo is equivalent to [From] called with a pointer to the payload
64+
// carried by `t`. It first confirms that the payload is of type `T`.
65+
func PointerTo[T any](t *Type) (*Pseudo[*T], error) {
66+
c, ok := t.val.(*concrete[T])
67+
if !ok {
68+
var want *T
69+
return nil, fmt.Errorf("cannot create *Pseudo[%T] from *Type carrying %T", want, t.val.get())
70+
}
71+
return From(&c.val), nil
72+
}
73+
74+
// MustPointerTo is equivalent to [PointerTo] except that it panics instead of
75+
// returning an error.
76+
func MustPointerTo[T any](t *Type) *Pseudo[*T] {
77+
p, err := PointerTo[T](t)
78+
if err != nil {
79+
panic(err)
80+
}
81+
return p
82+
}
83+
6384
// Interface returns the wrapped value as an `any`, equivalent to
6485
// [reflect.Value.Interface]. Prefer [Value.Get].
6586
func (t *Type) Interface() any { return t.val.get() }

libevm/pseudo/type_test.go

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,3 +77,26 @@ func ExamplePseudo_TypeAndValue() {
7777
_ = typ
7878
_ = val
7979
}
80+
81+
func TestPointer(t *testing.T) {
82+
type carrier struct {
83+
payload int
84+
}
85+
86+
typ, val := From(carrier{42}).TypeAndValue()
87+
88+
t.Run("invalid type", func(t *testing.T) {
89+
_, err := PointerTo[int](typ)
90+
require.Errorf(t, err, "PointerTo[int](%T)", carrier{})
91+
})
92+
93+
t.Run("valid type", func(t *testing.T) {
94+
ptrVal := MustPointerTo[carrier](typ).Value
95+
96+
assert.Equal(t, 42, val.Get().payload, "before setting via pointer")
97+
var ptr *carrier = ptrVal.Get()
98+
ptr.payload = 314159
99+
assert.Equal(t, 314159, val.Get().payload, "after setting via pointer")
100+
})
101+
102+
}

0 commit comments

Comments
 (0)