| 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 go1.20 && goexperiment.arenas |
| 5 |
// +build go1.20,goexperiment.arenas |
| 6 |
|
| 7 |
package clone |
| 8 |
|
| 9 |
import ( |
| 10 |
"arena" |
| 11 |
"reflect" |
| 12 |
"runtime" |
| 13 |
"testing" |
| 14 |
"unsafe" |
| 15 |
|
| 16 |
"github.com/huandu/go-assert" |
| 17 |
) |
| 18 |
|
| 19 |
func TestArenaClone(t *testing.T) { |
| 20 |
a := assert.New(t) |
| 21 |
|
| 22 |
type FooInner struct { |
| 23 |
Value float64 |
| 24 |
} |
| 25 |
|
| 26 |
type Foo struct { |
| 27 |
A string |
| 28 |
B []int |
| 29 |
C *FooInner |
| 30 |
D map[int]string |
| 31 |
} |
| 32 |
|
| 33 |
foo := &Foo{ |
| 34 |
A: "hello", |
| 35 |
B: []int{1, 2, 3}, |
| 36 |
C: &FooInner{ |
| 37 |
Value: 45.6, |
| 38 |
}, |
| 39 |
D: map[int]string{ |
| 40 |
7: "7", |
| 41 |
}, |
| 42 |
} |
| 43 |
|
| 44 |
ar := arena.NewArena() |
| 45 |
|
| 46 |
cloned := ArenaClone(ar, foo) |
| 47 |
a.Equal(foo, cloned) |
| 48 |
|
| 49 |
// If a pointer is not allocated by arena, arena.Clone() will return the pointer as it is. |
| 50 |
// Use this feature to check whether a pointer is allocated by arena. |
| 51 |
prevStr := foo.A |
| 52 |
str := arena.Clone(cloned.A) |
| 53 |
a.Assert(((*reflect.StringHeader)(unsafe.Pointer(&str))).Data != ((*reflect.StringHeader)(unsafe.Pointer(&prevStr))).Data) |
| 54 |
|
| 55 |
a.Assert(arena.Clone(cloned) != foo) |
| 56 |
|
| 57 |
slice := arena.Clone(cloned.B) |
| 58 |
a.Assert(&slice[0] != &foo.B[0]) |
| 59 |
|
| 60 |
a.Assert(arena.Clone(cloned.C) != foo.C) |
| 61 |
|
| 62 |
prevStr = foo.D[7] |
| 63 |
str = arena.Clone(cloned.D[7]) |
| 64 |
a.Assert(((*reflect.StringHeader)(unsafe.Pointer(&str))).Data != ((*reflect.StringHeader)(unsafe.Pointer(&prevStr))).Data) |
| 65 |
|
| 66 |
// Make sure ar is alive. |
| 67 |
runtime.KeepAlive(ar) |
| 68 |
} |