diff options
Diffstat (limited to 'core/state_backend.go')
| -rw-r--r-- | core/state_backend.go | 18 |
1 files changed, 16 insertions, 2 deletions
diff --git a/core/state_backend.go b/core/state_backend.go index 5870739..ae9fe1d 100644 --- a/core/state_backend.go +++ b/core/state_backend.go | |||
| @@ -2,6 +2,9 @@ package core | |||
| 2 | 2 | ||
| 3 | import ( | 3 | import ( |
| 4 | "context" | 4 | "context" |
| 5 | "encoding/json" | ||
| 6 | "fmt" | ||
| 7 | |||
| 5 | ) | 8 | ) |
| 6 | 9 | ||
| 7 | type StateBackend interface { | 10 | type StateBackend interface { |
| @@ -22,6 +25,7 @@ type stateBackendKeyType struct{} | |||
| 22 | 25 | ||
| 23 | var stateBackendKey stateBackendKeyType | 26 | var stateBackendKey stateBackendKeyType |
| 24 | 27 | ||
| 28 | // type adapter | ||
| 25 | type typedValueState[T any] struct { | 29 | type typedValueState[T any] struct { |
| 26 | inner ValueState[any] | 30 | inner ValueState[any] |
| 27 | } | 31 | } |
| @@ -32,14 +36,24 @@ func CastValueType[T any](inner ValueState[any]) ValueState[T] { | |||
| 32 | 36 | ||
| 33 | func (s *typedValueState[T]) Value(ctx context.Context) (T, error) { | 37 | func (s *typedValueState[T]) Value(ctx context.Context) (T, error) { |
| 34 | val, err := s.inner.Value(ctx) | 38 | val, err := s.inner.Value(ctx) |
| 39 | var zero T | ||
| 35 | if err != nil { | 40 | if err != nil { |
| 36 | var zero T | ||
| 37 | return zero, err | 41 | return zero, err |
| 38 | } | 42 | } |
| 39 | if val == nil { | 43 | if val == nil { |
| 40 | var zero T | ||
| 41 | return zero, nil | 44 | return zero, nil |
| 42 | } | 45 | } |
| 46 | |||
| 47 | if rawBytes, ok := val.([]byte); ok { | ||
| 48 | defer PutBuffer(rawBytes) | ||
| 49 | |||
| 50 | var result T | ||
| 51 | if err := json.Unmarshal(rawBytes, &result); err != nil { | ||
| 52 | return zero, fmt.Errorf("failed to unmarshal state: %w", err) | ||
| 53 | } | ||
| 54 | return result, nil | ||
| 55 | } | ||
| 56 | |||
| 43 | return val.(T), nil | 57 | return val.(T), nil |
| 44 | } | 58 | } |
| 45 | 59 | ||
