Debian Codegraph @

allocator_sample_test.go

raw
1 // Copyright 2023 Huan Du. All rights reserved.
2 // Licensed under the MIT license that can be found in the LICENSE file.
3
4 //go:build !goexperiment.arenas
5
6 package clone
7
8 import (
9 "fmt"
10 "reflect"
11 "runtime"
12 "sync"
13 "unsafe"
14 )
15
16 func ExampleAllocator() {
17 // We can create a new allocator to hold customized config without poluting the default allocator.
18 // Calling FromHeap() is a convenient way to create a new allocator which allocates memory from heap.
19 allocator := FromHeap()
20
21 // Mark T as scalar only in the allocator.
22 type T struct {
23 Value *int
24 }
25 allocator.MarkAsScalar(reflect.TypeOf(new(T)))
26
27 t := &T{
28 Value: new(int),
29 }
30 cloned1 := allocator.Clone(reflect.ValueOf(t)).Interface().(*T)
31 cloned2 := Clone(t).(*T)
32
33 fmt.Println(t.Value == cloned1.Value)
34 fmt.Println(t.Value == cloned2.Value)
35
36 // Output:
37 // true
38 // false
39 }
40
41 func ExampleAllocator_syncPool() {
42 type Foo struct {
43 Bar int
44 }
45
46 typeOfFoo := reflect.TypeOf(Foo{})
47 poolUsed := 0 // For test only.
48
49 // A sync pool to allocate Foo.
50 p := &sync.Pool{
51 New: func() interface{} {
52 return &Foo{}
53 },
54 }
55
56 // Creates a custom allocator using p as pool.
57 allocator := NewAllocator(unsafe.Pointer(p), &AllocatorMethods{
58 New: func(pool unsafe.Pointer, t reflect.Type) reflect.Value {
59 // If t is Foo, allocate value from the sync pool p.
60 if t == typeOfFoo {
61 poolUsed++ // For test only.
62
63 p := (*sync.Pool)(pool)
64 v := p.Get()
65 runtime.SetFinalizer(v, func(v *Foo) {
66 *v = Foo{}
67 p.Put(v)
68 })
69
70 return reflect.ValueOf(v)
71 }
72
73 // Fallback to reflect API.
74 return reflect.New(t)
75 },
76 })
77
78 // Do clone.
79 target := []*Foo{
80 {Bar: 1},
81 {Bar: 2},
82 }
83 cloned := allocator.Clone(reflect.ValueOf(target)).Interface().([]*Foo)
84
85 fmt.Println(reflect.DeepEqual(target, cloned))
86 fmt.Println(poolUsed)
87
88 // Output:
89 // true
90 // 2
91 }
92
93 func ExampleAllocator_deepCloneString() {
94 // By default, string is considered as scalar and copied by value.
95 // In some cases, we may need to clone string deeply, that is, copy the underlying bytes.
96 // We can use a custom allocator to do this.
97 allocator := NewAllocator(nil, &AllocatorMethods{
98 IsScalar: func(t reflect.Kind) bool {
99 return t != reflect.String && IsScalar(t)
100 },
101 })
102 cloner := MakeCloner(allocator)
103
104 data := []byte("bytes")
105 s1 := *(*string)(unsafe.Pointer(&data)) // Unsafe conversion from []byte to string.
106 s2 := Clone(s1).(string) // s2 shares the same underlying bytes with s1.
107 s3 := cloner.Clone(s1).(string) // s3 has its own underlying bytes.
108
109 copy(data, "magic") // Change the underlying bytes.
110 fmt.Println(s1)
111 fmt.Println(s2)
112 fmt.Println(s3)
113
114 // Output:
115 // magic
116 // magic
117 // bytes
118 }