Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 2 additions & 10 deletions Benchmarks/Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

11 changes: 1 addition & 10 deletions Package.resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 0 additions & 2 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ let package = Package(
],
dependencies: [
.package(url: "https://github.com/apple/swift-algorithms.git", from: "1.0.0"),
.package(url: "https://github.com/adam-fowler/async-collections", from: "0.0.1"),
.package(url: "https://github.com/apple/swift-nio.git", from: "2.84.0"),
],
targets: [
Expand All @@ -27,7 +26,6 @@ let package = Package(
name: "AsyncDataLoader",
dependencies: [
.product(name: "Algorithms", package: "swift-algorithms"),
.product(name: "AsyncCollections", package: "async-collections"),
]
),
.testTarget(
Expand Down
17 changes: 14 additions & 3 deletions Sources/AsyncDataLoader/DataLoader.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import Algorithms
import AsyncCollections

public enum DataLoaderValue<T: Sendable>: Sendable {
case success(T)
Expand Down Expand Up @@ -115,7 +114,19 @@ public actor DataLoader<Key: Hashable & Sendable, Value: Sendable> {
return []
}

return try await keys.concurrentMap { try await self.load(key: $0) }
// This buffer pointer allows us to initialize a pre-sized non-nullable list
// that we can populate by index as `load` results stream in asyncronously
let buffer = UnsafeMutableBufferPointer<Value>.allocate(capacity: keys.count)
try await withThrowingTaskGroup { group in
for (index, element) in keys.enumerated() {
group.addTask {
let result = try await self.load(key: element)
buffer[index] = result
}
}
try await group.waitForAll()
}
return Array(buffer)
}

/// Clears the value at `key` from the cache, if it exists. Returns itself for
Expand Down Expand Up @@ -175,7 +186,7 @@ public actor DataLoader<Key: Hashable & Sendable, Value: Sendable> {
// If a maxBatchSize was provided and the queue is longer, then segment the
// queue into multiple batches, otherwise treat the queue as a single batch.
if let maxBatchSize = options.maxBatchSize, maxBatchSize > 0, maxBatchSize < batch.count {
try await batch.chunks(ofCount: maxBatchSize).asyncForEach { slicedBatch in
for slicedBatch in batch.chunks(ofCount: maxBatchSize) {
try await self.executeBatch(batch: Array(slicedBatch))
}
} else {
Expand Down
Loading