-
Notifications
You must be signed in to change notification settings - Fork 0
/
result.go
381 lines (324 loc) · 8.05 KB
/
result.go
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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
// Copyright 2024 Nikolay Pakulin (@pakuula). All rights reserved.
// Use of this source code is governed by LGPL-3.0 licence.
// The text of the licence can be found in the LICENSE.txt file.
package result
import (
"encoding"
"encoding/json"
"errors"
"fmt"
"reflect"
)
// A value or an error
type Result[T any] struct {
value T
err error
}
// Constructors
func Wrap[T any](val T, err error) Result[T] {
return Result[T]{
value: val,
err: err,
}
}
func Val[T any](value T) Result[T] {
return Result[T]{value: value}
}
func Err[T any](err error) Result[T] {
if err == nil {
panic("Not an error")
}
return Result[T]{
err: err,
}
}
type _Void struct{}
type ResultVoid = Result[_Void]
func Void(err error) Result[_Void] {
return Wrap(_Void{}, err)
}
// String representaion
type hasToString interface {
ToString() string
}
// Builds a string representation of the result object.
// If it is an error, returns the err.Error() string
// If T has String method, calls String
// If T has ToString method, calls ToString
// If T has MarshalText method, calls MarshalText
// Otherwise calls fmt.Sprint(self.Unwrap())
func (self Result[T]) String() string {
if self.IsError() {
return "error: " + self.Err().Error()
}
reflected := reflect.ValueOf(self.value).Interface()
{
z, ok := reflected.(hasToString)
if ok {
return z.ToString()
}
}
{
z, ok := reflected.(fmt.Stringer)
if ok {
return z.String()
}
}
{
z, ok := reflected.(encoding.TextMarshaler)
if ok {
strBytes, err := z.MarshalText()
if err == nil {
return string(strBytes)
}
}
}
{
z, ok := reflected.(json.Marshaler)
if ok {
strBytes, err := z.MarshalJSON()
if err == nil {
return string(strBytes)
}
}
}
return fmt.Sprint(self.value)
}
// Check the result
// True if self is an error
func (self Result[T]) IsError() bool {
return self.err != nil
}
// True if self is an error and it matches the condition
func (self Result[T]) IsErrorAnd(cond func(error) bool) bool {
return self.err != nil && cond(self.err)
}
// True is self contains a value
func (self Result[T]) IsValue() bool {
return self.err == nil
}
// True is self contains a value and it matches the condition
func (self Result[T]) IsValueAnd(cond func(T) bool) bool {
return self.err == nil && cond(self.value)
}
type checkError struct {
err error
}
// Defer Catch(&res) to convert failed invocation of Must into Result
func Catch[T any](res *Result[T]) {
if panicValue := recover(); panicValue != nil {
err, ok := panicValue.(checkError)
if ok {
*res = Err[T](err.err)
} else {
panic(panicValue)
}
}
}
// Defer Catch(&err) to convert failed invocation of Must into error
func CatchError(errorPtr *error) {
if panicValue := recover(); panicValue != nil {
err, ok := panicValue.(checkError)
if ok {
*errorPtr = err.err
} else {
panic(panicValue)
}
}
}
// Extracting the stored value
// Extracts the stored value or panics with a catchable value.
func (self Result[T]) Must() T {
if self.IsError() {
panic(checkError{self.err})
}
return self.value
}
// Extracts the stored value or panics with a catchable string.
//
// The string is appended with 'error: <error's Error() method result>'
func (self Result[T]) Mustf(format string, a ...any) T {
if self.IsError() {
msg := fmt.Sprintf(format, a...)
if msg != "" {
msg += ": "
}
msg += "error: " + self.err.Error()
panic(checkError{errors.New(msg)})
}
return self.value
}
// Returns the value of panics with the catchable value.
func Must[T any](val T, err error) T {
if err != nil {
panic(checkError{err})
}
return val
}
// In the case of error panics with the catchable value.
func NoError(err error) ResultVoid {
if err != nil {
panic(checkError{err})
}
return Void(nil)
}
// Returns the stored value or panics with the given message
func (self Result[T]) Expect(msg string) T {
if self.IsError() {
panic(msg)
}
return self.value
}
// Returns the stored value or panics with the given formatted message
func (self Result[T]) Expectf(format string, a ...any) T {
if self.IsError() {
panic(fmt.Sprintf(format, a...))
}
return self.value
}
// Returns the stored value or panics
func (self Result[T]) Unwrap() T {
if self.IsError() {
panic(fmt.Errorf("unwrap error: %w", self.err))
}
return self.value
}
// Returns the stored value without checking the error
func (self Result[T]) UnwrapUnsafe() T {
return self.value
}
// Returns the stored value or the provided default value
func (self Result[T]) UnwrapOr(valueIfError T) T {
if self.IsError() {
return valueIfError
}
return self.value
}
// Returns the stored value or the default value for the type T
func (self Result[T]) UnwrapOrDefault() T {
if self.IsError() {
var zero T
return zero
}
return self.value
}
// Returns the stored value or transforms the error
func (self Result[T]) UnwrapOrElse(f func(error) T) T {
if self.IsError() {
return f(self.err)
}
return self.value
}
// Converts to the pair (value, error)
func (self Result[T]) UnwrapWithError() (T, error) {
return self.value, self.err
}
// Accessing the error
// Returns the error or panics
func (self Result[T]) Err() error {
if self.IsValue() {
panic("not an error")
}
return self.err
}
// Returns the stored error or the provided error
func (self Result[T]) ErrOr(other error) error {
if self.IsValue() {
return other
}
return self.err
}
// Returns the error or panics with the given message
func (self Result[T]) ExpectError(msg string) error {
if self.IsValue() {
panic(msg)
}
return self.err
}
// Returns the error or panics with the given formatted message
func (self Result[T]) ExpectErrorf(format string, a ...any) error {
if self.IsValue() {
panic(fmt.Sprintf(format, a...))
}
return self.err
}
// Pointer and dereference
// Converts to Result[*T]
func Ptr[T any](res *Result[T]) Result[*T] {
if res.IsError() {
return Err[*T](res.err)
}
return Val(&res.value)
}
var ErrDerefNil = errors.New("derefencing nil")
// Derefences Result[*T] - produces Result[T]
func Deref[T any](res Result[*T]) Result[T] {
if res.IsError() {
return Err[T](res.err)
}
if res.value == nil {
return Err[T](ErrDerefNil)
}
return Val(*res.value)
}
// Transform the Result
// Applies f to the stored value or keeps the error unchanged
func Apply[T any, U any](from Result[T], f func(T) U) Result[U] {
if from.IsError() {
return Err[U](from.err)
}
return Val(f(from.value))
}
// Applies f to the stored value or keeps error unchanged.
// If f returns an error, set the error
func ApplyE[T any, U any](from Result[T], f func(T) (U, error)) Result[U] {
if from.IsError() {
return Err[U](from.err)
}
res, err := f(from.value)
return Wrap[U](res, err)
}
// Applies f to the stored value or keeps error unchanged.
// If f returns an error, set the error
func ApplyResult[T any, U any](from Result[T], f func(T) Result[U]) Result[U] {
if from.IsError() {
return Err[U](from.err)
}
return f(from.value)
}
// Utility functions
// Unmarshal JSON data into a value of the type T or error
func UnmarshalJson[T any](data []byte) Result[T] {
var result T
err := json.Unmarshal(data, &result)
return Wrap(result, err)
}
// Unmarshal JSON string into a value of the type T or error
func UnmarshalJsonString[T any](data string) Result[T] {
return UnmarshalJson[T]([]byte(data))
}
// Marshal a value of the type T into JSON or error
func MarshalJson[T any](val T) Result[json.RawMessage] {
bz, err := json.Marshal(val)
return Wrap(json.RawMessage(bz), err)
}
// Marshal a value of the type T into indented JSON or error
func MarshalIndentJson[T any](val T, prefix string, indent string) Result[json.RawMessage] {
bz, err := json.MarshalIndent(val, prefix, indent)
return Wrap(json.RawMessage(bz), err)
}
// Iterator
func MapE[T any, U any](slice []T, f func(T) (U, error)) []Result[U] {
var retval = make([]Result[U], len(slice))
for i, t := range slice {
retval[i] = Wrap[U](f(t))
}
return retval
}
func MapR[T any, U any](slice []T, f func(T) Result[U]) []Result[U] {
var retval = make([]Result[U], len(slice))
for i, t := range slice {
retval[i] = f(t)
}
return retval
}