Skip to content

Commit 19c7884

Browse files
committed
[cxx-interop] Allow creating Dictionary from std::map
This adds an initializer to `Swift.Dictionary` that takes an instance of `std::map` or `std::unordered_map`. rdar://155050682
1 parent 54a8a86 commit 19c7884

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

stdlib/public/Cxx/CxxDictionary.swift

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -253,3 +253,18 @@ extension CxxDictionary {
253253
return result
254254
}
255255
}
256+
257+
extension Dictionary {
258+
@inlinable
259+
public init(_ dictionary: some CxxDictionary<Key, Value>) {
260+
self.init()
261+
262+
var it = dictionary.__beginUnsafe()
263+
let endIterator = dictionary.__endUnsafe()
264+
while it != endIterator {
265+
self[it.pointee.first] = it.pointee.second
266+
it = it.successor()
267+
}
268+
withExtendedLifetime(dictionary) {}
269+
}
270+
}

test/Interop/Cxx/stdlib/use-std-map.swift

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -132,6 +132,39 @@ StdMapTestSuite.test("UnorderedMap.init(grouping:by:)") {
132132
expectEqual(m[3]?.size(), 6)
133133
}
134134

135+
StdMapTestSuite.test("Dictionary<CInt, CInt>.init(_: Map)") {
136+
let cxxMap0 = Map()
137+
let swiftMap0 = Dictionary<CInt, CInt>(cxxMap0)
138+
expectTrue(swiftMap0.isEmpty)
139+
140+
let cxxMap1 = initMap()
141+
let swiftMap1 = Dictionary<CInt, CInt>(cxxMap1)
142+
expectEqual(swiftMap1, [1 : 3, 2 : 2, 3 : 3])
143+
}
144+
145+
StdMapTestSuite.test("Dictionary<CInt, CInt>.init(_: UnorderedMap)") {
146+
let cxxMap0 = UnorderedMap()
147+
let swiftMap0 = Dictionary<CInt, CInt>(cxxMap0)
148+
expectTrue(swiftMap0.isEmpty)
149+
150+
let cxxMap1 = initUnorderedMap()
151+
let swiftMap1 = Dictionary<CInt, CInt>(cxxMap1)
152+
expectEqual(swiftMap1, [1 : 3, 2 : 2, 3 : 3])
153+
}
154+
155+
StdMapTestSuite.test("Dictionary<std.string, std.string>.init(_: MapStrings)") {
156+
let cxxMap0 = MapStrings()
157+
let swiftMap0 = Dictionary<std.string, std.string>(cxxMap0)
158+
expectTrue(swiftMap0.isEmpty)
159+
160+
var cxxMap1 = MapStrings()
161+
cxxMap1[std.string("abc")] = std.string("def")
162+
cxxMap1[std.string("890")] = std.string("3210")
163+
let swiftMap1 = Dictionary<std.string, std.string>(cxxMap1)
164+
expectEqual(swiftMap1, [std.string("abc") : std.string("def"),
165+
std.string("890") : std.string("3210")])
166+
}
167+
135168
StdMapTestSuite.test("Map.subscript") {
136169
// This relies on the `std::map` conformance to `CxxDictionary` protocol.
137170
var m = initMap()

0 commit comments

Comments
 (0)