Skip to content

Commit 9dbb5f4

Browse files
committed
cm: add SetOK and SetErr methods to mutate a result
1 parent 03b3108 commit 9dbb5f4

1 file changed

Lines changed: 34 additions & 20 deletions

File tree

cm/result.go

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,40 @@ type result[Shape, OK, Err any] struct {
3939
data Shape // [unsafe.Sizeof(*(*Shape)(unsafe.Pointer(nil)))]byte
4040
}
4141

42+
// OK returns an OK result with shape Shape and type OK and Err.
43+
// Pass Result[OK, OK, Err] or Result[Err, OK, Err] as the first type argument.
44+
func OK[R AnyResult[Shape, OK, Err], Shape, OK, Err any](ok OK) R {
45+
var r Result[Shape, OK, Err]
46+
r.validate()
47+
r.isErr = ResultOK
48+
*((*OK)(unsafe.Pointer(&r.data))) = ok
49+
return R(r)
50+
}
51+
52+
// Err returns an error result with shape Shape and type OK and Err.
53+
// Pass Result[OK, OK, Err] or Result[Err, OK, Err] as the first type argument.
54+
func Err[R AnyResult[Shape, OK, Err], Shape, OK, Err any](err Err) R {
55+
var r Result[Shape, OK, Err]
56+
r.validate()
57+
r.isErr = ResultErr
58+
*((*Err)(unsafe.Pointer(&r.data))) = err
59+
return R(r)
60+
}
61+
62+
// SetOK sets r to an OK result.
63+
func (r *result[Shape, OK, Err]) SetOK(ok OK) {
64+
r.validate()
65+
r.isErr = ResultOK
66+
*((*OK)(unsafe.Pointer(&r.data))) = ok
67+
}
68+
69+
// SetErr sets r to an error result.
70+
func (r *result[Shape, OK, Err]) SetErr(err Err) {
71+
r.validate()
72+
r.isErr = ResultErr
73+
*((*Err)(unsafe.Pointer(&r.data))) = err
74+
}
75+
4276
// IsOK returns true if r represents the OK case.
4377
func (r *result[Shape, OK, Err]) IsOK() bool {
4478
r.validate()
@@ -107,23 +141,3 @@ func (r *result[Shape, OK, Err]) validate() {
107141
panic("result: size of data type == 0, but result size != 1")
108142
}
109143
}
110-
111-
// OK returns an OK result with shape Shape and type OK and Err.
112-
// Pass Result[OK, OK, Err] or Result[Err, OK, Err] as the first type argument.
113-
func OK[R AnyResult[Shape, OK, Err], Shape, OK, Err any](ok OK) R {
114-
var r Result[Shape, OK, Err]
115-
r.validate()
116-
r.isErr = ResultOK
117-
*((*OK)(unsafe.Pointer(&r.data))) = ok
118-
return R(r)
119-
}
120-
121-
// Err returns an error result with shape Shape and type OK and Err.
122-
// Pass Result[OK, OK, Err] or Result[Err, OK, Err] as the first type argument.
123-
func Err[R AnyResult[Shape, OK, Err], Shape, OK, Err any](err Err) R {
124-
var r Result[Shape, OK, Err]
125-
r.validate()
126-
r.isErr = ResultErr
127-
*((*Err)(unsafe.Pointer(&r.data))) = err
128-
return R(r)
129-
}

0 commit comments

Comments
 (0)