1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Collections open source project
//
// Copyright (c) 2021 - 2024 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
//
//===----------------------------------------------------------------------===//
#if !COLLECTIONS_SINGLE_MODULE
import InternalCollectionsUtilities
#endif
extension OrderedDictionary {
/// Creates an empty dictionary.
///
/// This initializer is equivalent to initializing with an empty dictionary
/// literal.
///
/// - Complexity: O(1)
@inlinable
@inline(__always)
public init() {
self._keys = OrderedSet()
self._values = []
}
/// Creates an empty dictionary with preallocated space for at least the
/// specified number of elements.
///
/// Use this initializer to avoid intermediate reallocations of a dictionary's
/// storage buffer when you know in advance how many elements you'll insert
/// into it after creation.
///
/// If you have a good idea of the expected working size of the dictionary,
/// calling this initializer with `persistent` set to true can sometimes
/// improve performance by eliminating churn due to repeated rehashings when
/// the dictionary temporarily shrinks below its regular size. You can cancel
/// any capacity you've previously reserved by persistently reserving a
/// capacity of zero. (This also shrinks the hash table to the ideal size for
/// its current number elements.)
///
/// - Parameter minimumCapacity: The minimum number of elements that the newly
/// created dictionary should be able to store without reallocating its
/// storage.
///
/// - Parameter persistent: If set to true, prevent removals from shrinking
/// storage below the specified capacity. By default, removals are allowed
/// to shrink storage below any previously reserved capacity.
///
/// - Complexity: O(`minimumCapacity`)
@inlinable
@inline(__always)
public init(minimumCapacity: Int, persistent: Bool = false) {
self._keys = OrderedSet(minimumCapacity: minimumCapacity, persistent: persistent)
self._values = []
_values.reserveCapacity(minimumCapacity)
}
}
extension OrderedDictionary {
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples with unique keys. Passing a sequence with duplicate
/// keys to this initializer results in a runtime error. If your
/// sequence might have duplicate keys, use the
/// `Dictionary(_:uniquingKeysWith:)` initializer instead.
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
///
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
///
/// - Precondition: The sequence must not have duplicate keys.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` implements high-quality hashing.
@_disfavoredOverload // https://github.com/apple/swift-collections/issues/125
@inlinable
public init(
uniqueKeysWithValues keysAndValues: some Sequence<(key: Key, value: Value)>
) {
if let keysAndValues = _specialize(
keysAndValues, for: Dictionary<Key, Value>.self
) {
self.init(_uncheckedUniqueKeysWithValues: keysAndValues)
return
}
self.init()
reserveCapacity(keysAndValues.underestimatedCount)
for (key, value) in keysAndValues {
guard _keys._append(key).inserted else {
preconditionFailure("Duplicate key: '\(key)'")
}
_values.append(value)
}
}
/// Creates a new dictionary from the key-value pairs in the given sequence.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples with unique keys. Passing a sequence with duplicate
/// keys to this initializer results in a runtime error. If your
/// sequence might have duplicate keys, use the
/// `Dictionary(_:uniquingKeysWith:)` initializer instead.
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
///
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
///
/// - Precondition: The sequence must not have duplicate keys.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` implements high-quality hashing.
@inlinable
public init(
uniqueKeysWithValues keysAndValues: some Sequence<(Key, Value)>
) {
self.init()
reserveCapacity(keysAndValues.underestimatedCount)
for (key, value) in keysAndValues {
guard _keys._append(key).inserted else {
preconditionFailure("Duplicate key: '\(key)'")
}
_values.append(value)
}
}
}
extension OrderedDictionary {
/// Creates a new dictionary from separate sequences of keys and values.
///
/// You use this initializer to create a dictionary when you have two
/// sequences with unique keys and their associated values, respectively.
/// Passing a `keys` sequence with duplicate keys to this initializer results
/// in a runtime error.
///
/// - Parameter keys: A sequence of unique keys.
///
/// - Parameter values: A sequence of values associated with items in `keys`.
///
/// - Returns: A new dictionary initialized with the data in
/// `keys` and `values`.
///
/// - Precondition: The sequence must not have duplicate keys, and `keys` and
/// `values` must contain an equal number of elements.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` implements high-quality hashing.
@inlinable
public init(
uniqueKeys keys: some Sequence<Key>,
values: some Sequence<Value>
) {
let keys = ContiguousArray(keys)
let values = ContiguousArray(values)
precondition(keys.count == values.count,
"Mismatching element counts between keys and values")
self._keys = .init(keys)
self._values = values
precondition(_keys.count == _values.count, "Duplicate keys")
_checkInvariants()
}
}
extension OrderedDictionary {
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// using a combining closure to determine the value for any duplicate keys.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples that might have duplicate keys. As the dictionary is
/// built, the initializer calls the `combine` closure with the current and
/// new values for any duplicate keys. Pass a closure as `combine` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
///
/// let firstValues = OrderedDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (first, _) in first })
/// // ["a": 1, "b": 2]
///
/// let lastValues = OrderedDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (_, last) in last })
/// // ["a": 3, "b": 4]
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs to use for the new
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// key-value pairs, if `Key` implements high-quality hashing.
@_disfavoredOverload // https://github.com/apple/swift-collections/issues/125
@inlinable
@inline(__always)
public init(
_ keysAndValues: some Sequence<(key: Key, value: Value)>,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows {
self.init()
try self.merge(keysAndValues, uniquingKeysWith: combine)
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// using a combining closure to determine the value for any duplicate keys.
///
/// You use this initializer to create a dictionary when you have a sequence
/// of key-value tuples that might have duplicate keys. As the dictionary is
/// built, the initializer calls the `combine` closure with the current and
/// new values for any duplicate keys. Pass a closure as `combine` that
/// returns the value to use in the resulting dictionary: The closure can
/// choose between the two values, combine them to produce a new value, or
/// even throw an error.
///
/// let pairsWithDuplicateKeys = [("a", 1), ("b", 2), ("a", 3), ("b", 4)]
///
/// let firstValues = OrderedDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (first, _) in first })
/// // ["a": 1, "b": 2]
///
/// let lastValues = OrderedDictionary(
/// pairsWithDuplicateKeys,
/// uniquingKeysWith: { (_, last) in last })
/// // ["a": 3, "b": 4]
///
/// - Parameters:
/// - keysAndValues: A sequence of key-value pairs to use for the new
/// dictionary.
/// - combine: A closure that is called with the values for any duplicate
/// keys that are encountered. The closure returns the desired value for
/// the final dictionary.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// key-value pairs, if `Key` implements high-quality hashing.
@inlinable
@inline(__always)
public init(
_ keysAndValues: some Sequence<(Key, Value)>,
uniquingKeysWith combine: (Value, Value) throws -> Value
) rethrows {
self.init()
try self.merge(keysAndValues, uniquingKeysWith: combine)
}
}
extension OrderedDictionary {
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// The arrays in the "values" position of the new dictionary each contain at
/// least one element, with the elements in the same order as the source
/// sequence.
///
/// The following example declares an array of names, and then creates a
/// dictionary from that array by grouping the names by first letter:
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = OrderedDictionary(grouping: students, by: { $0.first! })
/// // ["K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"], "E": ["Efua"]]
///
/// The new `studentsByLetter` dictionary has three entries, with students'
/// names grouped by the keys `"E"`, `"K"`, and `"A"`.
///
/// - Parameters:
/// - values: A sequence of values to group into a dictionary.
/// - keyForValue: A closure that returns a key for each element in
/// `values`.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// values, if `Key` implements high-quality hashing.
@inlinable
public init<S: Sequence>(
grouping values: S,
by keyForValue: (S.Element) throws -> Key
) rethrows where Value: RangeReplaceableCollection, Value.Element == S.Element {
try self.init(_grouping: values, by: keyForValue)
}
/// Creates a new dictionary whose keys are the groupings returned by the
/// given closure and whose values are arrays of the elements that returned
/// each key.
///
/// The arrays in the "values" position of the new dictionary each contain at
/// least one element, with the elements in the same order as the source
/// sequence.
///
/// The following example declares an array of names, and then creates a
/// dictionary from that array by grouping the names by first letter:
///
/// let students = ["Kofi", "Abena", "Efua", "Kweku", "Akosua"]
/// let studentsByLetter = OrderedDictionary(grouping: students, by: { $0.first! })
/// // ["K": ["Kofi", "Kweku"], "A": ["Abena", "Akosua"], "E": ["Efua"]]
///
/// The new `studentsByLetter` dictionary has three entries, with students'
/// names grouped by the keys `"E"`, `"K"`, and `"A"`.
///
/// - Parameters:
/// - values: A sequence of values to group into a dictionary.
/// - keyForValue: A closure that returns a key for each element in
/// `values`.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count of
/// values, if `Key` implements high-quality hashing.
@inlinable
public init<S: Sequence>(
grouping values: S,
by keyForValue: (S.Element) throws -> Key
) rethrows where Value == [S.Element] {
// Note: this extra overload is necessary to make type inference work
// for the `Value` type -- we want it to default to `[S.Element`].
// (https://github.com/apple/swift-collections/issues/139)
try self.init(_grouping: values, by: keyForValue)
}
@inlinable
internal init<S: Sequence>(
_grouping values: S,
by keyForValue: (S.Element) throws -> Key
) rethrows where Value: RangeReplaceableCollection, Value.Element == S.Element {
self.init()
for value in values {
let key = try keyForValue(value)
self.updateValue(forKey: key, default: Value()) { array in
array.append(value)
}
}
}
}
extension OrderedDictionary {
@inlinable
internal init(
_uncheckedUniqueKeysWithValues keysAndValues:
some Sequence<(key: Key, value: Value)>
) {
self.init()
reserveCapacity(keysAndValues.underestimatedCount)
for (key, value) in keysAndValues {
_keys._appendNew(key)
_values.append(value)
}
_checkInvariants()
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// which must not contain duplicate keys.
///
/// In optimized builds, this initializer does not verify that the keys are
/// actually unique. This makes creating the dictionary somewhat faster if you
/// know for sure that the elements are unique (e.g., because they come from
/// another collection with guaranteed-unique members, such as a
/// `Dictionary`). However, if you accidentally call this initializer with
/// duplicate members, it can return a corrupt dictionary value that may be
/// difficult to debug.
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
///
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
///
/// - Precondition: The sequence must not have duplicate keys.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` implements high-quality hashing.
@_disfavoredOverload // https://github.com/apple/swift-collections/issues/125
@inlinable
public init(
uncheckedUniqueKeysWithValues keysAndValues:
some Sequence<(key: Key, value: Value)>
) {
#if DEBUG
self.init(uniqueKeysWithValues: keysAndValues)
#else
self.init(_uncheckedUniqueKeysWithValues: keysAndValues)
#endif
}
/// Creates a new dictionary from the key-value pairs in the given sequence,
/// which must not contain duplicate keys.
///
/// In optimized builds, this initializer does not verify that the keys are
/// actually unique. This makes creating the dictionary somewhat faster if you
/// know for sure that the elements are unique (e.g., because they come from
/// another collection with guaranteed-unique members, such as a
/// `Dictionary`). However, if you accidentally call this initializer with
/// duplicate members, it can return a corrupt dictionary value that may be
/// difficult to debug.
///
/// - Parameter keysAndValues: A sequence of key-value pairs to use for
/// the new dictionary. Every key in `keysAndValues` must be unique.
///
/// - Returns: A new dictionary initialized with the elements of
/// `keysAndValues`.
///
/// - Precondition: The sequence must not have duplicate keys.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` implements high-quality hashing.
@inlinable
public init(
uncheckedUniqueKeysWithValues keysAndValues: some Sequence<(Key, Value)>
) {
// Add tuple labels
let keysAndValues = keysAndValues.lazy.map { (key: $0.0, value: $0.1) }
self.init(uncheckedUniqueKeysWithValues: keysAndValues)
}
}
extension OrderedDictionary {
/// Creates a new dictionary from separate sequences of unique keys and
/// associated values.
///
/// In optimized builds, this initializer does not verify that the keys are
/// actually unique. This makes creating the dictionary somewhat faster if you
/// know for sure that the elements are unique (e.g., because they come from
/// another collection with guaranteed-unique members, such as a
/// `Dictionary`). However, if you accidentally call this initializer with
/// duplicate members, it can return a corrupt dictionary value that may be
/// difficult to debug.
///
/// - Parameter keys: A sequence of unique keys.
///
/// - Parameter values: A sequence of values associated with items in `keys`.
///
/// - Returns: A new dictionary initialized with the data in
/// `keys` and `values`.
///
/// - Precondition: The sequence must not have duplicate keys, and `keys` and
/// `values` must contain an equal number of elements.
///
/// - Complexity: Expected O(*n*) on average, where *n* is the count if
/// key-value pairs, if `Key` implements high-quality hashing.
@inlinable
@inline(__always)
public init(
uncheckedUniqueKeys keys: some Sequence<Key>,
values: some Sequence<Value>
) {
#if DEBUG
self.init(uniqueKeys: keys, values: values)
#else
self._keys = .init(uncheckedUniqueElements: keys)
self._values = .init(values)
precondition(_keys.count == _values.count)
_checkInvariants()
#endif
}
}
|