|
| 1 | +//===--- ArrayImageSource.swift - An image source backed by an Array -------===// |
| 2 | +// |
| 3 | +// This source file is part of the Swift.org open source project |
| 4 | +// |
| 5 | +// Copyright (c) 2023 Apple Inc. and the Swift project authors |
| 6 | +// Licensed under Apache License v2.0 with Runtime Library Exception |
| 7 | +// |
| 8 | +// See https://swift.org/LICENSE.txt for license information |
| 9 | +// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors |
| 10 | +// |
| 11 | +//===----------------------------------------------------------------------===// |
| 12 | +// |
| 13 | +// Defines ArrayImageSource, an image source that is backed by a Swift Array. |
| 14 | +// |
| 15 | +//===----------------------------------------------------------------------===// |
| 16 | + |
| 17 | +import Swift |
| 18 | + |
| 19 | +@_implementationOnly import OS.Libc |
| 20 | + |
| 21 | +enum ArrayImageSourceError: Error { |
| 22 | + case outOfBoundsRead(UInt64, UInt64) |
| 23 | +} |
| 24 | + |
| 25 | +struct ArrayImageSource<T>: ImageSource { |
| 26 | + private var array: Array<T> |
| 27 | + |
| 28 | + public init(array: Array<T>) { |
| 29 | + self.array = array |
| 30 | + } |
| 31 | + |
| 32 | + public var isMappedImage: Bool { return false } |
| 33 | + public var path: String? { return nil } |
| 34 | + public var bounds: Bounds? { |
| 35 | + return Bounds(base: 0, size: Size(array.count * MemoryLayout<T>.stride)) |
| 36 | + } |
| 37 | + |
| 38 | + public func fetch<U>(from addr: Address, |
| 39 | + into buffer: UnsafeMutableBufferPointer<U>) throws { |
| 40 | + try array.withUnsafeBytes{ |
| 41 | + let size = Size($0.count) |
| 42 | + let requested = Size(buffer.count * MemoryLayout<U>.stride) |
| 43 | + if addr > size || requested > size - addr { |
| 44 | + throw ArrayImageSourceError.outOfBoundsRead(addr, requested) |
| 45 | + } |
| 46 | + |
| 47 | + memcpy(buffer.baseAddress!, $0.baseAddress! + Int(addr), Int(requested)) |
| 48 | + } |
| 49 | + } |
| 50 | +} |
0 commit comments