Skip to content

Commit 2dbd83c

Browse files
committed
Add a merge method to Metadata
1 parent 74d0848 commit 2dbd83c

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed

Sources/GRPCCore/Metadata.swift

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -170,6 +170,15 @@ public struct Metadata: Sendable, Hashable {
170170
internal mutating func addValue(_ value: Value, forKey key: String) {
171171
self.elements.append(.init(key: key, value: value))
172172
}
173+
174+
/// Merge another instance of `Metadata` into this one.
175+
///
176+
/// - Parameter other: the `Metadata` which key-value pairs should be merged into this one.
177+
public mutating func merge(_ other: Metadata) {
178+
for (key, value) in other {
179+
self.addValue(value, forKey: key)
180+
}
181+
}
173182

174183
/// Removes all values associated with the given key.
175184
///

Tests/GRPCCoreTests/MetadataTests.swift

Lines changed: 48 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -252,4 +252,52 @@ struct MetadataTests {
252252
#expect(self.metadata == ["key1": "value1", "key3": "value1"])
253253
}
254254
}
255+
256+
@Suite("Merge")
257+
struct Merge {
258+
var metadata: Metadata = [
259+
"key1": "value1-1",
260+
"key2": "value2",
261+
"key3": "value3",
262+
]
263+
var otherMetadata: Metadata = [
264+
"key4": "value4",
265+
"key5": "value5",
266+
]
267+
268+
@Test("Where key is already present with a different value")
269+
mutating func mergeWhereKeyIsAlreadyPresentWithDifferentValue() async throws {
270+
self.otherMetadata.addString("value1-2", forKey: "key1")
271+
self.metadata.merge(otherMetadata)
272+
273+
#expect(self.metadata == [
274+
"key1": "value1-1",
275+
"key2": "value2",
276+
"key3": "value3",
277+
"key4": "value4",
278+
"key5": "value5",
279+
"key1": "value1-2",
280+
])
281+
}
282+
283+
@Test("Where key is already present with same value")
284+
mutating func mergeWhereKeyIsAlreadyPresentWithSameValue() async throws {
285+
self.otherMetadata.addString("value1-1", forKey: "key1")
286+
self.metadata.merge(otherMetadata)
287+
288+
#expect(self.metadata == [
289+
"key1": "value1-1",
290+
"key2": "value2",
291+
"key3": "value3",
292+
"key4": "value4",
293+
"key5": "value5",
294+
"key1": "value1-1",
295+
])
296+
}
297+
298+
@Test("Where key is not already present")
299+
func mergeWhereKeyIsNotAlreadyPresent() async throws {
300+
301+
}
302+
}
255303
}

0 commit comments

Comments
 (0)