This repository has been archived by the owner on May 27, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
mutation.go
104 lines (87 loc) · 1.83 KB
/
mutation.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
package mutantdb
import (
"encoding/json"
"fmt"
)
type Mutator[T any] interface {
Name() string
Apply(T, any) (T, error)
}
type mutator[T, M any] struct {
name string
fn func(T, M) (T, error)
}
func NewMutator[T, M any](name string, fn func(T, M) (T, error)) *mutator[T, M] {
return &mutator[T, M]{
name: name,
fn: fn,
}
}
func (m *mutator[T, M]) Name() string {
return m.name
}
func (m *mutator[T, M]) Apply(data T, md any) (T, error) {
var mutationData M
switch t := md.(type) {
case nil:
// do nothing
case M:
mutationData = t
case json.RawMessage:
if err := json.Unmarshal(t, &mutationData); err != nil {
return data, fmt.Errorf("mutantdb: failed to deserialize mutation data into %T: %w", mutationData, err)
}
default:
return data, fmt.Errorf("mutantdb: invalid mutation data type %T", t)
}
return m.fn(data, mutationData)
}
func (m *mutator[T, M]) New(data M, meta ...Meta) *mutation[T, M] {
e := &mutation[T, M]{
data: data,
mutator: m,
}
for _, meta := range meta {
if e.meta == nil {
e.meta = make(Meta)
}
for k, v := range meta {
e.meta[k] = v
}
}
return e
}
type Meta map[string]string
type Mutation[T any] interface {
Name() string
Data() any
Meta() Meta
Apply(T) (T, error)
}
// Apply is a convenience function that applies mutations to a value.
func Apply[T any](d T, mutations ...Mutation[T]) (T, error) {
for _, m := range mutations {
d, err := m.Apply(d)
if err != nil {
return d, err
}
}
return d, nil
}
type mutation[T, M any] struct {
data M
meta Meta
mutator *mutator[T, M]
}
func (m *mutation[T, M]) Name() string {
return m.mutator.name
}
func (m *mutation[T, M]) Data() any {
return m.data
}
func (m *mutation[T, M]) Meta() Meta {
return m.meta
}
func (m *mutation[T, M]) Apply(data T) (T, error) {
return m.mutator.fn(data, m.data)
}