Skip to content

Instantly share code, notes, and snippets.

@JadenGeller
JadenGeller / AdaptiveRangeBuffer.swift
Last active March 11, 2024 05:11
useful for buffering models for a scroll view!
// import https://gist.github.com/JadenGeller/66585051f8de54d9f2a3df1acfd87c32#file-pinnedcollection-swift
import DequeModule
struct AdaptiveRangeBuffer<Index: Strideable, Element>: RandomAccessCollection, MutableCollection where Index.Stride == Int {
var storage: PinnedCollection<Deque<Element>, Index>
var defaultValue: (Index) -> Element
var willRemoveRange: (Slice<Self>) -> Void
init(indices: Range<Index>, defaultValue: @escaping (Index) -> Element, willRemoveRange: @escaping (Slice<Self>) -> Void = { _ in }) {
self.defaultValue = defaultValue
@JadenGeller
JadenGeller / TemporarilyUnhiddenAssets.Swift
Created February 28, 2024 02:05
Helper to temporarily unhide assets (for working around bug in PhotoKit where cloud ID of hidden assets cannot be accessed)
extension PHPhotoLibrary {
// RADAR: https://feedbackassistant.apple.com/feedback/13660931
func withTemporarilyUnhiddenAssets<Success>(_ assets: [PHAsset], _ block: () async throws -> Success) async throws -> Success {
var collectionPlaceholder: PHObjectPlaceholder?
try await performChanges {
let collectionChange = PHAssetCollectionChangeRequest.creationRequestForAssetCollection(withTitle: "Temporarily Unhidden Assets")
collectionPlaceholder = collectionChange.placeholderForCreatedAssetCollection
collectionChange.insertAssets(assets as NSArray, at: IndexSet((0...).prefix(assets.count)))
for asset in assets {
precondition(asset.isHidden)
@JadenGeller
JadenGeller / RequestBatcher.swift
Created February 27, 2024 22:40
Request batcher using Swift async
actor RequestBatcher<Request, Response> {
var maxBatch: Int
var maxDelay: Duration
var priority: TaskPriority?
var dispatchBatch: ([Request]) async -> [Result<Response, Error>]
init(maxBatch: Int, maxDelay: Duration, dispatchBatch: @escaping ([Request]) async -> [Result<Response, Error>]) {
self.maxBatch = maxBatch
self.maxDelay = maxDelay
self.dispatchBatch = dispatchBatch
@JadenGeller
JadenGeller / Pipeline.swift
Created January 21, 2024 05:37
Parallelize sequential steps in a pipeline with streaming inputs
protocol PipelineStep {
associatedtype Context
associatedtype Downstream: PipelineStep
func step(with context: Context) async throws -> Downstream
}
protocol IdleCheckablePipelinewStep: PipelineStep {
var isIdle: Bool { get }
}
@JadenGeller
JadenGeller / BoundsSegmentedSequence.swift
Last active January 4, 2024 03:14
Efficiently split a sorted sequence with a list of sorted bounds
extension RandomAccessCollection {
/// A sequence that partitions a sorted collection into non-overlapping segments based on a sorted sequence of boundaries.
///
/// If N bounds are provided, the resulting sequence contains N + 1 segments, since the segment before the first boundary
/// and the segment after the last boundary are both included.
///
/// - Parameter bounds: A sequence of bounds used to partition the collection.
/// - Parameter areInIncreasingOrder: A predicate that determines whether an element should be included
/// in the segment before the boundary.
/// - Returns: A sequence of collection subseqences partitioned by the given bounds.
@JadenGeller
JadenGeller / DragModifier.swift
Last active December 30, 2023 07:33
NSFilePromiseProvider with SwiftUI, to drag a file that's loaded asynchronously
import SwiftUI
import UniformTypeIdentifiers
struct FileDragProvider: NSViewRepresentable {
var filePromise: FilePromise
var preview: PlatformImage
class NSViewType: NSView, NSFilePromiseProviderDelegate, NSDraggingSource {
var filePromise: FilePromise
var preview: PlatformImage
@JadenGeller
JadenGeller / UnificationSystem.swift
Last active December 17, 2023 00:43
Union-Find disjoint-set data structure in Swift
public protocol UnificationSystemProtocol {
associatedtype Variable
mutating func makeFreshVariable() -> Variable
mutating func canonicalVariable(for variable: Variable) -> Variable
@discardableResult
mutating func unify(_ first: Variable, _ second: Variable) -> Bool
}
public struct UnificationSystem: UnificationSystemProtocol {
public typealias Variable = Int
protocol Lattice {
static func join(_ lhs: Self, _ rhs: Self) -> Self
static func meet(_ lhs: Self, _ rhs: Self) -> Self
}
extension Lattice {
mutating func join(with other: Self) {
self = .join(self, other)
}
mutating func meet(with other: Self) {
@JadenGeller
JadenGeller / BufferLoader.swift
Created November 18, 2023 02:07
BufferLoader
struct BufferLoader {
var buffer: UnsafeRawBufferPointer
var byteOffset: Int = 0
mutating func loadUnaligned<T>(as type: T.Type) -> T {
defer { byteOffset += MemoryLayout<T>.size }
return buffer.loadUnaligned(fromByteOffset: byteOffset, as: T.self)
}
}
extension UnsafeRawBufferPointer {
@JadenGeller
JadenGeller / Semaphore.swift
Created November 17, 2023 19:09
Semaphore using Swift async
actor Semaphore {
private var capacity: Int {
didSet {
assert(capacity >= 0)
}
}
struct Waiter {
var priority: TaskPriority
var continuation: CheckedContinuation<Void, Never>
}