Files
swift-torrent/Sources/SwiftTorrent/Storage/PieceCache.swift
T
Chad Paulson 6c8c581517 Implement SwiftTorrent: pure Swift BitTorrent library
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>
2026-01-29 04:17:43 -06:00

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
}
}