v2 / vlib / v / tests / pointers / heap_reference_test.v
101 lines · 95 sloc · 1.78 KB · 6488041a749df9762348d019c4223908c476f2e2
Raw
1@[heap]
2struct GitStructure {
3pub mut:
4 root string
5 repos []&GitRepo
6}
7
8@[heap]
9struct GitRepo {
10 id int @[skip]
11pub:
12 path string // path on filesystem
13 name string
14}
15
16pub fn (mut gitstructure GitStructure) repo_get(name string) !&GitRepo {
17 for r in gitstructure.repos {
18 if r.name == name {
19 if name != '' {
20 r2 := gitstructure.repos[r.id]
21 return r2
22 }
23 }
24 }
25 return error("Could not find repo for account name: '${name}'")
26}
27
28fn test_opt_ref_return() {
29 mut gitstruct := GitStructure{
30 root: 'r'
31 repos: [
32 &GitRepo{
33 id: 0
34 path: 'testpath'
35 name: 'thename'
36 },
37 ]
38 }
39 mut err_msg := ''
40 a := gitstruct.repo_get('thename') or {
41 err_msg = '${err}'
42 r := &GitRepo{}
43 r
44 }
45 assert a.path == 'testpath'
46 assert err_msg == ''
47 b := gitstruct.repo_get('wrong_name') or {
48 err_msg = '${err}'
49 r := &GitRepo{}
50 r
51 }
52 assert b.path == ''
53 assert err_msg == "Could not find repo for account name: 'wrong_name'"
54}
55
56@[heap]
57struct GitStructureNoRef {
58pub mut:
59 root string
60 repos []GitRepo
61}
62
63pub fn (mut gitstructure GitStructureNoRef) repo_get(name string) !&GitRepo {
64 for r in gitstructure.repos {
65 if r.name == name {
66 if name != '' {
67 r2 := &gitstructure.repos[r.id]
68 return r2
69 }
70 }
71 }
72 return error("Could not find repo for account name: '${name}'")
73}
74
75fn test_opt_return() {
76 mut gitstruct := &GitStructureNoRef{
77 root: 'r'
78 repos: [
79 GitRepo{
80 id: 0
81 path: 'testpath2'
82 name: 'thename2'
83 },
84 ]
85 }
86 mut err_msg := ''
87 a := gitstruct.repo_get('thename2') or {
88 err_msg = '${err}'
89 r := &GitRepo{}
90 r
91 }
92 assert a.path == 'testpath2'
93 assert err_msg == ''
94 b := gitstruct.repo_get('wrong_name2') or {
95 err_msg = '${err}'
96 r := &GitRepo{}
97 r
98 }
99 assert b.path == ''
100 assert err_msg == "Could not find repo for account name: 'wrong_name2'"
101}
102