File: allocator_test.go

package info (click to toggle)
golang-github-huandu-go-clone 1.6.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 276 kB
  • sloc: makefile: 2
file content (86 lines) | stat: -rw-r--r-- 1,771 bytes parent folder | download
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
// Copyright 2023 Huan Du. All rights reserved.
// Licensed under the MIT license that can be found in the LICENSE file.

package clone

import (
	"reflect"
	"testing"
	"unsafe"

	"github.com/huandu/go-assert"
)

func TestAllocatorClone(t *testing.T) {
	a := assert.New(t)
	cnt := 0
	allocator := NewAllocator(nil, &AllocatorMethods{
		New: func(pool unsafe.Pointer, t reflect.Type) reflect.Value {
			cnt++
			return heapNew(pool, t)
		},
	})

	type dataNode struct {
		Data int
		Next *dataNode
	}
	data := &dataNode{
		Data: 1,
		Next: &dataNode{
			Data: 2,
		},
	}
	cloned := allocator.Clone(reflect.ValueOf(data)).Interface().(*dataNode)
	a.Equal(data, cloned)

	// Should allocate following value.
	//     - allocator
	//     - data
	//     - data.Next
	a.Equal(cnt, 3)
}

func TestAllocatorCloneSlowly(t *testing.T) {
	a := assert.New(t)
	cnt := 0
	allocator := NewAllocator(nil, &AllocatorMethods{
		New: func(pool unsafe.Pointer, t reflect.Type) reflect.Value {
			cnt++
			return heapNew(pool, t)
		},
	})

	type dataNode struct {
		Data int
		Next *dataNode
	}

	// data is a cycle linked list.
	data := &dataNode{
		Data: 1,
		Next: &dataNode{
			Data: 2,
			Next: &dataNode{
				Data: 3,
			},
		},
	}
	data.Next.Next.Next = data

	cloned := allocator.CloneSlowly(reflect.ValueOf(data)).Interface().(*dataNode)

	a.Equal(data.Data, cloned.Data)
	a.Equal(data.Next.Data, cloned.Next.Data)
	a.Equal(data.Next.Next.Data, cloned.Next.Next.Data)
	a.Equal(data.Next.Next.Next.Data, cloned.Next.Next.Next.Data)
	a.Equal(data.Next.Next.Next.Next.Data, cloned.Next.Next.Next.Next.Data)
	a.Assert(cloned.Next.Next.Next == cloned)

	// Should allocate following value.
	//     - allocator
	//     - data
	//     - data.Next
	//     - data.Next.Next
	a.Equal(cnt, 4)
}