-
-
Notifications
You must be signed in to change notification settings - Fork 660
Expand file tree
/
Copy pathatomic-count.go
More file actions
41 lines (33 loc) · 837 Bytes
/
atomic-count.go
File metadata and controls
41 lines (33 loc) · 837 Bytes
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
package torrent
import (
"encoding/json"
"fmt"
"reflect"
"sync/atomic"
)
type Count struct {
n int64
}
var _ fmt.Stringer = (*Count)(nil)
func (me *Count) Add(n int64) {
atomic.AddInt64(&me.n, n)
}
func (me *Count) Int64() int64 {
return atomic.LoadInt64(&me.n)
}
func (me *Count) String() string {
return fmt.Sprintf("%v", me.Int64())
}
func (me *Count) MarshalJSON() ([]byte, error) {
return json.Marshal(me.n)
}
// TODO: Can this use more generics to speed it up? Should we be checking the field types?
func copyCountFields[T any](src *T) (dst T) {
srcValue := reflect.ValueOf(src).Elem()
dstValue := reflect.ValueOf(&dst).Elem()
for i := 0; i < reflect.TypeFor[T]().NumField(); i++ {
n := srcValue.Field(i).Addr().Interface().(*Count).Int64()
dstValue.Field(i).Addr().Interface().(*Count).Add(n)
}
return
}