Challenge A
Build a new type, Image, that represents a simple image. It should also provide mutating functions that apply modifications to the image. Use copy-on-write to economize use of memory in the case where a user defines a large array of these identical images, and does not mutate any of them.
To get you started, assume you are using the following Pixels class for the raw storage.
private class Pixels { let size: Int
let storage: UnsafeMutablePointer<UInt8>
init(size: Int, value: UInt8) { self.size = size
storage = UnsafeMutablePointer<UInt8>.allocate(capacity: size) storage.initialize(from: repeatElement(value, count: size))
}
init(pixels: Pixels) { self.size = pixels.size
storage = UnsafeMutablePointer<UInt8>.allocate(capacity: size) storage.initialize(from: pixels.storage, count: pixels.size)
}
subscript(offset: Int) -> UInt8 { get {
return storage[offset]
}
set {
storage[offset] = newValue
}
}
deinit { storage.deallocate(capacity: size)
}
}
Your image should be able to set and get individual pixel values as well as set all the values at once. Typical usage:
image1[0,0] | // -> | 0 |
---|---|---|
image1[0,0] | = 100 | |
image1[0,0] | // -> | 100 |
image1[1,1] | // -> | 0 |