Debian Codegraph @

allocator_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 package clone
5
6 import (
7 "reflect"
8 "testing"
9 "unsafe"
10
11 "github.com/huandu/go-assert"
12 )
13
14 func TestAllocatorClone(t *testing.T) {
15 a := assert.New(t)
16 cnt := 0
17 allocator := NewAllocator(nil, &AllocatorMethods{
18 New: func(pool unsafe.Pointer, t reflect.Type) reflect.Value {
19 cnt++
20 return heapNew(pool, t)
21 },
22 })
23
24 type dataNode struct {
25 Data int
26 Next *dataNode
27 }
28 data := &dataNode{
29 Data: 1,
30 Next: &dataNode{
31 Data: 2,
32 },
33 }
34 cloned := allocator.Clone(reflect.ValueOf(data)).Interface().(*dataNode)
35 a.Equal(data, cloned)
36
37 // Should allocate following value.
38 // - allocator
39 // - data
40 // - data.Next
41 a.Equal(cnt, 3)
42 }
43
44 func TestAllocatorCloneSlowly(t *testing.T) {
45 a := assert.New(t)
46 cnt := 0
47 allocator := NewAllocator(nil, &AllocatorMethods{
48 New: func(pool unsafe.Pointer, t reflect.Type) reflect.Value {
49 cnt++
50 return heapNew(pool, t)
51 },
52 })
53
54 type dataNode struct {
55 Data int
56 Next *dataNode
57 }
58
59 // data is a cycle linked list.
60 data := &dataNode{
61 Data: 1,
62 Next: &dataNode{
63 Data: 2,
64 Next: &dataNode{
65 Data: 3,
66 },
67 },
68 }
69 data.Next.Next.Next = data
70
71 cloned := allocator.CloneSlowly(reflect.ValueOf(data)).Interface().(*dataNode)
72
73 a.Equal(data.Data, cloned.Data)
74 a.Equal(data.Next.Data, cloned.Next.Data)
75 a.Equal(data.Next.Next.Data, cloned.Next.Next.Data)
76 a.Equal(data.Next.Next.Next.Data, cloned.Next.Next.Next.Data)
77 a.Equal(data.Next.Next.Next.Next.Data, cloned.Next.Next.Next.Next.Data)
78 a.Assert(cloned.Next.Next.Next == cloned)
79
80 // Should allocate following value.
81 // - allocator
82 // - data
83 // - data.Next
84 // - data.Next.Next
85 a.Equal(cnt, 4)
86 }