Skip to content

Commit 0f3c884

Browse files
authored
Merge pull request #215 from alexzielenski/schema-copy
add CopyInto method to schema.Schema
2 parents 73412af + f345637 commit 0f3c884

File tree

2 files changed

+63
-0
lines changed

2 files changed

+63
-0
lines changed

schema/elements.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,3 +259,25 @@ func (s *Schema) Resolve(tr TypeRef) (Atom, bool) {
259259
}
260260
return tr.Inlined, true
261261
}
262+
263+
// Clones this instance of Schema into the other
264+
// If other is nil this method does nothing.
265+
// If other is already initialized, overwrites it with this instance
266+
// Warning: Not thread safe
267+
func (s Schema) CopyInto(dst *Schema) {
268+
if dst == nil {
269+
return
270+
}
271+
272+
// Schema type is considered immutable so sharing references
273+
dst.Types = s.Types
274+
275+
if s.m != nil {
276+
// If cache is non-nil then the once token had been consumed.
277+
// Must reset token and use it again to ensure same semantics.
278+
dst.once = sync.Once{}
279+
dst.once.Do(func() {
280+
dst.m = s.m
281+
})
282+
}
283+
}

schema/elements_test.go

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -120,3 +120,44 @@ func TestResolve(t *testing.T) {
120120
})
121121
}
122122
}
123+
124+
func TestCopyInto(t *testing.T) {
125+
existing := "existing"
126+
notExisting := "not-existing"
127+
a := Atom{List: &List{}}
128+
129+
tests := []struct {
130+
testName string
131+
schemaTypeDefs []TypeDef
132+
typeRef TypeRef
133+
}{
134+
{"noNamedType", nil, TypeRef{Inlined: a}},
135+
{"notExistingNamedType", nil, TypeRef{NamedType: &notExisting}},
136+
{"existingNamedType", []TypeDef{{Name: existing, Atom: a}}, TypeRef{NamedType: &existing}},
137+
}
138+
139+
for _, tt := range tests {
140+
t.Run(tt.testName, func(t *testing.T) {
141+
t.Parallel()
142+
s := Schema{
143+
Types: tt.schemaTypeDefs,
144+
}
145+
146+
theCopy := Schema{}
147+
s.CopyInto(&theCopy)
148+
149+
if !reflect.DeepEqual(s, theCopy) {
150+
t.Fatal("")
151+
}
152+
153+
// test after resolve
154+
_, _ = s.Resolve(tt.typeRef)
155+
theCopy = Schema{}
156+
s.CopyInto(&theCopy)
157+
158+
if !reflect.DeepEqual(s, theCopy) {
159+
t.Fatal("")
160+
}
161+
})
162+
}
163+
}

0 commit comments

Comments
 (0)