mirror of
https://github.com/warppipe/swift-torrent.git
synced 2026-05-28 15:27:20 +00:00
6c8c581517
Full BEP-3 peer wire protocol, BEP-5 DHT, BEP-15 UDP trackers, magnet link support, bencode serialization, rarest-first piece selection, and async session management using SwiftNIO and swift-crypto. Includes 64 passing unit tests. Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
47 lines
1.3 KiB
Swift
47 lines
1.3 KiB
Swift
import Foundation
|
|
|
|
/// LRU piece cache for reducing disk reads.
|
|
public actor PieceCache {
|
|
private var cache: [Int: Data] // piece index -> data
|
|
private var accessOrder: [Int] // LRU order (most recent at end)
|
|
private let maxPieces: Int
|
|
|
|
public init(maxPieces: Int = 64) {
|
|
self.cache = [:]
|
|
self.accessOrder = []
|
|
self.maxPieces = maxPieces
|
|
}
|
|
|
|
/// Get a piece from cache.
|
|
public func get(_ pieceIndex: Int) -> Data? {
|
|
guard let data = cache[pieceIndex] else { return nil }
|
|
// Move to end (most recently used)
|
|
accessOrder.removeAll { $0 == pieceIndex }
|
|
accessOrder.append(pieceIndex)
|
|
return data
|
|
}
|
|
|
|
/// Put a piece into cache.
|
|
public func put(_ pieceIndex: Int, data: Data) {
|
|
cache[pieceIndex] = data
|
|
accessOrder.removeAll { $0 == pieceIndex }
|
|
accessOrder.append(pieceIndex)
|
|
|
|
// Evict oldest if over capacity
|
|
while cache.count > maxPieces, let oldest = accessOrder.first {
|
|
cache.removeValue(forKey: oldest)
|
|
accessOrder.removeFirst()
|
|
}
|
|
}
|
|
|
|
/// Clear the cache.
|
|
public func clear() {
|
|
cache.removeAll()
|
|
accessOrder.removeAll()
|
|
}
|
|
|
|
public func count() -> Int {
|
|
cache.count
|
|
}
|
|
}
|